summaryrefslogtreecommitdiff
path: root/src/main/scala/io/trygvis/cj/Views.scala
blob: 869677e3ab88c2a7647caf48c36697dcf246e55f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
package io.trygvis.cj

import scala.collection.JavaConversions._
import scala.xml.{Group, NodeSeq, Elem}
import java.net.{MalformedURLException, URL, URI, URLEncoder}
import net.hamnaberg.json.collection.{Property, Link, Json4sHelpers, JsonCollection}
import net.hamnaberg.json.collection.Render.IMAGE
import org.json4s.native.JsonMethods
import java.io.{PrintWriter, StringWriter, Writer}

class Views(baseUrl: String) {

  val notSet = <i>Not set</i>

  def tryLink(s: String) = try {
    val url = new URL(s)
    <a href={url.toExternalForm}>{s}</a>
  } catch {
    case _: MalformedURLException => <xml:group>{s}</xml:group>
  }

  def render(uri: URI) = {
    val s = uri.toURL.toExternalForm
    baseUrl + "render?url=" + URLEncoder.encode(s, "utf-8")
  }

  def delete(uri: URI) = {
    val s = uri.toURL.toExternalForm
    baseUrl + "render?url=" + URLEncoder.encode(s, "utf-8") + "&action=delete"
  }

  def examples: Array[Elem] = Array("minimal", "collection", "item", "queries", "template", "error") map { name =>
    val cj = baseUrl + "examples/from-spec/" + name + ".collection+json"
    <a href={render(URI.create(cj))}>{name}</a>
  }

  def getStackTrace(aThrowable: Throwable) = {
    val result: Writer = new StringWriter()
    val printWriter: PrintWriter = new PrintWriter(result)
    aThrowable.printStackTrace(printWriter)
    result.toString
  }

  /*
  mixin get_name(link, prefix, i)
  - var name = typeof link.name == 'string' ? link.name : undefined
  - var prompt = typeof link.prompt == 'string' ? link.prompt : undefined
  - var prefix = typeof prefix == 'string' ? prefix + ': ' : ''
  |#{prefix + (name || prompt || '#' + i)}

   */
  def getName(link: Link, prefix: String, i: Int) = {
//    var name = link.name
    val name = Json4sHelpers.getAsString(link.underlying, "name")
    prefix + name.orElse(link.prompt).getOrElse("#" + i)
  }

  def index = {
    def innerContent =
      <div class='hero-unit'>
        <h1>&#x2764; Collection+JSON &#x2764;</h1>

        <!-- spacers -->
        <div class='row-fluid'> &nbsp;</div>
        <div class='row-fluid'> &nbsp;</div>

        <div class='row-fluid'>
          <div class='span12 input-append'>
            <form action='/render' class='form-search'>
              <input type='text' name='url' placeholder='Resource to explore' class='span11'/>
              <button type='submit' class='btn btn-primary'>Explore</button>
            </form>
          </div>
        </div>
      </div>
      <div class="row-fluid">
        <div class="span4">
          <h2>About</h2>
          <p>This is an interactive explorer for the Collection+JSON hypermedia. Give it an URL and it will render is as good as it can.</p>
          <p>
            The purpose is twofold: it is a useful tool to inspect
            collections while developing or debugging an application. At
            the same time it's useful to show the power of
            <a href='http://en.wikipedia.org/wiki/Hypermedia'>hypermedia</a>
            by showing how much a generic user agent can do by using
            only the generic Collection+JSON specification and not
            knowing anything about your application.
          </p>
          <h3>See also</h3>
          <p>
            There's a growing C+J community that's discussing on the <a href="https://groups.google.com/forum/#!forum/collectionjson">Google Group</a>.
          </p>
          <p>
            Reading the (quite light) <a href="http://amundsen.com/media-types/collection/">formal specification</a> is
            useful. It also has a tutorial and some examples.
          </p>
        </div>
        <div class="span4">
          <h2>Using</h2>
          <p>
            Feel to use this service! However, note that it's running on a free
            <a href="http://heroku.com">Heroku</a>
            instance so it might fail, be slow or otherwise useless.</p>
          <p>
            If you want to run it against your own local servers you can either run it yourself, or use apps like
            <a href="http://localtunnel.com">localtunnel.com</a> to make your application publicly available.
          </p>
          <h3>The Source Code</h3>
          <p>
            The source code is available
            <a href="http://trygvis.dyndns.org/~trygvis/git/2012/06/collection+json-explorer.git">here</a>.
          </p>
        </div>
        <div class="span4">
          <h2>Examples</h2>
          <p>
            The <a href="http://employee.herokuapp.com">Employee</a> application is a set of resources with employees
            and departments. The application was made specifically for this explorer:
            <a href={render(URI.create("http://employee.herokuapp.com"))} class="label label-info">explore now!</a>
          </p>
          <p>The specification contains a few example collections too which
            you can explore:
          </p>
          <ul>
            {examples.map {example => <li>{example}</li>}}
          </ul>
        </div>
      </div>
    ;

    def content = <div class="offset2 span10">{innerContent}</div>
    layout(content, None)
  }

  def data(url: URI, params: Map[String, Seq[String]], result: Either[Throwable, JsonCollection], res: CjResponse) = {

    def href(uri: URI) = {
//      val splits = uri.getPath.split('/')
//      for split in splits
//      a(href=urlgenerator.render(split[1]), title='Explore #{split[1]}') #{split[0]}
      uri.toURL.toExternalForm
    }

    def link(link: Link) = {
      val name = Json4sHelpers.getAsString(link.underlying, "name")
      <xml:group>
      <div>
        <a class="btn btn-primary btn-mini" href={render(link.href)}>Explore</a>
        <a class="btn btn-primary btn-mini" href={link.href.toURL.toExternalForm}>Raw</a>
      </div>
      <dl>
        <dt>href</dt>
        <dd><div>{href(link.href)}</div></dd>
        <dt>rel</dt>
        <dd>{tryLink(link.rel)}</dd>
        <dt>name</dt>
        <dd>{name.getOrElse(notSet)}</dd>
        <dt>prompt</dt>
        <dd>{link.prompt.getOrElse(notSet)}</dd>
        <dt>render</dt>
        <dd>{link.render.map(_.name).getOrElse(notSet)}</dd>
        {link.render match {
          case Some(IMAGE) =>
            <dt>Image</dt>
            <dd>
              <a href={link.href.toURL.toExternalForm}>
                <img src={link.href.toURL.toExternalForm} alt={name.getOrElse("")} title={name.getOrElse("")}/>
              </a>
            </dd>
          case _ =>
            NodeSeq.Empty
        }}
      </dl>
      </xml:group>
    }

    def meta(implicit cj: JsonCollection) = <xml:group>
      <div class="row-fluid">
        <div class="span12">
          <dl>
            <dt>version</dt>
            <dd>{cj.version.name}</dd>
            <dt>href</dt>
            <dd>
              <div>{href(cj.href)}</div>
            </dd>
          </dl>
        </div>
      </div>
      <div class="row-fluid">
        <div class="span12">
          <p>
            <a class="btn btn-primary" href={render(cj.href)}>Explore</a>
            <a class="btn btn-primary" href={cj.href.toURL.toExternalForm}>Raw</a>
            <a class="btn btn-danger" href={delete(cj.href)}>Delete</a>
            <form action='http://redbot.org'>
              <input name='uri' value={url.toURL.toExternalForm} type='hidden'/>
              <input name='req_hdr' value='Accept: application/vnd.collection+json' type='hidden'/>
              <button class='btn btn-primary' type='submit'>Check with redbot.org</button>
            </form>
          </p>
        </div>
      </div>
      {cj.links match {
        case Nil =>
          NodeSeq.Empty
        case _ =>
          <xml:group>
            <h2>Collection Links</h2>
            {cj.links.zipWithIndex.map { case (l, i) =>
              val name = Json4sHelpers.getAsString(l.underlying, "name")
              val title = l.prompt.orElse(name) match {
                case Some(t) => ": " + t
                case _ => ""
              }
              Group(Seq(<h3 id={"link-#" + (i + 1)}>{"Collection link #" + (i + 1) + title}</h3>, link(l)))
            }}
          </xml:group>
      }}
      </xml:group>

    // TODO: If the collection has prev/next links, add buttons to automaticaly navigate those.
    // TODO: Add ability to show the raw part of the collection.
    def items(cj: JsonCollection) = {

      def itemLinks(cj: JsonCollection) = {
        val first = cj.findLinkByRel("first")
        val prev = cj.findLinkByRel("prev")
        val next = cj.findLinkByRel("next")
        val last = cj.findLinkByRel("last")
        if(first.isDefined || prev.isDefined || next.isDefined || last.isDefined) {
          <div class="fluid-row">
            <div class="span12">
              {if(first.isDefined) <a class="btn btn-primary btn-mini" href={render(first.get.href) + "#items"}>First</a>}
              {if(prev.isDefined) <a class="btn btn-primary btn-mini" href={render(prev.get.href) + "#items"}>Previous</a>}
              {if(next.isDefined) <a class="btn btn-primary btn-mini" href={render(next.get.href) + "#items"}>Next</a>}
              {if(last.isDefined) <a class="btn btn-primary btn-mini" href={render(last.get.href) + "#items"}>Last</a>}
            </div>
          </div>
        }
      }

      <xml:group>
        {itemLinks(cj)}
        {
          cj.items.zipWithIndex.map { case (item, i) =>
            val links = item.links
            <div class="item-container">
              <h2 id={"item-" + (i + 1)}>Item #{i + 1}</h2>
              <div class="fluid-row">
                <div class="span12">
                  <p>
                    <a class="btn btn-primary btn-mini" href={render(item.href)}>Explore</a>
                    <a class="btn btn-primary btn-mini" href={item.href.toURL.toExternalForm}>Raw</a>
                    <a class="btn btn-primary btn-mini" onClick='var item = $(this).parentsUntil("#items").last(); item.find(".item-form").toggle(); item.find(".item-data").toggle()'>Edit</a>
                    <a class="btn btn-danger btn-mini" href={delete(item.href)}>Delete</a>
                  </p>
                </div>
              </div>
              <div class="fluid-row">
                <div class="span12">
                  <dl>
                    <dt>href</dt>
                    <dd><div>{href(item.href)}</div></dd>
                  </dl>
                </div>
              </div>
              {if(links.nonEmpty) {
                <xml:group>
                <h3>Item Links</h3>
                {links.zipWithIndex.map { case (l, i2) =>
                  Group(Seq(<h4>Item Link #{i2 + 1}</h4>, link(l)))
                }}
                </xml:group>
              }}
              <h3 class="item-data">Data</h3>
              <div class="item-data fluid-row">
                <div class="span12">
                  <table class="data-table">
                    <!-- d.value is not the correct way to access the value -->
                    {item.data map { d => <tr><th