target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testCanContinue() { DurationCount durationCount = new DurationCount("10"); assertEquals(10L, durationCount.getNumericDuration()); DurationCountTestProgress progress = new DurationCountTestProgress(); for (int i = 0; i < durationCount.getNumericDuration(); i++) { assertTrue(durationCount.canContinue(progress)); progress.increment(); } assertFalse(durationCount.canContinue(progress)); progress.increment(); assertFalse(durationCount.canContinue(progress)); assertEquals("count", durationCount.durationTypeName()); assertEquals("10", durationCount.toString()); assertEquals(durationCount.getCoolDownDuration(), durationCount.getWarmUpDuration()); } | @Override public boolean canContinue(final TestProgress progress) { return progress.messageCount() < count; } | DurationCount implements TestDuration { @Override public boolean canContinue(final TestProgress progress) { return progress.messageCount() < count; } } | DurationCount implements TestDuration { @Override public boolean canContinue(final TestProgress progress) { return progress.messageCount() < count; } DurationCount(final String durationSpec); DurationCount(long count); } | DurationCount implements TestDuration { @Override public boolean canContinue(final TestProgress progress) { return progress.messageCount() < count; } DurationCount(final String durationSpec); DurationCount(long count); @Override boolean canContinue(final TestProgress progress); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); } | DurationCount implements TestDuration { @Override public boolean canContinue(final TestProgress progress) { return progress.messageCount() < count; } DurationCount(final String durationSpec); DurationCount(long count); @Override boolean canContinue(final TestProgress progress); @Override long getNumericDuration(); @Override TestDuration getWarmUpDuration(); @Override TestDuration getCoolDownDuration(); String toString(); @Override String durationTypeName(); static final long WARM_UP_COUNT; } |
@Test public void testRate() { assertEquals(0, WorkerUtils.getExchangeInterval(0)); assertEquals(20000, WorkerUtils.getExchangeInterval(50000)); } | public static long getExchangeInterval(final long rate) { return rate > 0 ? (1_000_000_000L / rate) : 0; } | WorkerUtils { public static long getExchangeInterval(final long rate) { return rate > 0 ? (1_000_000_000L / rate) : 0; } } | WorkerUtils { public static long getExchangeInterval(final long rate) { return rate > 0 ? (1_000_000_000L / rate) : 0; } private WorkerUtils(); } | WorkerUtils { public static long getExchangeInterval(final long rate) { return rate > 0 ? (1_000_000_000L / rate) : 0; } private WorkerUtils(); static long getExchangeInterval(final long rate); static long waitNanoInterval(final long expectedFireTime, final long intervalInNanos); } | WorkerUtils { public static long getExchangeInterval(final long rate) { return rate > 0 ? (1_000_000_000L / rate) : 0; } private WorkerUtils(); static long getExchangeInterval(final long rate); static long waitNanoInterval(final long expectedFireTime, final long intervalInNanos); } |
@Test public void testSaveXmlSuccess() { String path = this.getClass().getResource("/").getPath() + "xunit.success.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); } | public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } |
@Test public void testSaveXmlWithFailure() { String path = this.getClass().getResource("/").getPath() + "xunit.failure.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); Failure failure = new Failure(); failure.setMessage("AMQP Framing Error"); failure.setContent("SUT disconnected"); testRun.setFailure(failure); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); } | public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } |
@Test public void testSave() throws IOException { Sha1Digest sha1Digest = new Sha1Digest(); sha1Digest.save(MESSAGE_FILE); sha1Digest.verify(MESSAGE_FILE); } | public void save(String source) throws IOException { final String digest = calculate(source); final File file = new File(source + "." + HASH_NAME); if (file.exists()) { if (!file.delete()) { throw new IOException("Unable to delete an existent file: " + file.getPath()); } } else { if (!file.createNewFile()) { throw new IOException("Unable to create a new file: " + file.getPath()); } } try (FileOutputStream output = new FileOutputStream(file)) { IOUtils.write(digest, output, Charset.defaultCharset()); } } | Sha1Digest implements MessageDigest { public void save(String source) throws IOException { final String digest = calculate(source); final File file = new File(source + "." + HASH_NAME); if (file.exists()) { if (!file.delete()) { throw new IOException("Unable to delete an existent file: " + file.getPath()); } } else { if (!file.createNewFile()) { throw new IOException("Unable to create a new file: " + file.getPath()); } } try (FileOutputStream output = new FileOutputStream(file)) { IOUtils.write(digest, output, Charset.defaultCharset()); } } } | Sha1Digest implements MessageDigest { public void save(String source) throws IOException { final String digest = calculate(source); final File file = new File(source + "." + HASH_NAME); if (file.exists()) { if (!file.delete()) { throw new IOException("Unable to delete an existent file: " + file.getPath()); } } else { if (!file.createNewFile()) { throw new IOException("Unable to create a new file: " + file.getPath()); } } try (FileOutputStream output = new FileOutputStream(file)) { IOUtils.write(digest, output, Charset.defaultCharset()); } } } | Sha1Digest implements MessageDigest { public void save(String source) throws IOException { final String digest = calculate(source); final File file = new File(source + "." + HASH_NAME); if (file.exists()) { if (!file.delete()) { throw new IOException("Unable to delete an existent file: " + file.getPath()); } } else { if (!file.createNewFile()) { throw new IOException("Unable to create a new file: " + file.getPath()); } } try (FileOutputStream output = new FileOutputStream(file)) { IOUtils.write(digest, output, Charset.defaultCharset()); } } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); } | Sha1Digest implements MessageDigest { public void save(String source) throws IOException { final String digest = calculate(source); final File file = new File(source + "." + HASH_NAME); if (file.exists()) { if (!file.delete()) { throw new IOException("Unable to delete an existent file: " + file.getPath()); } } else { if (!file.createNewFile()) { throw new IOException("Unable to create a new file: " + file.getPath()); } } try (FileOutputStream output = new FileOutputStream(file)) { IOUtils.write(digest, output, Charset.defaultCharset()); } } String calculate(final InputStream inputStream); String calculate(final File file); String calculate(String path); boolean verify(String source); boolean verify(String source, String digest); void save(String source); } |
@Test public void testSaveXmlWithError() { String path = this.getClass().getResource("/").getPath() + "xunit.error.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); Error error = new Error(); error.setMessage("java.lang.NullPointerException"); error.setContent("Maestro worker failed: java.lang.NullPointerException"); testRun.setError(error); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); } | public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } |
@Test public void testSaveXmlSuccessAndProperties() { String path = this.getClass().getResource("/").getPath() + "xunit.success.with.properties.xml"; TestCase warmUpTc = new TestCase(); warmUpTc.setAssertions(1); warmUpTc.setClassName("singlepoint.FixedRate"); warmUpTc.setName("AMQP-s-1024-c-30-ld-10-durable-false"); warmUpTc.setTime(Duration.ofSeconds(5)); TestCase testRun = new TestCase(); testRun.setAssertions(1); testRun.setClassName("singlepoint.FixedRate"); testRun.setName("AMQP-s-1024-c-100-ld-10-durable-false"); testRun.setTime(Duration.ofSeconds(300)); TestSuite testSuite = new TestSuite(); testSuite.setId("0"); testSuite.setTests(1); testSuite.getTestCaseList().add(warmUpTc); testSuite.getTestCaseList().add(testRun); TestSuites testSuites = new TestSuites(); testSuites.getTestSuiteList().add(testSuite); Property messageSize = new Property(); messageSize.setValue("1024"); messageSize.setName("size"); Property pairs = new Property(); pairs.setValue("100"); pairs.setName("pairs"); testSuites.getProperties().getPropertyList().add(messageSize); testSuites.getProperties().getPropertyList().add(pairs); XunitWriter xunitWriter = new XunitWriter(); File outFile = new File(path); xunitWriter.saveToXML(outFile, testSuites); assertTrue(outFile.exists()); } | public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } | XunitWriter { public void saveToXML(final File outputFile, TestSuites testSuites) { Element rootEle = dom.createElement("testsuites"); serializeTestSuites(rootEle, testSuites.getTestSuiteList()); serializeProperties(rootEle, testSuites.getProperties()); dom.appendChild(rootEle); try { Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT, "yes"); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty("{http: tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(outputFile))); } catch (IOException | TransformerException te) { throw new MaestroException(te); } } XunitWriter(); void saveToXML(final File outputFile, TestSuites testSuites); } |
@Test public void testURLPathRewrite() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } | public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } |
@Test public void testURLPathRewriteWithUser() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } | public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } |
@Test public void testURLPathRewriteWithQuery() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } | public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } |
@Test public void testURLPathRewriteWithUserWithQuery() { String originalUrl = "amqp: String expectedUrl = "amqp: String ret = URLUtils.rewritePath(originalUrl, "worker"); assertEquals(expectedUrl, ret); } | public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } | URLUtils { public static String rewritePath(final String inputUrl, final String string) { try { URI url = new URI(inputUrl); final String userInfo = url.getUserInfo(); final String host = url.getHost(); if (host == null) { throw new MaestroException("Invalid URI: null host"); } URI ret; if (host.equals(userInfo)) { ret = new URI(url.getScheme(), null, url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } else { ret = new URI(url.getScheme(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath() + "." + string, url.getQuery(), null); } return ret.toString(); } catch (URISyntaxException e) { throw new MaestroException("Invalid URL: " + string); } } private URLUtils(); static String sanitizeURL(final String url); static String getHostnameFromURL(final String string); static String rewritePath(final String inputUrl, final String string); } |
@Test public void testParse() { assertTrue(ContentStrategyFactory.parse("100") instanceof FixedSizeContent); assertTrue(ContentStrategyFactory.parse("~100") instanceof VariableSizeContent); } | public static ContentStrategy parse(final String sizeSpec) { ContentStrategy ret; if (sizeSpec.startsWith("~")) { ret = new VariableSizeContent(sizeSpec); } else { ret = new FixedSizeContent(sizeSpec); } return ret; } | ContentStrategyFactory { public static ContentStrategy parse(final String sizeSpec) { ContentStrategy ret; if (sizeSpec.startsWith("~")) { ret = new VariableSizeContent(sizeSpec); } else { ret = new FixedSizeContent(sizeSpec); } return ret; } } | ContentStrategyFactory { public static ContentStrategy parse(final String sizeSpec) { ContentStrategy ret; if (sizeSpec.startsWith("~")) { ret = new VariableSizeContent(sizeSpec); } else { ret = new FixedSizeContent(sizeSpec); } return ret; } private ContentStrategyFactory(); } | ContentStrategyFactory { public static ContentStrategy parse(final String sizeSpec) { ContentStrategy ret; if (sizeSpec.startsWith("~")) { ret = new VariableSizeContent(sizeSpec); } else { ret = new FixedSizeContent(sizeSpec); } return ret; } private ContentStrategyFactory(); static ContentStrategy parse(final String sizeSpec); } | ContentStrategyFactory { public static ContentStrategy parse(final String sizeSpec) { ContentStrategy ret; if (sizeSpec.startsWith("~")) { ret = new VariableSizeContent(sizeSpec); } else { ret = new FixedSizeContent(sizeSpec); } return ret; } private ContentStrategyFactory(); static ContentStrategy parse(final String sizeSpec); } |
@Test public void testPrepareContent() { VariableSizeContent content = new VariableSizeContent(100); assertEquals(96, content.minSize()); assertEquals(105, content.maxSize()); for (int i = 0; i < 100; i++) { ByteBuffer buffer = content.prepareContent(); final int length = buffer.remaining(); final int position = buffer.position(); final int offset = buffer.arrayOffset() + position; assertTrue("Generated a buffer starting at offset = " + offset + " with length = " + length + " is invalid", content.minSize() <= length); assertTrue("Generated a buffer starting at offset = " + offset + " with length = " + length + " is invalid", content.maxSize() >= length); } } | @Override public ByteBuffer prepareContent() { final int currentLimit = ThreadLocalRandom.current().nextInt(this.lowerLimitInclusive, this.upperLimitExclusive); buffer.clear(); buffer.limit(currentLimit); return buffer; } | VariableSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { final int currentLimit = ThreadLocalRandom.current().nextInt(this.lowerLimitInclusive, this.upperLimitExclusive); buffer.clear(); buffer.limit(currentLimit); return buffer; } } | VariableSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { final int currentLimit = ThreadLocalRandom.current().nextInt(this.lowerLimitInclusive, this.upperLimitExclusive); buffer.clear(); buffer.limit(currentLimit); return buffer; } VariableSizeContent(int size); VariableSizeContent(final String sizeSpec); } | VariableSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { final int currentLimit = ThreadLocalRandom.current().nextInt(this.lowerLimitInclusive, this.upperLimitExclusive); buffer.clear(); buffer.limit(currentLimit); return buffer; } VariableSizeContent(int size); VariableSizeContent(final String sizeSpec); int minSize(); int maxSize(); @Override ByteBuffer prepareContent(); } | VariableSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { final int currentLimit = ThreadLocalRandom.current().nextInt(this.lowerLimitInclusive, this.upperLimitExclusive); buffer.clear(); buffer.limit(currentLimit); return buffer; } VariableSizeContent(int size); VariableSizeContent(final String sizeSpec); int minSize(); int maxSize(); @Override ByteBuffer prepareContent(); } |
@Test public void testPepareContent() { FixedSizeContent content = new FixedSizeContent(100); for (int i = 0; i < 100; i++) { ByteBuffer buffer = content.prepareContent(); final int length = buffer.remaining(); assertEquals(100, length); } } | @Override public ByteBuffer prepareContent() { return buffer; } | FixedSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { return buffer; } } | FixedSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { return buffer; } FixedSizeContent(int size); FixedSizeContent(final String sizeSpec); } | FixedSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { return buffer; } FixedSizeContent(int size); FixedSizeContent(final String sizeSpec); @Override ByteBuffer prepareContent(); } | FixedSizeContent implements ContentStrategy { @Override public ByteBuffer prepareContent() { return buffer; } FixedSizeContent(int size); FixedSizeContent(final String sizeSpec); @Override ByteBuffer prepareContent(); } |
@Test public void testVariable() { assertEquals("~1024", MessageSize.variable(1024)); } | public static String variable(long value) { return "~" + Long.toString(value); } | MessageSize { public static String variable(long value) { return "~" + Long.toString(value); } } | MessageSize { public static String variable(long value) { return "~" + Long.toString(value); } private MessageSize(); } | MessageSize { public static String variable(long value) { return "~" + Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } | MessageSize { public static String variable(long value) { return "~" + Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } |
@Test public void testCleanExitOnDefault() { WorkerStateInfo wsi = new WorkerStateInfo(); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } | public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } |
@Test public void testFixed() { assertEquals("1024", MessageSize.fixed(1024)); } | public static String fixed(long value) { return Long.toString(value); } | MessageSize { public static String fixed(long value) { return Long.toString(value); } } | MessageSize { public static String fixed(long value) { return Long.toString(value); } private MessageSize(); } | MessageSize { public static String fixed(long value) { return Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } | MessageSize { public static String fixed(long value) { return Long.toString(value); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } |
@Test public void isVariable() { assertTrue(MessageSize.isVariable("~1024")); assertFalse(MessageSize.isVariable("1024")); } | public static boolean isVariable(final String sizeSpec) { return sizeSpec.startsWith("~"); } | MessageSize { public static boolean isVariable(final String sizeSpec) { return sizeSpec.startsWith("~"); } } | MessageSize { public static boolean isVariable(final String sizeSpec) { return sizeSpec.startsWith("~"); } private MessageSize(); } | MessageSize { public static boolean isVariable(final String sizeSpec) { return sizeSpec.startsWith("~"); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } | MessageSize { public static boolean isVariable(final String sizeSpec) { return sizeSpec.startsWith("~"); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } |
@Test public void toSizeFromSpec() { assertEquals(1024, MessageSize.toSizeFromSpec("~1024")); } | public static int toSizeFromSpec(final String sizeSpec) { if (isVariable(sizeSpec)) { return Integer.parseInt(sizeSpec.replace("~", "")); } return Integer.parseInt(sizeSpec); } | MessageSize { public static int toSizeFromSpec(final String sizeSpec) { if (isVariable(sizeSpec)) { return Integer.parseInt(sizeSpec.replace("~", "")); } return Integer.parseInt(sizeSpec); } } | MessageSize { public static int toSizeFromSpec(final String sizeSpec) { if (isVariable(sizeSpec)) { return Integer.parseInt(sizeSpec.replace("~", "")); } return Integer.parseInt(sizeSpec); } private MessageSize(); } | MessageSize { public static int toSizeFromSpec(final String sizeSpec) { if (isVariable(sizeSpec)) { return Integer.parseInt(sizeSpec.replace("~", "")); } return Integer.parseInt(sizeSpec); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } | MessageSize { public static int toSizeFromSpec(final String sizeSpec) { if (isVariable(sizeSpec)) { return Integer.parseInt(sizeSpec.replace("~", "")); } return Integer.parseInt(sizeSpec); } private MessageSize(); static String variable(long value); static String fixed(long value); static boolean isVariable(final String sizeSpec); static int toSizeFromSpec(final String sizeSpec); } |
@Test public void closeQuietly() { LangUtils.closeQuietly(null); MockCloseeable mock = new MockCloseeable(); LangUtils.closeQuietly(mock); assertTrue(mock.closeCalled); } | public static <T extends Closeable> void closeQuietly(T object) { if (object != null) { try { object.close(); } catch (IOException ignored) { } } } | LangUtils { public static <T extends Closeable> void closeQuietly(T object) { if (object != null) { try { object.close(); } catch (IOException ignored) { } } } } | LangUtils { public static <T extends Closeable> void closeQuietly(T object) { if (object != null) { try { object.close(); } catch (IOException ignored) { } } } private LangUtils(); } | LangUtils { public static <T extends Closeable> void closeQuietly(T object) { if (object != null) { try { object.close(); } catch (IOException ignored) { } } } private LangUtils(); static void closeQuietly(T object); } | LangUtils { public static <T extends Closeable> void closeQuietly(T object) { if (object != null) { try { object.close(); } catch (IOException ignored) { } } } private LangUtils(); static void closeQuietly(T object); } |
@Test public void testQueryWithFalse() throws Exception { String url = "amqp: URLQuery urlQuery = new URLQuery(new URI(url)); assertFalse(urlQuery.getBoolean("value1", true)); assertTrue(urlQuery.getBoolean("value2", false)); } | public boolean getBoolean(final String name, boolean defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } if (value.equalsIgnoreCase("true")) { return true; } else { if (value.equalsIgnoreCase("false")) { return false; } } return defaultValue; } | URLQuery { public boolean getBoolean(final String name, boolean defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } if (value.equalsIgnoreCase("true")) { return true; } else { if (value.equalsIgnoreCase("false")) { return false; } } return defaultValue; } } | URLQuery { public boolean getBoolean(final String name, boolean defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } if (value.equalsIgnoreCase("true")) { return true; } else { if (value.equalsIgnoreCase("false")) { return false; } } return defaultValue; } URLQuery(final String uri); URLQuery(URI uri); } | URLQuery { public boolean getBoolean(final String name, boolean defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } if (value.equalsIgnoreCase("true")) { return true; } else { if (value.equalsIgnoreCase("false")) { return false; } } return defaultValue; } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); } | URLQuery { public boolean getBoolean(final String name, boolean defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } if (value.equalsIgnoreCase("true")) { return true; } else { if (value.equalsIgnoreCase("false")) { return false; } } return defaultValue; } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); } |
@Test public void testQueryWithLong() throws Exception { String url = "amqp: URLQuery urlQuery = new URLQuery(new URI(url)); assertEquals(1234L, (long) urlQuery.getLong("value1", 0L)); } | public Long getLong(final String name, final Long defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } return Long.parseLong(value); } | URLQuery { public Long getLong(final String name, final Long defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } return Long.parseLong(value); } } | URLQuery { public Long getLong(final String name, final Long defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } return Long.parseLong(value); } URLQuery(final String uri); URLQuery(URI uri); } | URLQuery { public Long getLong(final String name, final Long defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } return Long.parseLong(value); } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); } | URLQuery { public Long getLong(final String name, final Long defaultValue) { String value = getString(name, null); if (value == null) { return defaultValue; } return Long.parseLong(value); } URLQuery(final String uri); URLQuery(URI uri); String getString(final String name, final String defaultValue); boolean getBoolean(final String name, boolean defaultValue); Integer getInteger(final String name, final Integer defaultValue); Long getLong(final String name, final Long defaultValue); @SuppressWarnings("unused") Map<String, String> getParams(); int count(); } |
@Test public void testInsert() { Report report = new Report(); report.setTestHost("localhost"); report.setTestHostRole(HostTypes.SENDER_HOST_TYPE); report.setTestName("unit-test"); report.setTestNumber(1); report.setTestId(1); report.setLocation(this.getClass().getResource(".").getPath()); report.setTestResult(ResultStrings.SUCCESS); report.setTestScript("undefined"); report.setTestDate(Date.from(Instant.now())); dao.insert(report); } | public void insert(final Report report) { runEmptyInsert( "insert into report(test_id, test_number, test_name, test_script, test_host, test_host_role, " + "test_result, test_result_message, location, aggregated, test_description, test_comments, " + "valid, retired, retired_date, test_date) " + "values(:testId, :testNumber, :testName, :testScript, :testHost, :testHostRole, :testResult, " + ":testResultMessage, :location, :aggregated, :testDescription, :testComments, :valid, " + ":retired, :retiredDate, :testDate)", report); } | ReportDao extends AbstractDao { public void insert(final Report report) { runEmptyInsert( "insert into report(test_id, test_number, test_name, test_script, test_host, test_host_role, " + "test_result, test_result_message, location, aggregated, test_description, test_comments, " + "valid, retired, retired_date, test_date) " + "values(:testId, :testNumber, :testName, :testScript, :testHost, :testHostRole, :testResult, " + ":testResultMessage, :location, :aggregated, :testDescription, :testComments, :valid, " + ":retired, :retiredDate, :testDate)", report); } } | ReportDao extends AbstractDao { public void insert(final Report report) { runEmptyInsert( "insert into report(test_id, test_number, test_name, test_script, test_host, test_host_role, " + "test_result, test_result_message, location, aggregated, test_description, test_comments, " + "valid, retired, retired_date, test_date) " + "values(:testId, :testNumber, :testName, :testScript, :testHost, :testHostRole, :testResult, " + ":testResultMessage, :location, :aggregated, :testDescription, :testComments, :valid, " + ":retired, :retiredDate, :testDate)", report); } ReportDao(); ReportDao(TemplateBuilder tp); } | ReportDao extends AbstractDao { public void insert(final Report report) { runEmptyInsert( "insert into report(test_id, test_number, test_name, test_script, test_host, test_host_role, " + "test_result, test_result_message, location, aggregated, test_description, test_comments, " + "valid, retired, retired_date, test_date) " + "values(:testId, :testNumber, :testName, :testScript, :testHost, :testHostRole, :testResult, " + ":testResultMessage, :location, :aggregated, :testDescription, :testComments, :valid, " + ":retired, :retiredDate, :testDate)", report); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } | ReportDao extends AbstractDao { public void insert(final Report report) { runEmptyInsert( "insert into report(test_id, test_number, test_name, test_script, test_host, test_host_role, " + "test_result, test_result_message, location, aggregated, test_description, test_comments, " + "valid, retired, retired_date, test_date) " + "values(:testId, :testNumber, :testName, :testScript, :testHost, :testHostRole, :testResult, " + ":testResultMessage, :location, :aggregated, :testDescription, :testComments, :valid, " + ":retired, :retiredDate, :testDate)", report); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } |
@Test public void testFetchAll() throws DataNotFoundException { List<Report> reports = dao.fetch(); assertTrue("The database should not be empty", reports.size() > 0); long aggregatedCount = reports.stream().filter(Report::isAggregated).count(); long expectedAggCount = 0; assertEquals("Aggregated reports should not be displayed by default", expectedAggCount, aggregatedCount); } | public List<Report> fetchAll() throws DataNotFoundException { return runQueryMany("select * from report", new BeanPropertyRowMapper<>(Report.class)); } | ReportDao extends AbstractDao { public List<Report> fetchAll() throws DataNotFoundException { return runQueryMany("select * from report", new BeanPropertyRowMapper<>(Report.class)); } } | ReportDao extends AbstractDao { public List<Report> fetchAll() throws DataNotFoundException { return runQueryMany("select * from report", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); } | ReportDao extends AbstractDao { public List<Report> fetchAll() throws DataNotFoundException { return runQueryMany("select * from report", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } | ReportDao extends AbstractDao { public List<Report> fetchAll() throws DataNotFoundException { return runQueryMany("select * from report", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } |
@Test public void testFetchById() throws DataNotFoundException { List<Report> reports = dao.fetch(2, 1); assertTrue("There should be at least 3 records for the given ID", reports.size() >= 3); long aggregatedCount = reports.stream().filter(Report::isAggregated).count(); long expectedAggCount = 0; assertEquals("Aggregated reports should not be displayed by default", expectedAggCount, aggregatedCount); } | public List<Report> fetch() throws DataNotFoundException { return runQueryMany("select * from report where aggregated = false and valid = true order by report_id desc", new BeanPropertyRowMapper<>(Report.class)); } | ReportDao extends AbstractDao { public List<Report> fetch() throws DataNotFoundException { return runQueryMany("select * from report where aggregated = false and valid = true order by report_id desc", new BeanPropertyRowMapper<>(Report.class)); } } | ReportDao extends AbstractDao { public List<Report> fetch() throws DataNotFoundException { return runQueryMany("select * from report where aggregated = false and valid = true order by report_id desc", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); } | ReportDao extends AbstractDao { public List<Report> fetch() throws DataNotFoundException { return runQueryMany("select * from report where aggregated = false and valid = true order by report_id desc", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } | ReportDao extends AbstractDao { public List<Report> fetch() throws DataNotFoundException { return runQueryMany("select * from report where aggregated = false and valid = true order by report_id desc", new BeanPropertyRowMapper<>(Report.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } |
@Test public void testAggregationInfo() throws DataNotFoundException { List<ReportAggregationInfo> aggregationInfos = dao.aggregationInfo(); long expectedAggregatedCount = 2; assertEquals("Unexpected amount of aggregated records", expectedAggregatedCount, aggregationInfos.size()); } | public List<ReportAggregationInfo> aggregationInfo() throws DataNotFoundException { return runQueryMany("SELECT test_id,test_number,sum(aggregated) AS aggregations FROM report " + "GROUP BY test_id,test_number ORDER BY test_id desc", new BeanPropertyRowMapper<>(ReportAggregationInfo.class)); } | ReportDao extends AbstractDao { public List<ReportAggregationInfo> aggregationInfo() throws DataNotFoundException { return runQueryMany("SELECT test_id,test_number,sum(aggregated) AS aggregations FROM report " + "GROUP BY test_id,test_number ORDER BY test_id desc", new BeanPropertyRowMapper<>(ReportAggregationInfo.class)); } } | ReportDao extends AbstractDao { public List<ReportAggregationInfo> aggregationInfo() throws DataNotFoundException { return runQueryMany("SELECT test_id,test_number,sum(aggregated) AS aggregations FROM report " + "GROUP BY test_id,test_number ORDER BY test_id desc", new BeanPropertyRowMapper<>(ReportAggregationInfo.class)); } ReportDao(); ReportDao(TemplateBuilder tp); } | ReportDao extends AbstractDao { public List<ReportAggregationInfo> aggregationInfo() throws DataNotFoundException { return runQueryMany("SELECT test_id,test_number,sum(aggregated) AS aggregations FROM report " + "GROUP BY test_id,test_number ORDER BY test_id desc", new BeanPropertyRowMapper<>(ReportAggregationInfo.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } | ReportDao extends AbstractDao { public List<ReportAggregationInfo> aggregationInfo() throws DataNotFoundException { return runQueryMany("SELECT test_id,test_number,sum(aggregated) AS aggregations FROM report " + "GROUP BY test_id,test_number ORDER BY test_id desc", new BeanPropertyRowMapper<>(ReportAggregationInfo.class)); } ReportDao(); ReportDao(TemplateBuilder tp); void insert(final Report report); int update(final Report report); List<Report> fetch(); List<Report> fetchAll(); List<Report> fetchAllAggregated(); Report fetch(int reportId); List<Report> fetch(int testId, int testNumber); List<Report> fetchByTestId(int testId); Report fetchAggregated(int testId, int testNumber); List<ReportAggregationInfo> aggregationInfo(); int getLastTestId(); int getNextTestId(); int getLastTestNumber(int testId); int getNextTestNumber(int testId); } |
@Test public void testCleanExitOnStopped() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED, null); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } | public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } |
@SuppressWarnings("unchecked") @Test public void parseReceivedMessage() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); Map<String, Object> fakeMap = buildTestMap(); List<Map<String, Object>> ret = converter.parseReceivedMessage(fakeMap); assertNotNull(ret); assertEquals(3, ret.size()); Map<String, Object> map1 = ret.get(0); assertNotNull(map1); assertEquals(2, map1.size()); assertEquals(map1.get("attribute1"), "value1.1"); assertEquals(map1.get("attribute2"), "value1.2"); Map<String, Object> map2 = ret.get(1); assertNotNull(map2); assertEquals(2, map2.size()); assertEquals(map2.get("attribute1"), "value2.1"); assertEquals(map2.get("attribute2"), "value2.2"); Map<String, Object> map3 = ret.get(2); assertNotNull(map3); assertEquals(2, map3.size()); assertEquals(map3.get("attribute1"), "value3.1"); assertEquals(map3.get("attribute2"), "value3.2"); } | public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } |
@Test public void parseReceivedMessageEmptyMap() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(new HashMap<String, Object>()); assertNotNull(ret); assertEquals(0, ret.size()); } | public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } |
@Test public void parseReceivedMessageInvalidAttributeNames() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(buildInvalidMap()); assertNotNull(ret); assertEquals(0, ret.size()); } | public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } |
@Test public void parseReceivedMessageWithEmptyLists() { InterconnectInfoConverter converter = new InterconnectInfoConverter(); List<Map<String, Object>> ret = converter.parseReceivedMessage(buildMapWithEmptyLists()); assertNotNull(ret); assertEquals(0, ret.size()); } | public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } | InterconnectInfoConverter { public List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map) { List<Map<String, Object>> recordList = new ArrayList<>(); if (map == null || map.isEmpty()) { logger.warn("The received attribute map is empty or null"); return recordList; } Object tmpAttributeNames = map.get("attributeNames"); if (tmpAttributeNames != null && !(tmpAttributeNames instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute names: "); } List<?> attributeNames = (List) tmpAttributeNames; if (attributeNames == null) { logger.warn("The received attribute map does not contain a list of attribute names"); return recordList; } Object tmpResults = map.get("results"); if (tmpResults != null && !(tmpResults instanceof List)) { throw new MaestroException("Unexpected type for the returned attribute values"); } List<List> results = (List<List>) tmpResults; if (results == null) { logger.warn("The received attribute map does not contain a list of attribute values (results)"); return recordList; } for (List<?> result : results) { Map<String, Object> tmpRecord = new HashMap<>(); for (Object attributeName: attributeNames) { tmpRecord.put((String) attributeName, result.get(attributeNames.indexOf(attributeName))); } recordList.add(Collections.unmodifiableMap(tmpRecord)); } return recordList; } List<Map<String, Object>> parseReceivedMessage(Map<?, ?> map); } |
@Test public void testCleanExitOnSuccess() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS, null); assertTrue(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } | public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } |
@Test public void testFailedExitOnFailure() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(false, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_FAILURE, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNotNull(wsi.getExitStatus()); } | public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } |
@Test public void testCleanExitOnStoppedRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); } | public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } |
@Test public void testCleanExitOnSuccessRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); } | public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } |
@Test public void testFailedExitOnFailureRunning() { WorkerStateInfo wsi = new WorkerStateInfo(); wsi.setState(true, WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_FAILURE, null); assertFalse(WorkerStateInfoUtil.isCleanExit(wsi)); assertNull(wsi.getExitStatus()); } | public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } | WorkerStateInfoUtil { public static boolean isCleanExit(WorkerStateInfo wsi) { if (wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_SUCCESS) { return true; } return wsi.getExitStatus() == WorkerStateInfo.WorkerExitStatus.WORKER_EXIT_STOPPED; } private WorkerStateInfoUtil(); static boolean isCleanExit(WorkerStateInfo wsi); } |
@Test public void testImportBuildings() throws Exception { FeatureTypeInfo ti = getCatalog().getFeatureTypeByName(getLayerId(SystemTestData.BUILDINGS)); SimpleFeatureCollection rawSource = (SimpleFeatureCollection) ti.getFeatureSource(null, null).getFeatures(); ForceCoordinateSystemFeatureResults forced = new ForceCoordinateSystemFeatureResults( rawSource, CRS.decode("EPSG:4326")); ImportProcess importer = new ImportProcess(getCatalog()); String result = importer.execute(forced, null, SystemTestData.CITE_PREFIX, SystemTestData.CITE_PREFIX, "Buildings2", null, null, null); checkBuildings2(result); } | @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } ImportProcess(Catalog catalog); } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } ImportProcess(Catalog catalog); @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") String execute(
@DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features,
@DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage,
@DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace,
@DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store,
@DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name,
@DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs,
@DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling,
@DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName); } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } ImportProcess(Catalog catalog); @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") String execute(
@DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features,
@DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage,
@DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace,
@DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store,
@DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name,
@DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs,
@DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling,
@DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName); } |
@Test public void testImportBuildingsForceCRS() throws Exception { FeatureTypeInfo ti = getCatalog().getFeatureTypeByName(getLayerId(SystemTestData.BUILDINGS)); SimpleFeatureCollection rawSource = (SimpleFeatureCollection) ti.getFeatureSource(null, null).getFeatures(); ImportProcess importer = new ImportProcess(getCatalog()); String result = importer.execute(rawSource, null, SystemTestData.CITE_PREFIX, SystemTestData.CITE_PREFIX, "Buildings2", CRS.decode("EPSG:4326"), null, null); checkBuildings2(result); } | @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } ImportProcess(Catalog catalog); } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } ImportProcess(Catalog catalog); @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") String execute(
@DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features,
@DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage,
@DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace,
@DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store,
@DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name,
@DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs,
@DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling,
@DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName); } | ImportProcess implements GSProcess { @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") public String execute( @DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features, @DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace, @DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store, @DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name, @DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs, @DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling, @DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName) throws ProcessException { WorkspaceInfo ws; if (workspace != null) { ws = catalog.getWorkspaceByName(workspace); if (ws == null) { throw new ProcessException("Could not find workspace " + workspace); } } else { ws = catalog.getDefaultWorkspace(); if (ws == null) { throw new ProcessException( "The catalog is empty, could not find a default workspace"); } } CatalogBuilder cb = new CatalogBuilder(catalog); cb.setWorkspace( ws ); StoreInfo storeInfo = null; boolean add = false; if (store != null) { if (features != null) { storeInfo = catalog.getDataStoreByName(ws.getName(), store); } else if (coverage != null) { storeInfo = catalog.getCoverageStoreByName(ws.getName(), store); } if (storeInfo == null) { throw new ProcessException("Could not find store " + store + " in workspace " + workspace); } } else if (features != null) { storeInfo = catalog.getDefaultDataStore(ws); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } else if (coverage != null) { LOGGER.info("Auto-configuring coverage store: " + (name != null ? name : coverage.getName().toString())); storeInfo = cb.buildCoverageStore((name != null ? name : coverage.getName().toString())); add = true; store = (name != null ? name : coverage.getName().toString()); if (storeInfo == null) { throw new ProcessException("Could not find a default store in workspace " + ws.getName()); } } StyleInfo targetStyle = null; if (styleName != null) { targetStyle = catalog.getStyleByName(styleName); if (targetStyle == null) { throw new ProcessException("Could not find style " + styleName); } } if (features != null) { String tentativeTargetName = null; if (name != null) { tentativeTargetName = ws.getName() + ":" + name; } else { tentativeTargetName = ws.getName() + ":" + features.getSchema().getTypeName(); } if (catalog.getLayer(tentativeTargetName) != null) { throw new ProcessException("Target layer " + tentativeTargetName + " already exists"); } String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { GeometryDescriptor gd = features.getSchema().getGeometryDescriptor(); if (gd == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; } else { CoordinateReferenceSystem nativeCrs = gd.getCoordinateReferenceSystem(); if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } SimpleFeatureType targetType; try { targetType = importDataIntoStore(features, name, (DataStoreInfo) storeInfo); } catch (IOException e) { throw new ProcessException("Failed to import data into the target store", e); } try { cb.setStore(storeInfo); FeatureTypeInfo typeInfo = cb.buildFeatureType(targetType.getName()); if (targetSRSCode != null) { typeInfo.setSRS(targetSRSCode); } if (srsHandling != null) { typeInfo.setProjectionPolicy(srsHandling); } cb.setupBounds(typeInfo); LayerInfo layerInfo = cb.buildLayer(typeInfo); if (targetStyle != null) { layerInfo.setDefaultStyle(targetStyle); } catalog.add(typeInfo); catalog.add(layerInfo); return layerInfo.prefixedName(); } catch (Exception e) { throw new ProcessException( "Failed to complete the import inside the GeoServer catalog", e); } } else if (coverage != null) { try { final File directory = catalog.getResourceLoader().findOrCreateDirectory("data", workspace, store); final File file = File.createTempFile(store, ".tif", directory); ((CoverageStoreInfo)storeInfo).setURL( file.toURL().toExternalForm() ); ((CoverageStoreInfo)storeInfo).setType("GeoTIFF"); CoordinateReferenceSystem cvCrs = coverage.getCoordinateReferenceSystem(); String targetSRSCode = null; if (srs != null) { try { Integer code = CRS.lookupEpsgCode(srs, true); if (code == null) { throw new WPSException("Could not find a EPSG code for " + srs); } targetSRSCode = "EPSG:" + code; } catch (Exception e) { throw new ProcessException("Could not lookup the EPSG code for the provided srs", e); } } else { if (cvCrs == null) { targetSRSCode = "EPSG:4326"; srsHandling = ProjectionPolicy.FORCE_DECLARED; srs = DefaultGeographicCRS.WGS84; } else { CoordinateReferenceSystem nativeCrs = cvCrs; if (nativeCrs == null) { throw new ProcessException("The original data has no native CRS, " + "you need to specify the srs parameter"); } else { try { Integer code = CRS.lookupEpsgCode(nativeCrs, true); if (code == null) { throw new ProcessException("Could not find an EPSG code for data " + "native spatial reference system: " + nativeCrs); } else { targetSRSCode = "EPSG:" + code; srs = CRS.decode(targetSRSCode, true); } } catch (Exception e) { throw new ProcessException("Failed to loookup an official EPSG code for " + "the source data native " + "spatial reference system", e); } } } } MathTransform tx = CRS.findMathTransform(cvCrs, srs); if (!tx.isIdentity() || !CRS.equalsIgnoreMetadata(cvCrs, srs)) { coverage = WCSUtils.resample(coverage, cvCrs, srs, null, Interpolation.getInstance(Interpolation.INTERP_NEAREST)); } GeoTiffWriter writer = new GeoTiffWriter(file); final ParameterValueGroup params = new GeoTiffFormat().getWriteParameters(); params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue( DEFAULT_WRITE_PARAMS); final GeneralParameterValue[] wps = (GeneralParameterValue[]) params.values().toArray( new GeneralParameterValue[1]); try { writer.write(coverage, wps); } finally { try { writer.dispose(); } catch (Exception e) { } } if ( add ) { catalog.add( (CoverageStoreInfo)storeInfo ); } else { catalog.save( (CoverageStoreInfo)storeInfo ); } cb.setStore( (CoverageStoreInfo)storeInfo ); GridCoverage2DReader reader = new GeoTiffReader(file); if ( reader == null ) { throw new ProcessException( "Could not aquire reader for coverage." ); } final Map customParameters = new HashMap(); CoverageInfo cinfo = cb.buildCoverage( reader, customParameters ); if ( name != null ) { cinfo.setName( name ); } if ( !add ) { CoverageInfo existing = catalog.getCoverageByCoverageStore((CoverageStoreInfo) storeInfo, name != null ? name : coverage.getName().toString() ); if ( existing == null ) { List<CoverageInfo> coverages = catalog.getCoveragesByCoverageStore( (CoverageStoreInfo) storeInfo ); if ( coverages.size() == 1 ) { existing = coverages.get(0); } if ( coverages.size() == 0 ) { add = true; } else { throw new ProcessException( "Unable to determine coverage to configure."); } } if ( existing != null ) { cb.updateCoverage(existing,cinfo); catalog.save( existing ); cinfo = existing; } } if ("UNKNOWN".equals(cinfo.getSRS())) { cinfo.setSRS( "EPSG:4326" ); } if ( add ) { catalog.add( cinfo ); LayerInfo layerInfo = cb.buildLayer( cinfo ); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } boolean valid = true; try { if (!catalog.validate(layerInfo, true).isEmpty()) { valid = false; } } catch (Exception e) { valid = false; } layerInfo.setEnabled(valid); catalog.add(layerInfo); return layerInfo.prefixedName(); } else { catalog.save( cinfo ); LayerInfo layerInfo = catalog.getLayerByName(cinfo.getName()); if ( styleName != null && targetStyle != null ) { layerInfo.setDefaultStyle( targetStyle ); } return layerInfo.prefixedName(); } } catch (MalformedURLException e) { throw new ProcessException( "URL Error", e ); } catch (IOException e) { throw new ProcessException( "I/O Exception", e ); } catch (Exception e) { e.printStackTrace(); throw new ProcessException( "Exception", e ); } } return null; } ImportProcess(Catalog catalog); @DescribeResult(name = "layerName", description = "Name of the new featuretype, with workspace") String execute(
@DescribeParameter(name = "features", min = 0, description = "Input feature collection") SimpleFeatureCollection features,
@DescribeParameter(name = "coverage", min = 0, description = "Input raster") GridCoverage2D coverage,
@DescribeParameter(name = "workspace", min = 0, description = "Target workspace (default is the system default)") String workspace,
@DescribeParameter(name = "store", min = 0, description = "Target store (default is the workspace default)") String store,
@DescribeParameter(name = "name", min = 0, description = "Name of the new featuretype/coverage (default is the name of the features in the collection)") String name,
@DescribeParameter(name = "srs", min = 0, description = "Target coordinate reference system (default is based on source when possible)") CoordinateReferenceSystem srs,
@DescribeParameter(name = "srsHandling", min = 0, description = "Desired SRS handling (default is FORCE_DECLARED, others are REPROJECT_TO_DECLARED or NONE)") ProjectionPolicy srsHandling,
@DescribeParameter(name = "styleName", min = 0, description = "Name of the style to be associated with the layer (default is a standard geometry-specific style)") String styleName); } |
@Test public void testSingleSave() throws Exception { GeoServer gs = createMock(GeoServer.class); List<ConfigurationListener> listeners = new ArrayList(); gs.addListener(capture(listeners)); expectLastCall().atLeastOnce(); List<ProcessGroupInfo> procGroups = new ArrayList(); WPSInfo wps = createNiceMock(WPSInfo.class); expect(wps.getProcessGroups()).andReturn(procGroups).anyTimes(); replay(wps); expect(gs.getService(WPSInfo.class)).andReturn(wps).anyTimes(); gs.save(wps); expectLastCall().once(); replay(gs); initer.initialize(gs); assertEquals(1, listeners.size()); ConfigurationListener l = listeners.get(0); l.handleGlobalChange(null, null, null, null); l.handlePostGlobalChange(null); verify(gs); } | public void initialize(final GeoServer geoServer) throws Exception { initWPS(geoServer.getService(WPSInfo.class), geoServer); geoServer.addListener(new ConfigurationListenerAdapter() { @Override public void handlePostGlobalChange(GeoServerInfo global) { initWPS(geoServer.getService(WPSInfo.class), geoServer); } }); } | WPSInitializer implements GeoServerInitializer { public void initialize(final GeoServer geoServer) throws Exception { initWPS(geoServer.getService(WPSInfo.class), geoServer); geoServer.addListener(new ConfigurationListenerAdapter() { @Override public void handlePostGlobalChange(GeoServerInfo global) { initWPS(geoServer.getService(WPSInfo.class), geoServer); } }); } } | WPSInitializer implements GeoServerInitializer { public void initialize(final GeoServer geoServer) throws Exception { initWPS(geoServer.getService(WPSInfo.class), geoServer); geoServer.addListener(new ConfigurationListenerAdapter() { @Override public void handlePostGlobalChange(GeoServerInfo global) { initWPS(geoServer.getService(WPSInfo.class), geoServer); } }); } WPSInitializer(WPSExecutionManager executionManager,
DefaultProcessManager processManager, WPSStorageCleaner cleaner); } | WPSInitializer implements GeoServerInitializer { public void initialize(final GeoServer geoServer) throws Exception { initWPS(geoServer.getService(WPSInfo.class), geoServer); geoServer.addListener(new ConfigurationListenerAdapter() { @Override public void handlePostGlobalChange(GeoServerInfo global) { initWPS(geoServer.getService(WPSInfo.class), geoServer); } }); } WPSInitializer(WPSExecutionManager executionManager,
DefaultProcessManager processManager, WPSStorageCleaner cleaner); void initialize(final GeoServer geoServer); } | WPSInitializer implements GeoServerInitializer { public void initialize(final GeoServer geoServer) throws Exception { initWPS(geoServer.getService(WPSInfo.class), geoServer); geoServer.addListener(new ConfigurationListenerAdapter() { @Override public void handlePostGlobalChange(GeoServerInfo global) { initWPS(geoServer.getService(WPSInfo.class), geoServer); } }); } WPSInitializer(WPSExecutionManager executionManager,
DefaultProcessManager processManager, WPSStorageCleaner cleaner); void initialize(final GeoServer geoServer); } |
@Test public void testCreateFromScratch() throws Exception { WPSXStreamLoader loader = new WPSXStreamLoader(new GeoServerResourceLoader()); WPSInfo wps = loader.createServiceFromScratch(null); assertNotNull(wps); assertEquals("WPS", wps.getName()); } | protected WPSInfo createServiceFromScratch(GeoServer gs) { WPSInfoImpl wps = new WPSInfoImpl(); wps.setName("WPS"); wps.setGeoServer( gs ); wps.getVersions().add( new Version( "1.0.0") ); wps.setMaxAsynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); wps.setMaxSynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); return wps; } | WPSXStreamLoader extends XStreamServiceLoader<WPSInfo> { protected WPSInfo createServiceFromScratch(GeoServer gs) { WPSInfoImpl wps = new WPSInfoImpl(); wps.setName("WPS"); wps.setGeoServer( gs ); wps.getVersions().add( new Version( "1.0.0") ); wps.setMaxAsynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); wps.setMaxSynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); return wps; } } | WPSXStreamLoader extends XStreamServiceLoader<WPSInfo> { protected WPSInfo createServiceFromScratch(GeoServer gs) { WPSInfoImpl wps = new WPSInfoImpl(); wps.setName("WPS"); wps.setGeoServer( gs ); wps.getVersions().add( new Version( "1.0.0") ); wps.setMaxAsynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); wps.setMaxSynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); return wps; } WPSXStreamLoader(GeoServerResourceLoader resourceLoader); } | WPSXStreamLoader extends XStreamServiceLoader<WPSInfo> { protected WPSInfo createServiceFromScratch(GeoServer gs) { WPSInfoImpl wps = new WPSInfoImpl(); wps.setName("WPS"); wps.setGeoServer( gs ); wps.getVersions().add( new Version( "1.0.0") ); wps.setMaxAsynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); wps.setMaxSynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); return wps; } WPSXStreamLoader(GeoServerResourceLoader resourceLoader); Class<WPSInfo> getServiceClass(); } | WPSXStreamLoader extends XStreamServiceLoader<WPSInfo> { protected WPSInfo createServiceFromScratch(GeoServer gs) { WPSInfoImpl wps = new WPSInfoImpl(); wps.setName("WPS"); wps.setGeoServer( gs ); wps.getVersions().add( new Version( "1.0.0") ); wps.setMaxAsynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); wps.setMaxSynchronousProcesses(Runtime.getRuntime().availableProcessors() * 2); return wps; } WPSXStreamLoader(GeoServerResourceLoader resourceLoader); Class<WPSInfo> getServiceClass(); } |
@Test public void testAddResourceNoExecutionId() throws Exception { File f = File.createTempFile("dummy", "dummy", new File("target")); resourceMgr.addResource(new WPSFileResource(f)); } | public void addResource(WPSResource resource) { String processId = getExecutionId(null); ExecutionResources resources = resourceCache.get(processId); if (resources == null) { throw new IllegalStateException("The executionId was not set for the current thread!"); } else { resources.temporary.add(resource); } } | WPSResourceManager implements DispatcherCallback,
ApplicationListener<ApplicationEvent> { public void addResource(WPSResource resource) { String processId = getExecutionId(null); ExecutionResources resources = resourceCache.get(processId); if (resources == null) { throw new IllegalStateException("The executionId was not set for the current thread!"); } else { resources.temporary.add(resource); } } } | WPSResourceManager implements DispatcherCallback,
ApplicationListener<ApplicationEvent> { public void addResource(WPSResource resource) { String processId = getExecutionId(null); ExecutionResources resources = resourceCache.get(processId); if (resources == null) { throw new IllegalStateException("The executionId was not set for the current thread!"); } else { resources.temporary.add(resource); } } } | WPSResourceManager implements DispatcherCallback,
ApplicationListener<ApplicationEvent> { public void addResource(WPSResource resource) { String processId = getExecutionId(null); ExecutionResources resources = resourceCache.get(processId); if (resources == null) { throw new IllegalStateException("The executionId was not set for the current thread!"); } else { resources.temporary.add(resource); } } String getExecutionId(Boolean synch); void setCurrentExecutionId(String executionId); void addResource(WPSResource resource); File getOutputFile(String executionId, String fileName); File getTemporaryFile(String extension); File getStoredResponseFile(String executionId); File getWpsOutputStorage(); void finished(Request request); void finished(String executionId); Request init(Request request); Operation operationDispatched(Request request, Operation operation); Object operationExecuted(Request request, Operation operation, Object result); Response responseDispatched(Request request, Operation operation, Object result,
Response response); Service serviceDispatched(Request request, Service service); void onApplicationEvent(ApplicationEvent event); } | WPSResourceManager implements DispatcherCallback,
ApplicationListener<ApplicationEvent> { public void addResource(WPSResource resource) { String processId = getExecutionId(null); ExecutionResources resources = resourceCache.get(processId); if (resources == null) { throw new IllegalStateException("The executionId was not set for the current thread!"); } else { resources.temporary.add(resource); } } String getExecutionId(Boolean synch); void setCurrentExecutionId(String executionId); void addResource(WPSResource resource); File getOutputFile(String executionId, String fileName); File getTemporaryFile(String extension); File getStoredResponseFile(String executionId); File getWpsOutputStorage(); void finished(Request request); void finished(String executionId); Request init(Request request); Operation operationDispatched(Request request, Operation operation); Object operationExecuted(Request request, Operation operation, Object result); Response responseDispatched(Request request, Operation operation, Object result,
Response response); Service serviceDispatched(Request request, Service service); void onApplicationEvent(ApplicationEvent event); } |
@Test public void getAllPostsWillBeOk() throws Exception { this.client .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); } | @GetMapping("/{id}") public Mono<Post> get(@PathVariable("id") String id) { return this.posts.findById(id); } | PostController { @GetMapping("/{id}") public Mono<Post> get(@PathVariable("id") String id) { return this.posts.findById(id); } } | PostController { @GetMapping("/{id}") public Mono<Post> get(@PathVariable("id") String id) { return this.posts.findById(id); } PostController(PostRepository posts); } | PostController { @GetMapping("/{id}") public Mono<Post> get(@PathVariable("id") String id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping("") Flux<Post> all(); @PostMapping("") Mono<Post> create(@RequestBody Post post); @GetMapping("/{id}") Mono<Post> get(@PathVariable("id") String id); @PutMapping("/{id}") Mono<Post> update(@PathVariable("id") String id, @RequestBody Post post); @DeleteMapping("/{id}") Mono<Void> delete(@PathVariable("id") String id); } | PostController { @GetMapping("/{id}") public Mono<Post> get(@PathVariable("id") String id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping("") Flux<Post> all(); @PostMapping("") Mono<Post> create(@RequestBody Post post); @GetMapping("/{id}") Mono<Post> get(@PathVariable("id") String id); @PutMapping("/{id}") Mono<Post> update(@PathVariable("id") String id, @RequestBody Post post); @DeleteMapping("/{id}") Mono<Void> delete(@PathVariable("id") String id); } |
@Test public void getPostById() throws Exception { this.rest .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this.rest .get() .uri("/posts/2") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post two"); } | @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } |
@Test public void getAllPostsWillBeOk() throws Exception { this.client .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); } | @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } |
@Test public void getPostById() throws Exception { this.client .get() .uri("/posts/1") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post one"); this.client .get() .uri("/posts/2") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.title") .isEqualTo("post two"); } | @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } |
@Test public void testGetAllPosts() { StepVerifier.create(posts.findAll()) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post one"))) .consumeNextWith(p -> assertTrue(p.getTitle().equals("post two"))) .expectComplete() .verify(); } | Flux<Post> findAll() { return Flux.fromIterable(data.values()); } | PostRepository { Flux<Post> findAll() { return Flux.fromIterable(data.values()); } } | PostRepository { Flux<Post> findAll() { return Flux.fromIterable(data.values()); } PostRepository(); } | PostRepository { Flux<Post> findAll() { return Flux.fromIterable(data.values()); } PostRepository(); } | PostRepository { Flux<Post> findAll() { return Flux.fromIterable(data.values()); } PostRepository(); } |
@Test public void getAllPostsWillBeOk() throws Exception { this.rest .get() .uri("/posts") .accept(APPLICATION_JSON) .exchange() .expectBody() .jsonPath("$.length()") .isEqualTo(2); } | @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } | PostController { @GetMapping(value = "/{id}") public Mono<Post> get(@PathVariable(value = "id") Long id) { return this.posts.findById(id); } PostController(PostRepository posts); @GetMapping(value = "") Flux<Post> all(); @GetMapping(value = "/{id}") Mono<Post> get(@PathVariable(value = "id") Long id); @PostMapping(value = "") Mono<Post> create(@RequestBody Post post); @PutMapping(value = "/{id}") Mono<Post> update(@PathVariable(value = "id") Long id, @RequestBody Post post); @DeleteMapping(value = "/{id}") Mono<Post> delete(@PathVariable(value = "id") Long id); } |
@Test public void shoudlComplainIfNotInAServletEnviroment() throws Exception { exception.expect(ServletException.class); ServletRequest request = mock(ServletRequest.class); ServletResponse response = mock(ServletResponse.class); vRaptor.doFilter(request, response, null); } | @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { validateServletEnvironment(req, res); final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (isWebsocketRequest(baseRequest)) { chain.doFilter(req, res); return; } if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.trace("VRaptor received a new request {}", req); try { encodingHandler.setEncoding(baseRequest, baseResponse); RequestStarted requestStarted = requestStartedFactory.createEvent(baseRequest, baseResponse, chain); cdiRequestFactories.setRequest(requestStarted); requestStartedEvent.fire(requestStarted); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } } | VRaptor implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { validateServletEnvironment(req, res); final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (isWebsocketRequest(baseRequest)) { chain.doFilter(req, res); return; } if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.trace("VRaptor received a new request {}", req); try { encodingHandler.setEncoding(baseRequest, baseResponse); RequestStarted requestStarted = requestStartedFactory.createEvent(baseRequest, baseResponse, chain); cdiRequestFactories.setRequest(requestStarted); requestStartedEvent.fire(requestStarted); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } } } | VRaptor implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { validateServletEnvironment(req, res); final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (isWebsocketRequest(baseRequest)) { chain.doFilter(req, res); return; } if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.trace("VRaptor received a new request {}", req); try { encodingHandler.setEncoding(baseRequest, baseResponse); RequestStarted requestStarted = requestStartedFactory.createEvent(baseRequest, baseResponse, chain); cdiRequestFactories.setRequest(requestStarted); requestStartedEvent.fire(requestStarted); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } } } | VRaptor implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { validateServletEnvironment(req, res); final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (isWebsocketRequest(baseRequest)) { chain.doFilter(req, res); return; } if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.trace("VRaptor received a new request {}", req); try { encodingHandler.setEncoding(baseRequest, baseResponse); RequestStarted requestStarted = requestStartedFactory.createEvent(baseRequest, baseResponse, chain); cdiRequestFactories.setRequest(requestStarted); requestStartedEvent.fire(requestStarted); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } } @Override void init(FilterConfig cfg); @Override void doFilter(ServletRequest req, ServletResponse res, FilterChain chain); @Override void destroy(); } | VRaptor implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { validateServletEnvironment(req, res); final HttpServletRequest baseRequest = (HttpServletRequest) req; final HttpServletResponse baseResponse = (HttpServletResponse) res; if (isWebsocketRequest(baseRequest)) { chain.doFilter(req, res); return; } if (staticHandler.requestingStaticFile(baseRequest)) { staticHandler.deferProcessingToContainer(chain, baseRequest, baseResponse); } else { logger.trace("VRaptor received a new request {}", req); try { encodingHandler.setEncoding(baseRequest, baseResponse); RequestStarted requestStarted = requestStartedFactory.createEvent(baseRequest, baseResponse, chain); cdiRequestFactories.setRequest(requestStarted); requestStartedEvent.fire(requestStarted); } catch (ApplicationLogicException e) { throw new ServletException(e.getMessage(), e.getCause()); } logger.debug("VRaptor ended the request"); } } @Override void init(FilterConfig cfg); @Override void doFilter(ServletRequest req, ServletResponse res, FilterChain chain); @Override void destroy(); static final String VERSION; } |
@Test public void canHandleUrlIfNonRootContextButPlainRequest() { when(request.getRequestURI()).thenReturn("/custom_context/"); when(request.getContextPath()).thenReturn("/custom_context"); when(request.getMethod()).thenReturn("GET"); when(router.parse("/", HttpMethod.GET, webRequest)).thenReturn(method); ControllerMethod controller = translator.translate(webRequest); assertThat(controller, is(equalTo(method))); } | @Override public ControllerMethod translate(MutableRequest request) { String controllerName = request.getRequestedUri(); logger.debug("trying to access {}", controllerName); HttpMethod method = getHttpMethod(request, controllerName); ControllerMethod controller = router.parse(controllerName, method, request); logger.debug("found controller {}", controller); return controller; } | DefaultControllerTranslator implements UrlToControllerTranslator { @Override public ControllerMethod translate(MutableRequest request) { String controllerName = request.getRequestedUri(); logger.debug("trying to access {}", controllerName); HttpMethod method = getHttpMethod(request, controllerName); ControllerMethod controller = router.parse(controllerName, method, request); logger.debug("found controller {}", controller); return controller; } } | DefaultControllerTranslator implements UrlToControllerTranslator { @Override public ControllerMethod translate(MutableRequest request) { String controllerName = request.getRequestedUri(); logger.debug("trying to access {}", controllerName); HttpMethod method = getHttpMethod(request, controllerName); ControllerMethod controller = router.parse(controllerName, method, request); logger.debug("found controller {}", controller); return controller; } protected DefaultControllerTranslator(); @Inject DefaultControllerTranslator(Router router); } | DefaultControllerTranslator implements UrlToControllerTranslator { @Override public ControllerMethod translate(MutableRequest request) { String controllerName = request.getRequestedUri(); logger.debug("trying to access {}", controllerName); HttpMethod method = getHttpMethod(request, controllerName); ControllerMethod controller = router.parse(controllerName, method, request); logger.debug("found controller {}", controller); return controller; } protected DefaultControllerTranslator(); @Inject DefaultControllerTranslator(Router router); @Override ControllerMethod translate(MutableRequest request); } | DefaultControllerTranslator implements UrlToControllerTranslator { @Override public ControllerMethod translate(MutableRequest request) { String controllerName = request.getRequestedUri(); logger.debug("trying to access {}", controllerName); HttpMethod method = getHttpMethod(request, controllerName); ControllerMethod controller = router.parse(controllerName, method, request); logger.debug("found controller {}", controller); return controller; } protected DefaultControllerTranslator(); @Inject DefaultControllerTranslator(Router router); @Override ControllerMethod translate(MutableRequest request); } |
@Test public void isCapableOfDealingWithGenericsAndMultipleParameters() throws Exception { requestParametersAre(ImmutableMap.of("key", new String[] { "age" }, "value", new String[] { "32" })); ControllerMethod generic = method(SpecificKeyValueResource.class, GenericKeyValueResource.class, "put", Object.class, Object.class); Object[] params = iogi.getParametersFor(generic, errors); String key = (String) params[0]; Long value = (Long) params[1]; assertThat(key, is("age")); assertThat(value, notNullValue()); assertThat(value, instanceOf(Long.class)); assertThat(value, is(32L)); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void returnsAnEmptyObjectArrayForZeroArityMethods() throws Exception { thereAreNoParameters(); Object[] params = iogi.getParametersFor(method("doNothing"), errors); assertThat(params, emptyArray()); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void returnsNullWhenInstantiatingAListForWhichThereAreNoParameters() throws Exception { thereAreNoParameters(); Object[] params = iogi.getParametersFor(method("list", List.class), errors); assertArrayEquals(new Object[] {null}, params); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void shouldInstantiateTheObjectEvenWhenThereAreNoParameters() throws Exception { thereAreNoParameters(); ControllerMethod method = method(House.class, House.class, "setCat", Cat.class); Object[] params = iogi.getParametersFor(method, errors); assertThat(params[0], notNullValue()); assertThat(params[0], instanceOf(Cat.class)); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void shouldnotInstantiateObjectWhenThereAreNoParameters() throws Exception { VRaptorInstantiator instantiator = new NullVRaptorInstantiator(converters, new VRaptorDependencyProvider(container), new VRaptorParameterNamesProvider(nameProvider), request); instantiator.createInstantiator(); IogiParametersProvider provider = new IogiParametersProvider(nameProvider, request, instantiator); thereAreNoParameters(); ControllerMethod method = method(House.class, House.class, "setCat", Cat.class); Object[] params = provider.getParametersFor(method, errors); assertThat(params[0], nullValue()); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void returnsNullWhenInstantiatingAStringForWhichThereAreNoParameters() throws Exception { thereAreNoParameters(); Object[] params = iogi.getParametersFor(method("string", String.class), errors); assertArrayEquals(new Object[] {null}, params); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void canInjectADependencyProvidedByVraptor() throws Exception { thereAreNoParameters(); ControllerMethod controllerMethod = method(OtherResource.class, OtherResource.class, "logic", NeedsMyResource.class); final MyResource providedInstance = new MyResource(); when(container.canProvide(MyResource.class)).thenReturn(true); when(container.instanceFor(MyResource.class)).thenReturn(providedInstance); Object[] params = iogi.getParametersFor(controllerMethod, errors); assertThat(((NeedsMyResource) params[0]).getMyResource(), is(sameInstance(providedInstance))); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void willCreateAnIogiParameterForEachRequestParameterValue() throws Exception { requestParameterIs("name", "a", "b"); final InstantiatorWithErrors mockInstantiator = mock(InstantiatorWithErrors.class); final Parameters expectedParamters = new Parameters(new Parameter("name", "a"), new Parameter("name", "b")); IogiParametersProvider iogiProvider = new IogiParametersProvider(nameProvider, request, mockInstantiator); iogiProvider.getParametersFor(method("buyA", House.class), errors); verify(mockInstantiator).instantiate(any(Target.class), eq(expectedParamters), eq(errors)); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void willCreateATargerForEachFormalParameterDeclaredByTheMethod() throws Exception { requestParameterIs("house", ""); final InstantiatorWithErrors mockInstantiator = mock(InstantiatorWithErrors.class); IogiParametersProvider iogiProvider = new IogiParametersProvider(nameProvider, request, mockInstantiator); final Target<House> expectedTarget = Target.create(House.class, "house"); iogiProvider.getParametersFor(method("buyA", House.class), errors); verify(mockInstantiator).instantiate(eq(expectedTarget), any(Parameters.class), eq(errors)); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void registerParametersWithMultipleRegexes() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = new DefaultParametersControl("/test/{hash1:[a-z0-9]{16}}{id}{hash2:[a-z0-9]{16}}/", Collections.singletonMap("id", "\\d+"), converters, evaluator,encodingHandler); control.fillIntoRequest("/test/0123456789abcdef1234fedcba9876543210/", request); verify(request).setParameter("hash1", new String[] {"0123456789abcdef"}); verify(request).setParameter("id", new String[] {"1234"}); verify(request).setParameter("hash2", new String[] {"fedcba9876543210"}); } | @Override public void fillIntoRequest(String uri, MutableRequest request) { Matcher m = pattern.matcher(uri); m.matches(); for (int i = 1; i <= m.groupCount(); i++) { String name = parameters.get(i - 1); try { request.setParameter(name, URLDecoder.decode(m.group(i), encodingHandler.getEncoding())); } catch (UnsupportedEncodingException e) { logger.error("Error when decoding url parameters"); } } } | DefaultParametersControl implements ParametersControl { @Override public void fillIntoRequest(String uri, MutableRequest request) { Matcher m = pattern.matcher(uri); m.matches(); for (int i = 1; i <= m.groupCount(); i++) { String name = parameters.get(i - 1); try { request.setParameter(name, URLDecoder.decode(m.group(i), encodingHandler.getEncoding())); } catch (UnsupportedEncodingException e) { logger.error("Error when decoding url parameters"); } } } } | DefaultParametersControl implements ParametersControl { @Override public void fillIntoRequest(String uri, MutableRequest request) { Matcher m = pattern.matcher(uri); m.matches(); for (int i = 1; i <= m.groupCount(); i++) { String name = parameters.get(i - 1); try { request.setParameter(name, URLDecoder.decode(m.group(i), encodingHandler.getEncoding())); } catch (UnsupportedEncodingException e) { logger.error("Error when decoding url parameters"); } } } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); } | DefaultParametersControl implements ParametersControl { @Override public void fillIntoRequest(String uri, MutableRequest request) { Matcher m = pattern.matcher(uri); m.matches(); for (int i = 1; i <= m.groupCount(); i++) { String name = parameters.get(i - 1); try { request.setParameter(name, URLDecoder.decode(m.group(i), encodingHandler.getEncoding())); } catch (UnsupportedEncodingException e) { logger.error("Error when decoding url parameters"); } } } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } | DefaultParametersControl implements ParametersControl { @Override public void fillIntoRequest(String uri, MutableRequest request) { Matcher m = pattern.matcher(uri); m.matches(); for (int i = 1; i <= m.groupCount(); i++) { String name = parameters.get(i - 1); try { request.setParameter(name, URLDecoder.decode(m.group(i), encodingHandler.getEncoding())); } catch (UnsupportedEncodingException e) { logger.error("Error when decoding url parameters"); } } } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } |
@Test public void shouldInjectOnlyAttributesWithSameType() throws Exception { Result result = mock(Result.class); when(request.getAttribute("result")).thenReturn(result); when(request.getParameterMap()).thenReturn(singletonMap("result", new String[] { "buggy" })); ControllerMethod method = method(OtherResource.class, OtherResource.class, "logic", String.class); Object[] out = iogi.getParametersFor(method, errors); assertThat(out[0], is(not((Object) result))); assertThat(out[0], is((Object) "buggy")); } | @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } | IogiParametersProvider implements ParametersProvider { @Override public Object[] getParametersFor(ControllerMethod method, List<Message> errors) { Parameters parameters = parseParameters(servletRequest); List<Target<Object>> targets = createTargets(method); return instantiateParameters(parameters, targets, errors).toArray(); } protected IogiParametersProvider(); @Inject IogiParametersProvider(ParameterNameProvider provider, HttpServletRequest parameters, InstantiatorWithErrors instantiator); @Override Object[] getParametersFor(ControllerMethod method, List<Message> errors); } |
@Test public void if_formatIsSpecifiedReturnIt() throws Exception { when(request.getParameter("_format")).thenReturn("xml"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); } | @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } |
@Test public void if_formatIsSpecifiedReturnItEvenIfAcceptsHtml() throws Exception { when(request.getParameter("_format")).thenReturn("xml"); when(request.getHeader("Accept")).thenReturn("html"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); } | @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } |
@Test public void if_formatNotSpecifiedShouldReturnRequestAcceptFormat() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn("application/xml"); when(acceptHeaderToFormat.getFormat("application/xml")).thenReturn("xml"); String format = resolver.getAcceptFormat(); assertThat(format, is("xml")); verify(request).getHeader("Accept"); } | @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } |
@Test public void if_formatNotSpecifiedAndNoAcceptsHaveFormat() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn("application/SOMETHING_I_DONT_HAVE"); String format = resolver.getAcceptFormat(); assertNull(format); verify(request).getHeader("Accept"); } | @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } |
@Test public void ifAcceptHeaderIsNullShouldReturnDefault() { when(request.getParameter("_format")).thenReturn(null); when(request.getHeader("Accept")).thenReturn(null); when(acceptHeaderToFormat.getFormat(null)).thenReturn("html"); String format = resolver.getAcceptFormat(); assertThat(format, is("html")); } | @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } | DefaultFormatResolver implements FormatResolver { @Override public String getAcceptFormat() { String format = request.getParameter("_format"); if (format != null) { return format; } format = request.getHeader("Accept"); return acceptHeaderToFormat.getFormat(format) ; } protected DefaultFormatResolver(); @Inject DefaultFormatResolver(HttpServletRequest request, AcceptHeaderToFormat acceptHeaderToFormat); @Override String getAcceptFormat(); } |
@Test public void shouldProxifyInterfaces() { TheInterface proxy = proxifier.proxify(TheInterface.class, new MethodInvocation<TheInterface>() { @Override public Object intercept(TheInterface proxy, Method method, Object[] args, SuperMethod superMethod) { return true; } }); assertThat(proxy.wasCalled(), is(true)); } | @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } |
@Test public void shouldProxifyConcreteClassesWithDefaultConstructors() { TheClass proxy = proxifier.proxify(TheClass.class, new MethodInvocation<TheClass>() { @Override public Object intercept(TheClass proxy, Method method, Object[] args, SuperMethod superMethod) { return true; } }); assertThat(proxy.wasCalled(), is(true)); } | @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } |
@Test public void shouldNotProxifyJavaLangObjectMethods() throws Exception { Object proxy = proxifier.proxify(JavassistProxifierTest.class, new MethodInvocation<Object>() { @Override public Object intercept(Object proxy, Method method, Object[] args, SuperMethod superMethod) { fail("should not call this Method interceptor"); return null; } }); new Mirror().on(proxy).invoke().method("finalize").withoutArgs(); } | @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } |
@Test public void shouldThrowProxyInvocationExceptionIfAnErrorOccurs() { C proxy = proxifier.proxify(C.class, new MethodInvocation<C>() { @Override public Object intercept(C proxy, Method method, Object[] args, SuperMethod superMethod) { return superMethod.invoke(proxy, args); } }); try { proxy.doThrow(); fail("Should throw exception"); } catch (ProxyInvocationException e) { } } | @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } |
@Test public void worksAsRegexWhenUsingParameters() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients/{dog.id}"); assertThat(control.matches("/clients/15"), is(equalTo(true))); } | @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } |
@Test public void shouldNotProxifyBridges() throws Exception { B proxy = proxifier.proxify(B.class, new MethodInvocation<B>() { @Override public Object intercept(B proxy, Method method, Object[] args, SuperMethod superMethod) { if (method.isBridge()) { fail("Method " + method + " is a bridge"); } return null; } }); Method[] methods = proxy.getClass().getMethods(); for (Method m : methods) { if (m.getName().equals("getT")) { m.invoke(proxy, ""); } } } | @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } |
@Test public void shouldConsiderSuperclassWhenProxifiyngProxy() throws Exception { MethodInvocation<C> handler = new MethodInvocation<C>() { @Override public Object intercept(C proxy, Method method, Object[] args, SuperMethod superMethod) { return null; } }; C firstProxy = proxifier.proxify(C.class, handler); C secondProxy = proxifier.proxify(firstProxy.getClass(), handler); assertEquals(firstProxy.getClass(), secondProxy.getClass()); } | @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } | JavassistProxifier implements Proxifier { @Override public <T> T proxify(Class<T> type, MethodInvocation<? super T> handler) { final ProxyFactory factory = new ProxyFactory(); factory.setFilter(IGNORE_BRIDGE_AND_OBJECT_METHODS); Class<?> rawType = extractRawType(type); if (type.isInterface()) { factory.setInterfaces(new Class[] { rawType }); } else { factory.setSuperclass(rawType); } Object instance = createInstance(type, handler, factory); logger.debug("a proxy for {} was created as {}", type, instance.getClass()); return (T) instance; } @Override T proxify(Class<T> type, MethodInvocation<? super T> handler); @Override boolean isProxy(Object o); @Override boolean isProxyType(Class<?> type); } |
@Test public void shoulIdentifyCDIProxies() { assertTrue(isCDIProxy(proxiable.getClass())); assertFalse(isCDIProxy(nonProxiable.getClass())); } | public static boolean isCDIProxy(Class<?> type) { return ProxyObject.class.isAssignableFrom(type); } | CDIProxies { public static boolean isCDIProxy(Class<?> type) { return ProxyObject.class.isAssignableFrom(type); } } | CDIProxies { public static boolean isCDIProxy(Class<?> type) { return ProxyObject.class.isAssignableFrom(type); } private CDIProxies(); } | CDIProxies { public static boolean isCDIProxy(Class<?> type) { return ProxyObject.class.isAssignableFrom(type); } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); } | CDIProxies { public static boolean isCDIProxy(Class<?> type) { return ProxyObject.class.isAssignableFrom(type); } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); } |
@Test public void shouldReturnTheBeanIfItsNotCDIProxy() { NonProxiableBean bean = unproxifyIfPossible(nonProxiable); assertThat(bean, equalTo(nonProxiable)); } | @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unproxifyIfPossible(T source) { if (source instanceof TargetInstanceProxy) { TargetInstanceProxy<T> target = (TargetInstanceProxy) source; return target.getTargetInstance(); } return source; } | CDIProxies { @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unproxifyIfPossible(T source) { if (source instanceof TargetInstanceProxy) { TargetInstanceProxy<T> target = (TargetInstanceProxy) source; return target.getTargetInstance(); } return source; } } | CDIProxies { @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unproxifyIfPossible(T source) { if (source instanceof TargetInstanceProxy) { TargetInstanceProxy<T> target = (TargetInstanceProxy) source; return target.getTargetInstance(); } return source; } private CDIProxies(); } | CDIProxies { @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unproxifyIfPossible(T source) { if (source instanceof TargetInstanceProxy) { TargetInstanceProxy<T> target = (TargetInstanceProxy) source; return target.getTargetInstance(); } return source; } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); } | CDIProxies { @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> T unproxifyIfPossible(T source) { if (source instanceof TargetInstanceProxy) { TargetInstanceProxy<T> target = (TargetInstanceProxy) source; return target.getTargetInstance(); } return source; } private CDIProxies(); static boolean isCDIProxy(Class<?> type); static Class<?> extractRawTypeIfPossible(Class<T> type); @SuppressWarnings({ "unchecked", "rawtypes" }) static T unproxifyIfPossible(T source); } |
@Test public void shouldInvokeTheMethodAndNotProceedWithInterceptorStack() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, DogAlike.class.getMethod("bark")); DogAlike auau = mock(DogAlike.class); when(methodInfo.getParametersValues()).thenReturn(new Object[0]); observer.execute(new InterceptorsExecuted(method, auau)); verify(auau).bark(); verify(messages).assertAbsenceOfErrors(); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void shouldUseTheProvidedArguments() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, DogAlike.class.getMethod("bark", int.class)); DogAlike auau = mock(DogAlike.class); when(methodInfo.getParametersValues()).thenReturn(new Object[] { 3 }); observer.execute(new InterceptorsExecuted(method, auau)); verify(auau).bark(3); verify(messages).assertAbsenceOfErrors(); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void shouldSetResultReturnedValueFromInvokedMethod() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, XController.class.getMethod("method", Object.class)); final XController controller = new XController(); when(methodInfo.getParametersValues()).thenReturn(new Object[] { "string" }); observer.execute(new InterceptorsExecuted(method, controller)); verify(messages).assertAbsenceOfErrors(); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void shouldSetNullWhenNullReturnedFromInvokedMethod() throws Exception { ControllerMethod method = new DefaultControllerMethod(null, XController.class.getMethod("method", Object.class)); final XController controller = new XController(); when(methodInfo.getParametersValues()).thenReturn(new Object[] { null }); observer.execute(new InterceptorsExecuted(method, controller)); verify(methodInfo).setResult(null); verify(messages).assertAbsenceOfErrors(); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void shouldBeOkIfThereIsValidationErrorsAndYouSpecifiedWhereToGo() throws Exception { Method specifiedWhereToGo = AnyController.class.getMethod("specifiedWhereToGo"); ControllerMethod method = DefaultControllerMethod.instanceFor(AnyController.class, specifiedWhereToGo); AnyController controller = new AnyController(validator); when(methodInfo.getParametersValues()).thenReturn(new Object[0]); doThrow(new ValidationException(Collections.<Message> emptyList())).when(validator).onErrorUse(nothing()); observer.execute(new InterceptorsExecuted(method, controller)); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void shouldThrowExceptionIfYouHaventSpecifiedWhereToGoOnValidationError() throws Exception { exception.expect(ValidationFailedException.class); Method didntSpecifyWhereToGo = AnyController.class.getMethod("didntSpecifyWhereToGo"); final ControllerMethod method = DefaultControllerMethod.instanceFor(AnyController.class, didntSpecifyWhereToGo); final AnyController controller = new AnyController(validator); doThrow(new ValidationFailedException("")).when(messages).assertAbsenceOfErrors(); when(methodInfo.getParametersValues()).thenReturn(new Object[0]); observer.execute(new InterceptorsExecuted(method, controller)); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void worksWithBasicRegexEvaluation() throws SecurityException, NoSuchMethodException { DefaultParametersControl control = getDefaultParameterControlForUrl("/clients.*"); assertThat(control.matches("/clientsWhatever"), is(equalTo(true))); } | @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } | DefaultParametersControl implements ParametersControl { @Override public boolean matches(String uri) { return pattern.matcher(uri).matches(); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } |
@Test public void shouldThrowApplicationLogicExceptionIfItsACheckedException() throws Exception { Method method = AnyController.class.getDeclaredMethod("throwException"); ControllerMethod controllerMethod = instanceFor(AnyController.class, method); AnyController controller = new AnyController(validator); expected.expect(ApplicationLogicException.class); expected.expectCause(any(TestCheckedException.class)); observer.execute(new InterceptorsExecuted(controllerMethod, controller)); verify(messages).assertAbsenceOfErrors(); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void shouldThrowTheBusinessExceptionIfItsUnChecked() throws Exception { Method method = AnyController.class.getDeclaredMethod("throwUnCheckedException"); ControllerMethod controllerMethod = instanceFor(AnyController.class, method); AnyController controller = new AnyController(validator); expected.expect(TestException.class); observer.execute(new InterceptorsExecuted(controllerMethod, controller)); verify(messages).assertAbsenceOfErrors(); } | public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } | ExecuteMethod { public void execute(@Observes final InterceptorsExecuted event) { Try run = Try.run(new Callable<Void>() { @Override public Void call() throws Exception { ControllerMethod method = event.getControllerMethod(); methodReady.fire(new MethodReady(method)); Method reflectionMethod = method.getMethod(); Object[] parameters = methodInfo.getParametersValues(); log.debug("Invoking {}", reflectionMethod); Object instance = event.getControllerInstance(); Object result = reflectionProvider.invoke(instance, reflectionMethod, parameters); messages.assertAbsenceOfErrors(); methodInfo.setResult(result); methodExecutedEvent.fire(new MethodExecuted(method, methodInfo)); return null; } }); if (run.failed()) { Exception exception = run.getException(); executeMethodExceptionHandler.handle(exception); } } @Inject ExecuteMethod(MethodInfo methodInfo, Messages messages,
Event<MethodExecuted> methodExecutedEvent, Event<MethodReady> methodReady,
ExecuteMethodExceptionHandler exceptionHandler, ReflectionProvider reflectionProvider); void execute(@Observes final InterceptorsExecuted event); } |
@Test public void shouldOnlyAcceptMethodsWithConsumesAnnotation() throws Exception { observer.deserializes(new InterceptorsReady(doesntConsume), request, methodInfo, status); verifyZeroInteractions(request); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void willSetHttpStatusCode415IfTheControllerMethodDoesNotSupportTheGivenMediaTypes() throws Exception { when(request.getContentType()).thenReturn("image/jpeg"); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); verify(status).unsupportedMediaType("Request with media type [image/jpeg]. Expecting one of [application/xml]."); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void willSetHttpStatusCode415IfThereIsNoDeserializerButIsAccepted() throws Exception { when(request.getContentType()).thenReturn("application/xml"); when(deserializers.deserializerFor("application/xml", container)).thenReturn(null); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); verify(status).unsupportedMediaType("Unable to handle media type [application/xml]: no deserializer found."); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void willSetMethodParametersWithDeserializationAndContinueStackAfterDeserialization() throws Exception { final Deserializer deserializer = mock(Deserializer.class); methodInfo.setControllerMethod(consumeXml); when(request.getContentType()).thenReturn("application/xml"); when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {"abc", "def"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def"); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void willSetMethodParametersWithDeserializationEvenIfTheContentTypeHasCharsetDeclaration() throws Exception { final Deserializer deserializer = mock(Deserializer.class); methodInfo.setControllerMethod(consumeXml); when(request.getContentType()).thenReturn("application/xml; charset=UTF-8"); when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {"abc", "def"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def"); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void willDeserializeForAnyContentTypeIfPossible() throws Exception { final ControllerMethod consumesAnything = new DefaultControllerMethod(null, DummyResource.class.getDeclaredMethod("consumesAnything", String.class, String.class)); when(request.getContentType()).thenReturn("application/xml"); methodInfo.setControllerMethod(consumesAnything); final Deserializer deserializer = mock(Deserializer.class); when(deserializer.deserialize(null, consumesAnything)).thenReturn(new Object[] {"abc", "def"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumesAnything), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "abc"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "def"); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void shouldNotDeserializeIfHasNoContentType() throws Exception { final ControllerMethod consumesAnything = new DefaultControllerMethod(null, DummyResource.class.getDeclaredMethod("consumesAnything", String.class, String.class)); when(request.getContentType()).thenReturn(null); methodInfo.setControllerMethod(consumesAnything); observer.deserializes(new InterceptorsReady(consumesAnything), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), null); assertEquals(methodInfo.getValuedParameters()[1].getValue(), null); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void willSetOnlyNonNullParameters() throws Exception { final Deserializer deserializer = mock(Deserializer.class); methodInfo.setControllerMethod(consumeXml); methodInfo.getValuedParameters()[0].setValue("original1"); methodInfo.getValuedParameters()[1].setValue("original2"); when(request.getContentType()).thenReturn("application/xml"); when(deserializer.deserialize(null, consumeXml)).thenReturn(new Object[] {null, "deserialized"}); when(deserializers.deserializerFor("application/xml", container)).thenReturn(deserializer); observer.deserializes(new InterceptorsReady(consumeXml), request, methodInfo, status); assertEquals(methodInfo.getValuedParameters()[0].getValue(), "original1"); assertEquals(methodInfo.getValuedParameters()[1].getValue(), "deserialized"); } | public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } | DeserializingObserver { public void deserializes(@Observes InterceptorsReady event, HttpServletRequest request, MethodInfo methodInfo, Status status) throws IOException { ControllerMethod method = event.getControllerMethod(); if (!method.containsAnnotation(Consumes.class)) return; List<String> supported = asList(method.getMethod().getAnnotation(Consumes.class).value()); if(request.getContentType() == null) { logger.warn("Request does not have Content-Type and parameters will be not deserialized"); return; } String contentType = mime(request.getContentType()); if (!supported.isEmpty() && !supported.contains(contentType)) { unsupported("Request with media type [%s]. Expecting one of %s.", status, contentType, supported); return; } Deserializer deserializer = deserializers.deserializerFor(contentType, container); if (deserializer == null) { unsupported("Unable to handle media type [%s]: no deserializer found.", status, contentType); return; } Object[] deserialized = deserializer.deserialize(request.getInputStream(), method); logger.debug("Deserialized parameters for {} are {} ", method, deserialized); for (int i = 0; i < deserialized.length; i++) { if (deserialized[i] != null) { methodInfo.setParameter(i, deserialized[i]); } } } protected DeserializingObserver(); @Inject DeserializingObserver(Deserializers deserializers, Container container); void deserializes(@Observes InterceptorsReady event, HttpServletRequest request,
MethodInfo methodInfo, Status status); } |
@Test public void shouldTranslateAsteriskAsEmpty() throws Exception { Method method = Controller.class.getDeclaredMethod("store", Client.class); String uri = getDefaultParameterControlForUrl("/clients/.*").fillUri(nameProvider.parametersFor(method), client(3L)); assertThat(uri, is(equalTo("/clients/"))); } | @Override public String fillUri(Parameter[] paramNames, Object... paramValues) { if (paramNames.length != paramValues.length) { String message = String.format("paramNames must have the same length as paramValues. Names: %s Values: %s", Arrays.toString(paramNames), Arrays.toString(paramValues)); throw new IllegalArgumentException(message); } String[] splittedPatterns = StringUtils.extractParameters(originalPattern); String base = originalPattern; for (int i=0; i<parameters.size(); i++) { String key = parameters.get(i); Object param = selectParam(key, paramNames, paramValues); Object result = evaluator.get(param, key); if (result != null) { Class<?> type = result.getClass(); if (converters.existsTwoWayFor(type)) { TwoWayConverter converter = converters.twoWayConverterFor(type); result = converter.convert(result); } } String parameter = encodeParameter(result == null ? "" : result.toString()); base = base.replace("{" + splittedPatterns[i] + "}", result == null ? "" : parameter); } return base.replaceAll("\\.\\*", ""); } | DefaultParametersControl implements ParametersControl { @Override public String fillUri(Parameter[] paramNames, Object... paramValues) { if (paramNames.length != paramValues.length) { String message = String.format("paramNames must have the same length as paramValues. Names: %s Values: %s", Arrays.toString(paramNames), Arrays.toString(paramValues)); throw new IllegalArgumentException(message); } String[] splittedPatterns = StringUtils.extractParameters(originalPattern); String base = originalPattern; for (int i=0; i<parameters.size(); i++) { String key = parameters.get(i); Object param = selectParam(key, paramNames, paramValues); Object result = evaluator.get(param, key); if (result != null) { Class<?> type = result.getClass(); if (converters.existsTwoWayFor(type)) { TwoWayConverter converter = converters.twoWayConverterFor(type); result = converter.convert(result); } } String parameter = encodeParameter(result == null ? "" : result.toString()); base = base.replace("{" + splittedPatterns[i] + "}", result == null ? "" : parameter); } return base.replaceAll("\\.\\*", ""); } } | DefaultParametersControl implements ParametersControl { @Override public String fillUri(Parameter[] paramNames, Object... paramValues) { if (paramNames.length != paramValues.length) { String message = String.format("paramNames must have the same length as paramValues. Names: %s Values: %s", Arrays.toString(paramNames), Arrays.toString(paramValues)); throw new IllegalArgumentException(message); } String[] splittedPatterns = StringUtils.extractParameters(originalPattern); String base = originalPattern; for (int i=0; i<parameters.size(); i++) { String key = parameters.get(i); Object param = selectParam(key, paramNames, paramValues); Object result = evaluator.get(param, key); if (result != null) { Class<?> type = result.getClass(); if (converters.existsTwoWayFor(type)) { TwoWayConverter converter = converters.twoWayConverterFor(type); result = converter.convert(result); } } String parameter = encodeParameter(result == null ? "" : result.toString()); base = base.replace("{" + splittedPatterns[i] + "}", result == null ? "" : parameter); } return base.replaceAll("\\.\\*", ""); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); } | DefaultParametersControl implements ParametersControl { @Override public String fillUri(Parameter[] paramNames, Object... paramValues) { if (paramNames.length != paramValues.length) { String message = String.format("paramNames must have the same length as paramValues. Names: %s Values: %s", Arrays.toString(paramNames), Arrays.toString(paramValues)); throw new IllegalArgumentException(message); } String[] splittedPatterns = StringUtils.extractParameters(originalPattern); String base = originalPattern; for (int i=0; i<parameters.size(); i++) { String key = parameters.get(i); Object param = selectParam(key, paramNames, paramValues); Object result = evaluator.get(param, key); if (result != null) { Class<?> type = result.getClass(); if (converters.existsTwoWayFor(type)) { TwoWayConverter converter = converters.twoWayConverterFor(type); result = converter.convert(result); } } String parameter = encodeParameter(result == null ? "" : result.toString()); base = base.replace("{" + splittedPatterns[i] + "}", result == null ? "" : parameter); } return base.replaceAll("\\.\\*", ""); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } | DefaultParametersControl implements ParametersControl { @Override public String fillUri(Parameter[] paramNames, Object... paramValues) { if (paramNames.length != paramValues.length) { String message = String.format("paramNames must have the same length as paramValues. Names: %s Values: %s", Arrays.toString(paramNames), Arrays.toString(paramValues)); throw new IllegalArgumentException(message); } String[] splittedPatterns = StringUtils.extractParameters(originalPattern); String base = originalPattern; for (int i=0; i<parameters.size(); i++) { String key = parameters.get(i); Object param = selectParam(key, paramNames, paramValues); Object result = evaluator.get(param, key); if (result != null) { Class<?> type = result.getClass(); if (converters.existsTwoWayFor(type)) { TwoWayConverter converter = converters.twoWayConverterFor(type); result = converter.convert(result); } } String parameter = encodeParameter(result == null ? "" : result.toString()); base = base.replace("{" + splittedPatterns[i] + "}", result == null ? "" : parameter); } return base.replaceAll("\\.\\*", ""); } DefaultParametersControl(String originalPattern, Map<String, String> parameterPatterns, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); DefaultParametersControl(String originalPattern, Converters converters, Evaluator evaluator, EncodingHandler encodingHandler); @Override String fillUri(Parameter[] paramNames, Object... paramValues); @Override boolean matches(String uri); @Override void fillIntoRequest(String uri, MutableRequest request); @Override String apply(String[] values); } |
@Test public void testIfUploadedFileIsConverted() { when(request.getAttribute("myfile")).thenReturn(file); UploadedFileConverter converter = new UploadedFileConverter(request); UploadedFile uploadedFile = converter.convert("myfile", UploadedFile.class); assertEquals(file, uploadedFile); } | @Override public UploadedFile convert(String value, Class<? extends UploadedFile> type) { Object upload = request.getAttribute(value); return type.cast(upload); } | UploadedFileConverter implements Converter<UploadedFile> { @Override public UploadedFile convert(String value, Class<? extends UploadedFile> type) { Object upload = request.getAttribute(value); return type.cast(upload); } } | UploadedFileConverter implements Converter<UploadedFile> { @Override public UploadedFile convert(String value, Class<? extends UploadedFile> type) { Object upload = request.getAttribute(value); return type.cast(upload); } protected UploadedFileConverter(); @Inject UploadedFileConverter(HttpServletRequest request); } | UploadedFileConverter implements Converter<UploadedFile> { @Override public UploadedFile convert(String value, Class<? extends UploadedFile> type) { Object upload = request.getAttribute(value); return type.cast(upload); } protected UploadedFileConverter(); @Inject UploadedFileConverter(HttpServletRequest request); @Override UploadedFile convert(String value, Class<? extends UploadedFile> type); } | UploadedFileConverter implements Converter<UploadedFile> { @Override public UploadedFile convert(String value, Class<? extends UploadedFile> type) { Object upload = request.getAttribute(value); return type.cast(upload); } protected UploadedFileConverter(); @Inject UploadedFileConverter(HttpServletRequest request); @Override UploadedFile convert(String value, Class<? extends UploadedFile> type); } |
@Test public void shouldNotAcceptFormURLEncoded() { MultipartConfig config = spy(new DefaultMultipartConfig()); when(request.getContentType()).thenReturn("application/x-www-form-urlencoded"); when(request.getMethod()).thenReturn("POST"); observer.upload(event, request, config, validator); verifyZeroInteractions(config); } | public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax(uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax(uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug("Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } } | CommonsUploadMultipartObserver { public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax(uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax(uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug("Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } } } | CommonsUploadMultipartObserver { public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax(uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax(uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug("Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } } } | CommonsUploadMultipartObserver { public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax(uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax(uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug("Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } } void upload(@Observes ControllerFound event, MutableRequest request,
MultipartConfig config, Validator validator); } | CommonsUploadMultipartObserver { public void upload(@Observes ControllerFound event, MutableRequest request, MultipartConfig config, Validator validator) { if (!ServletFileUpload.isMultipartContent(request)) { return; } logger.info("Request contains multipart data. Try to parse with commons-upload."); final Multiset<String> indexes = HashMultiset.create(); final Multimap<String, String> params = LinkedListMultimap.create(); ServletFileUpload uploader = createServletFileUpload(config); UploadSizeLimit uploadSizeLimit = event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class); uploader.setSizeMax(uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit()); uploader.setFileSizeMax(uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit()); logger.debug("Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax()); try { final List<FileItem> items = uploader.parseRequest(request); logger.debug("Found {} attributes in the multipart form submission. Parsing them.", items.size()); for (FileItem item : items) { String name = item.getFieldName(); name = fixIndexedParameters(name, indexes); if (item.isFormField()) { logger.debug("{} is a field", name); params.put(name, getValue(item, request)); } else if (isNotEmpty(item)) { logger.debug("{} is a file", name); processFile(item, name, request); } else { logger.debug("A file field is empty: {}", item.getFieldName()); } } for (String paramName : params.keySet()) { Collection<String> paramValues = params.get(paramName); request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()])); } } catch (final SizeLimitExceededException e) { reportSizeLimitExceeded(e, validator); } catch (FileUploadException e) { reportFileUploadException(e, validator); } } void upload(@Observes ControllerFound event, MutableRequest request,
MultipartConfig config, Validator validator); } |
@Test public void shouldHandle404() throws Exception { when(translator.translate(webRequest)).thenThrow(new ControllerNotFoundException()); observer.handle(requestStarted); verify(notFoundHandler).couldntFind(chain, webRequest, webResponse); verify(interceptorStack, never()).start(); } | public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } |
@Test public void shouldHandle405() throws Exception { EnumSet<HttpMethod> allowedMethods = EnumSet.of(HttpMethod.GET); when(translator.translate(webRequest)).thenThrow(new MethodNotAllowedException(allowedMethods, POST.toString())); observer.handle(requestStarted); verify(methodNotAllowedHandler).deny(webRequest, webResponse, allowedMethods); verify(interceptorStack, never()).start(); } | public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } |
@Test public void shouldHandle400() throws Exception { InvalidInputException invalidInputException = new InvalidInputException(""); when(translator.translate(webRequest)).thenThrow(invalidInputException); observer.handle(requestStarted); verify(interceptorStack, never()).start(); verify(invalidInputHandler).deny(invalidInputException); } | public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } |
@Test public void shouldUseControllerMethodFoundWithNextInterceptor() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(interceptorStack).start(); } | public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } |
@Test public void shouldFireTheControllerWasFound() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(controllerFoundEvent).fire(any(ControllerFound.class)); } | public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } |
@Test public void shouldFireTheRequestSuceeded() throws Exception { final ControllerMethod method = mock(ControllerMethod.class); when(translator.translate(webRequest)).thenReturn(method); observer.handle(requestStarted); verify(requestSucceededEvent).fire(any(RequestSucceded.class)); } | public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } | RequestHandlerObserver { public void handle(@Observes VRaptorRequestStarted event) { MutableResponse response = event.getResponse(); MutableRequest request = event.getRequest(); try { ControllerMethod method = translator.translate(request); controllerFoundEvent.fire(new ControllerFound(method)); interceptorStack.start(); endRequestEvent.fire(new RequestSucceded(request, response)); } catch (ControllerNotFoundException e) { LOGGER.debug("Could not found controller method", e); controllerNotFoundHandler.couldntFind(event.getChain(), request, response); } catch (MethodNotAllowedException e) { LOGGER.debug("Method is not allowed", e); methodNotAllowedHandler.deny(request, response, e.getAllowedMethods()); } catch (InvalidInputException e) { LOGGER.debug("Invalid input", e); invalidInputHandler.deny(e); } } protected RequestHandlerObserver(); @Inject RequestHandlerObserver(UrlToControllerTranslator translator,
ControllerNotFoundHandler controllerNotFoundHandler, MethodNotAllowedHandler methodNotAllowedHandler,
Event<ControllerFound> controllerFoundEvent, Event<RequestSucceded> endRequestEvent,
InterceptorStack interceptorStack, InvalidInputHandler invalidInputHandler); void handle(@Observes VRaptorRequestStarted event); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.