diff --git a/arquillian/RESTEASY-1056-jetty-bv11/src/test/java/org/jboss/resteasy/test/resteasy1056/MissingCDITest.java b/arquillian/RESTEASY-1056-jetty-bv11/src/test/java/org/jboss/resteasy/test/resteasy1056/MissingCDITest.java index 52724a5a955..c8b8ba51072 100644 --- a/arquillian/RESTEASY-1056-jetty-bv11/src/test/java/org/jboss/resteasy/test/resteasy1056/MissingCDITest.java +++ b/arquillian/RESTEASY-1056-jetty-bv11/src/test/java/org/jboss/resteasy/test/resteasy1056/MissingCDITest.java @@ -34,49 +34,48 @@ @RunAsClient public class MissingCDITest { - private static final Logger LOG = Logger.getLogger(MissingCDITest.class); + private static final Logger LOG = Logger.getLogger(MissingCDITest.class); - @Deployment - public static Archive createTestArchive() { - WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-1056.war") - .addClasses(TestApplication.class, TestResource.class) - .addAsWebInfResource("web.xml"); - return war; - } + @Deployment + public static Archive createTestArchive() { + WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-1056.war") + .addClasses(TestApplication.class, TestResource.class) + .addAsWebInfResource("web.xml"); + return war; + } - @ArquillianResource - URI baseUri; + @ArquillianResource + URI baseUri; - @Test - public void testMissingCDIValid() throws Exception { - Response response = ResteasyClientBuilder.newClient().target(baseUri.toString() + "test/17").request().get(); - LOG.info("Status: " + response.getStatus()); - String entity = response.readEntity(String.class); - LOG.info("Result: " + entity); - assertEquals(200, response.getStatus()); - Assert.assertEquals("17", entity); - } + @Test + public void testMissingCDIValid() throws Exception { + Response response = ResteasyClientBuilder.newClient().target(baseUri.toString() + "test/17").request().get(); + LOG.info("Status: " + response.getStatus()); + String entity = response.readEntity(String.class); + LOG.info("Result: " + entity); + assertEquals(200, response.getStatus()); + Assert.assertEquals("17", entity); + } - @Test - public void testMissingCDIInvalid() throws Exception { - Response response = ResteasyClientBuilder.newClient().target(baseUri.toString() + "test/0").request().get(); - LOG.info("Status: " + response.getStatus()); - String entity = response.readEntity(String.class); - LOG.info("Result: " + entity); - assertEquals(400, response.getStatus()); - ResteasyViolationException e = new ResteasyViolationException(entity); - countViolations(e, 1, 0, 0, 0, 1, 0); - ResteasyConstraintViolation cv = e.getParameterViolations().iterator().next(); - Assert.assertTrue(cv.getMessage().equals("must be greater than or equal to 7")); - } + @Test + public void testMissingCDIInvalid() throws Exception { + Response response = ResteasyClientBuilder.newClient().target(baseUri.toString() + "test/0").request().get(); + LOG.info("Status: " + response.getStatus()); + String entity = response.readEntity(String.class); + LOG.info("Result: " + entity); + assertEquals(400, response.getStatus()); + ResteasyViolationException e = new ResteasyViolationException(entity); + countViolations(e, 1, 0, 0, 0, 1, 0); + ResteasyConstraintViolation cv = e.getParameterViolations().iterator().next(); + Assert.assertTrue(cv.getMessage().equals("must be greater than or equal to 7")); + } - protected void countViolations(ResteasyViolationException e, int totalCount, int fieldCount, int propertyCount, int classCount, int parameterCount, int returnValueCount) { - Assert.assertEquals(totalCount, e.getViolations().size()); - Assert.assertEquals(fieldCount, e.getFieldViolations().size()); - Assert.assertEquals(propertyCount, e.getPropertyViolations().size()); - Assert.assertEquals(classCount, e.getClassViolations().size()); - Assert.assertEquals(parameterCount, e.getParameterViolations().size()); - Assert.assertEquals(returnValueCount, e.getReturnValueViolations().size()); - } + protected void countViolations(ResteasyViolationException e, int totalCount, int fieldCount, int propertyCount, int classCount, int parameterCount, int returnValueCount) { + Assert.assertEquals(totalCount, e.getViolations().size()); + Assert.assertEquals(fieldCount, e.getFieldViolations().size()); + Assert.assertEquals(propertyCount, e.getPropertyViolations().size()); + Assert.assertEquals(classCount, e.getClassViolations().size()); + Assert.assertEquals(parameterCount, e.getParameterViolations().size()); + Assert.assertEquals(returnValueCount, e.getReturnValueViolations().size()); + } } - diff --git a/arquillian/RESTEASY-736-jetty/src/main/java/org/jboss/resteasy/resteasy736/TestResource.java b/arquillian/RESTEASY-736-jetty/src/main/java/org/jboss/resteasy/resteasy736/TestResource.java index 9f66cb8ad11..d8f26169651 100644 --- a/arquillian/RESTEASY-736-jetty/src/main/java/org/jboss/resteasy/resteasy736/TestResource.java +++ b/arquillian/RESTEASY-736-jetty/src/main/java/org/jboss/resteasy/resteasy736/TestResource.java @@ -39,7 +39,7 @@ public void run() Thread.sleep(10000); Response jaxrs = Response.ok("test").type(MediaType.TEXT_PLAIN).build(); response.setResponse(jaxrs); - LOG.info("TestResource: async thread finished"); + LOG.info("TestResource: async thread finished"); } catch (Exception e) { @@ -65,7 +65,7 @@ public void run() Thread.sleep(35000); // Jetty async timeout defaults to 30000. Response jaxrs = Response.ok("test").type(MediaType.TEXT_PLAIN).build(); response.setResponse(jaxrs); - LOG.info("TestResource: async thread finished"); + LOG.info("TestResource: async thread finished"); } catch (Exception e) { diff --git a/arquillian/RESTEASY-736-jetty/src/test/java/org/jboss/resteasy/test/resteasy736/AsyncTimeoutTest.java b/arquillian/RESTEASY-736-jetty/src/test/java/org/jboss/resteasy/test/resteasy736/AsyncTimeoutTest.java index da5fe3dba40..38565912135 100644 --- a/arquillian/RESTEASY-736-jetty/src/test/java/org/jboss/resteasy/test/resteasy736/AsyncTimeoutTest.java +++ b/arquillian/RESTEASY-736-jetty/src/test/java/org/jboss/resteasy/test/resteasy736/AsyncTimeoutTest.java @@ -32,32 +32,32 @@ @RunAsClient public class AsyncTimeoutTest { - private static final Logger LOG = Logger.getLogger(AsyncTimeoutTest.class); + private static final Logger LOG = Logger.getLogger(AsyncTimeoutTest.class); - @Deployment - public static Archive createTestArchive() { - WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-736.war") - .addClasses(TestApplication.class, TestResource.class) - .addClasses(AsyncTimeoutTest.class) - .addAsWebInfResource("web.xml"); - return war; - } + @Deployment + public static Archive createTestArchive() { + WebArchive war = ShrinkWrap.create(WebArchive.class, "RESTEASY-736.war") + .addClasses(TestApplication.class, TestResource.class) + .addClasses(AsyncTimeoutTest.class) + .addAsWebInfResource("web.xml"); + return war; + } - @ArquillianResource - URI url; + @ArquillianResource + URI url; - @Test - public void testAsynchTimeout() throws Exception { - LOG.info("url = " + url); - Builder request = ResteasyClientBuilder.newClient().target(url.toString() + "test/").request(); - long start = System.currentTimeMillis(); - LOG.info("start: " + start); - Response response = null; - try { + @Test + public void testAsynchTimeout() throws Exception { + LOG.info("url = " + url); + Builder request = ResteasyClientBuilder.newClient().target(url.toString() + "test/").request(); + long start = System.currentTimeMillis(); + LOG.info("start: " + start); + Response response = null; + try { response = request.get(); - } catch (Exception e) { + } catch (Exception e) { LOG.error(e.getMessage(), e); - } finally { + } finally { LOG.info("finish: " + System.currentTimeMillis()); long elapsed = System.currentTimeMillis() - start; LOG.info("elapsed: " + elapsed + " ms"); @@ -66,21 +66,21 @@ public void testAsynchTimeout() throws Exception { LOG.info("response: " + response.readEntity(String.class)); Assert.assertEquals("Status is wrong", 503, response.getStatus()); assertTrue(elapsed < 10000); - } - } + } + } - @Ignore - @Test - public void testDefaultAsynchTimeout() throws Exception { - Builder request = ResteasyClientBuilder.newClient().target(url.toString() + "default/").request(); - long start = System.currentTimeMillis(); - LOG.info("start: " + start); - Response response = null; - try { + @Ignore + @Test + public void testDefaultAsynchTimeout() throws Exception { + Builder request = ResteasyClientBuilder.newClient().target(url.toString() + "default/").request(); + long start = System.currentTimeMillis(); + LOG.info("start: " + start); + Response response = null; + try { response = request.get(); - } catch (Exception e) { + } catch (Exception e) { LOG.error("Error: ", e); - } finally { + } finally { LOG.info("finish: " + System.currentTimeMillis()); long elapsed = System.currentTimeMillis() - start; LOG.info("elapsed: " + elapsed + " ms"); @@ -89,7 +89,7 @@ public void testDefaultAsynchTimeout() throws Exception { LOG.info("response: " + response.readEntity(String.class)); Assert.assertEquals("Wrong response", 503, response.getStatus()); Assert.assertTrue("Should timeout", elapsed < 36000); // Jetty async timeout defaults to 30000. - } - } + } + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/CachedPrimaryZone.java b/eagledns/src/main/java/se/unlogic/eagledns/CachedPrimaryZone.java index 06825ecc988..4ee9a2121e5 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/CachedPrimaryZone.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/CachedPrimaryZone.java @@ -4,28 +4,28 @@ public class CachedPrimaryZone { - protected Zone zone; - protected ZoneProvider zoneProvider; + protected Zone zone; + protected ZoneProvider zoneProvider; - public CachedPrimaryZone(Zone zone, ZoneProvider zoneProvider) { + public CachedPrimaryZone(Zone zone, ZoneProvider zoneProvider) { - super(); - this.zone = zone; - this.zoneProvider = zoneProvider; - } + super(); + this.zone = zone; + this.zoneProvider = zoneProvider; + } - public Zone getZone() { + public Zone getZone() { - return zone; - } + return zone; + } - public void setZone(Zone zone) { + public void setZone(Zone zone) { - this.zone = zone; - } + this.zone = zone; + } - public ZoneProvider getZoneProvider() { + public ZoneProvider getZoneProvider() { - return zoneProvider; - } + return zoneProvider; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/CachedSecondaryZone.java b/eagledns/src/main/java/se/unlogic/eagledns/CachedSecondaryZone.java index 9ef9b71e80a..0f48506edb4 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/CachedSecondaryZone.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/CachedSecondaryZone.java @@ -14,111 +14,111 @@ public class CachedSecondaryZone { - private Logger log = Logger.getLogger(this.getClass()); - protected ZoneProvider zoneProvider; - private SecondaryZone secondaryZone; + private Logger log = Logger.getLogger(this.getClass()); + protected ZoneProvider zoneProvider; + private SecondaryZone secondaryZone; - public CachedSecondaryZone(ZoneProvider zoneProvider, SecondaryZone secondaryZone) { + public CachedSecondaryZone(ZoneProvider zoneProvider, SecondaryZone secondaryZone) { - this.zoneProvider = zoneProvider; - this.secondaryZone = secondaryZone; - //this.update(); + this.zoneProvider = zoneProvider; + this.secondaryZone = secondaryZone; + //this.update(); - if(this.secondaryZone.getZoneCopy() != null){ + if(this.secondaryZone.getZoneCopy() != null){ - log.info("Using stored zone data for sedondary zone " + this.secondaryZone.getZoneName()); - } - } + log.info("Using stored zone data for sedondary zone " + this.secondaryZone.getZoneName()); + } + } - public SecondaryZone getSecondaryZone() { + public SecondaryZone getSecondaryZone() { - return secondaryZone; - } + return secondaryZone; + } - public void setSecondaryZone(SecondaryZone secondaryZone) { + public void setSecondaryZone(SecondaryZone secondaryZone) { - this.secondaryZone = secondaryZone; - } + this.secondaryZone = secondaryZone; + } - /** - * Updates this secondary zone from the primary zone - * @param axfrTimeout - */ - public void update(int axfrTimeout) { + /** + * Updates this secondary zone from the primary zone + * @param axfrTimeout + */ + public void update(int axfrTimeout) { - try { - ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(this.secondaryZone.getZoneName(), this.secondaryZone.getRemoteServerAddress(), null); - xfrin.setDClass(DClass.value(this.secondaryZone.getDclass())); - xfrin.setTimeout(axfrTimeout); + try { + ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(this.secondaryZone.getZoneName(), this.secondaryZone.getRemoteServerAddress(), null); + xfrin.setDClass(DClass.value(this.secondaryZone.getDclass())); + xfrin.setTimeout(axfrTimeout); - List records = xfrin.run(); + List records = xfrin.run(); - if (!xfrin.isAXFR()) { + if (!xfrin.isAXFR()) { - log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", response is not a valid AXFR!"); + log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", response is not a valid AXFR!"); - return; - } + return; + } - Zone axfrZone = new Zone(this.secondaryZone.getZoneName(),records.toArray(new Record[records.size()])); + Zone axfrZone = new Zone(this.secondaryZone.getZoneName(),records.toArray(new Record[records.size()])); - log.debug("Zone " + this.secondaryZone.getZoneName() + " successfully transfered from server " + this.secondaryZone.getRemoteServerAddress()); + log.debug("Zone " + this.secondaryZone.getZoneName() + " successfully transfered from server " + this.secondaryZone.getRemoteServerAddress()); - if(!axfrZone.getSOA().getName().equals(this.secondaryZone.getZoneName())){ + if(!axfrZone.getSOA().getName().equals(this.secondaryZone.getZoneName())){ - log.warn("Invalid AXFR zone name in response when updating secondary zone " + this.secondaryZone.getZoneName() + ". Got zone name " + axfrZone.getSOA().getName() + " in respons."); - } + log.warn("Invalid AXFR zone name in response when updating secondary zone " + this.secondaryZone.getZoneName() + ". Got zone name " + axfrZone.getSOA().getName() + " in respons."); + } - if(this.secondaryZone.getZoneCopy() == null || this.secondaryZone.getZoneCopy().getSOA().getSerial() != axfrZone.getSOA().getSerial()){ + if(this.secondaryZone.getZoneCopy() == null || this.secondaryZone.getZoneCopy().getSOA().getSerial() != axfrZone.getSOA().getSerial()){ - this.secondaryZone.setZoneCopy(axfrZone); - this.secondaryZone.setDownloaded(new Timestamp(System.currentTimeMillis())); - this.zoneProvider.zoneUpdated(this.secondaryZone); + this.secondaryZone.setZoneCopy(axfrZone); + this.secondaryZone.setDownloaded(new Timestamp(System.currentTimeMillis())); + this.zoneProvider.zoneUpdated(this.secondaryZone); - log.info("Zone " + this.secondaryZone.getZoneName() + " successfully updated from server " + this.secondaryZone.getRemoteServerAddress()); - }else{ + log.info("Zone " + this.secondaryZone.getZoneName() + " successfully updated from server " + this.secondaryZone.getRemoteServerAddress()); + }else{ - log.info("Zone " + this.secondaryZone.getZoneName() + " is already up to date with serial " + axfrZone.getSOA().getSerial()); - this.zoneProvider.zoneChecked(secondaryZone); - } + log.info("Zone " + this.secondaryZone.getZoneName() + " is already up to date with serial " + axfrZone.getSOA().getSerial()); + this.zoneProvider.zoneChecked(secondaryZone); + } - } catch (IOException e) { + } catch (IOException e) { - log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", " + e); + log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", " + e); - checkExpired(); + checkExpired(); - } catch (ZoneTransferException e) { + } catch (ZoneTransferException e) { - log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", " + e); + log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", " + e); - checkExpired(); + checkExpired(); - }catch (RuntimeException e) { + }catch (RuntimeException e) { - log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", " + e); + log.warn("Unable to transfer zone " + this.secondaryZone.getZoneName() + " from server " + this.secondaryZone.getRemoteServerAddress() + ", " + e); - checkExpired(); + checkExpired(); - }finally{ + }finally{ - this.secondaryZone.setDownloaded(new Timestamp(System.currentTimeMillis())); - } - } + this.secondaryZone.setDownloaded(new Timestamp(System.currentTimeMillis())); + } + } - private void checkExpired() { + private void checkExpired() { - if(this.secondaryZone.getZoneCopy() != null && (System.currentTimeMillis() - this.secondaryZone.getDownloaded().getTime()) > (this.secondaryZone.getZoneCopy().getSOA().getExpire() * 1000)){ + if(this.secondaryZone.getZoneCopy() != null && (System.currentTimeMillis() - this.secondaryZone.getDownloaded().getTime()) > (this.secondaryZone.getZoneCopy().getSOA().getExpire() * 1000)){ - log.warn("AXFR copy of secondary zone " + secondaryZone.getZoneName() + " has expired, deleting zone data..."); + log.warn("AXFR copy of secondary zone " + secondaryZone.getZoneName() + " has expired, deleting zone data..."); - this.secondaryZone.setZoneCopy(null); - this.secondaryZone.setDownloaded(null); - this.zoneProvider.zoneUpdated(this.secondaryZone); - } - } + this.secondaryZone.setZoneCopy(null); + this.secondaryZone.setDownloaded(null); + this.zoneProvider.zoneUpdated(this.secondaryZone); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/EagleDNS.java b/eagledns/src/main/java/se/unlogic/eagledns/EagleDNS.java index 2e7df99bc16..54b16b20b54 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/EagleDNS.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/EagleDNS.java @@ -71,42 +71,42 @@ public class EagleDNS implements Runnable, EagleManager { - public static final String VERSION = "Eagle DNS 1.0"; + public static final String VERSION = "Eagle DNS 1.0"; - static final int FLAG_DNSSECOK = 1; - static final int FLAG_SIGONLY = 2; + static final int FLAG_DNSSECOK = 1; + static final int FLAG_SIGONLY = 2; - private final Logger log = Logger.getLogger(this.getClass()); + private final Logger log = Logger.getLogger(this.getClass()); - private final ConcurrentHashMap primaryZoneMap = new ConcurrentHashMap(); - private final ConcurrentHashMap secondaryZoneMap = new ConcurrentHashMap(); - private final HashMap TSIGs = new HashMap(); + private final ConcurrentHashMap primaryZoneMap = new ConcurrentHashMap(); + private final ConcurrentHashMap secondaryZoneMap = new ConcurrentHashMap(); + private final HashMap TSIGs = new HashMap(); - private final HashMap zoneProviders = new HashMap(); + private final HashMap zoneProviders = new HashMap(); - private int tcpThreadPoolSize = 20; - private int udpThreadPoolSize = 20; + private int tcpThreadPoolSize = 20; + private int udpThreadPoolSize = 20; - private int tcpThreadPoolShutdownTimeout = 60; - private int udpThreadPoolShutdownTimeout = 60; + private int tcpThreadPoolShutdownTimeout = 60; + private int udpThreadPoolShutdownTimeout = 60; - private ArrayList tcpMonitorThreads = new ArrayList(); - private ArrayList udpMonitorThreads = new ArrayList(); + private ArrayList tcpMonitorThreads = new ArrayList(); + private ArrayList udpMonitorThreads = new ArrayList(); - private ThreadPoolExecutor tcpThreadPool; - private ThreadPoolExecutor udpThreadPool; + private ThreadPoolExecutor tcpThreadPool; + private ThreadPoolExecutor udpThreadPool; - private int axfrTimeout = 60; + private int axfrTimeout = 60; - private String remotePassword; - private Integer remotePort; - private LoginHandler loginHandler; + private String remotePassword; + private Integer remotePort; + private LoginHandler loginHandler; - private Timer secondaryZoneUpdateTimer; - private RunnableTimerTask timerTask; + private Timer secondaryZoneUpdateTimer; + private RunnableTimerTask timerTask; private String configFilePath; - private boolean shutdown = false; + private boolean shutdown = false; public EagleDNS() throws UnknownHostException { @@ -129,311 +129,311 @@ public void start() throws UnknownHostException { //DOMConfigurator.configure(logurl); //DOMConfigurator.configure("conf/log4j.xml"); - log.info(VERSION + " starting..."); + log.info(VERSION + " starting..."); - XMLSettingNode configFile; + XMLSettingNode configFile; - try { - log.debug("Parsing config file..." + configFilePath); - configFile = new XMLSettingNode(configFilePath); + try { + log.debug("Parsing config file..." + configFilePath); + configFile = new XMLSettingNode(configFilePath); - } catch (Exception e) { + } catch (Exception e) { - log.fatal("Unable to open config file " + configFilePath + ", aborting startup!"); - log.info("Unable to open config file " + configFilePath + ", aborting startup!"); - return; - } + log.fatal("Unable to open config file " + configFilePath + ", aborting startup!"); + log.info("Unable to open config file " + configFilePath + ", aborting startup!"); + return; + } - List ports = configFile.getIntegers("/Config/System/Port"); + List ports = configFile.getIntegers("/Config/System/Port"); - if (ports.isEmpty()) { + if (ports.isEmpty()) { - log.debug("No ports found in config file " + configFilePath + ", using default port 53"); - ports.add(new Integer(53)); - } + log.debug("No ports found in config file " + configFilePath + ", using default port 53"); + ports.add(new Integer(53)); + } - List addresses = new ArrayList(); - List addressStrings = configFile.getStrings("/Config/System/Address"); + List addresses = new ArrayList(); + List addressStrings = configFile.getStrings("/Config/System/Address"); - if (addressStrings == null || addressStrings.isEmpty()) { + if (addressStrings == null || addressStrings.isEmpty()) { - log.debug("No addresses found in config, listening on all addresses (0.0.0.0)"); - addresses.add(Address.getByAddress("0.0.0.0")); + log.debug("No addresses found in config, listening on all addresses (0.0.0.0)"); + addresses.add(Address.getByAddress("0.0.0.0")); - } else { + } else { - for (String addressString : addressStrings) { + for (String addressString : addressStrings) { - try { + try { - addresses.add(Address.getByAddress(addressString)); + addresses.add(Address.getByAddress(addressString)); - } catch (UnknownHostException e) { + } catch (UnknownHostException e) { - log.error("Invalid address " + addressString + " specified in config file, skipping address " + e); - } - } + log.error("Invalid address " + addressString + " specified in config file, skipping address " + e); + } + } - if (addresses.isEmpty()) { + if (addresses.isEmpty()) { - log.fatal("None of the " + addressStrings.size() + " addresses specified in the config file are valid, aborting startup!\n" + "Correct the addresses or remove them from the config file if you want to listen on all interfaces."); + log.fatal("None of the " + addressStrings.size() + " addresses specified in the config file are valid, aborting startup!\n" + "Correct the addresses or remove them from the config file if you want to listen on all interfaces."); return; - } - } + } + } - Integer tcpThreadPoolSize = configFile.getInteger("/Config/System/TCPThreadPoolSize"); + Integer tcpThreadPoolSize = configFile.getInteger("/Config/System/TCPThreadPoolSize"); - if (tcpThreadPoolSize != null) { + if (tcpThreadPoolSize != null) { - log.debug("Setting TCP thread pool size to " + tcpThreadPoolSize); - this.tcpThreadPoolSize = tcpThreadPoolSize; - } + log.debug("Setting TCP thread pool size to " + tcpThreadPoolSize); + this.tcpThreadPoolSize = tcpThreadPoolSize; + } - Integer tcpThreadPoolShutdownTimeout = configFile.getInteger("/Config/System/TCPThreadPoolShutdownTimeout"); + Integer tcpThreadPoolShutdownTimeout = configFile.getInteger("/Config/System/TCPThreadPoolShutdownTimeout"); - if (tcpThreadPoolShutdownTimeout != null) { + if (tcpThreadPoolShutdownTimeout != null) { - log.debug("Setting TCP thread pool shutdown timeout to " + tcpThreadPoolSize + " seconds"); - this.tcpThreadPoolShutdownTimeout = tcpThreadPoolShutdownTimeout; - } + log.debug("Setting TCP thread pool shutdown timeout to " + tcpThreadPoolSize + " seconds"); + this.tcpThreadPoolShutdownTimeout = tcpThreadPoolShutdownTimeout; + } - Integer udpThreadPoolSize = configFile.getInteger("/Config/System/UDPThreadPoolSize"); + Integer udpThreadPoolSize = configFile.getInteger("/Config/System/UDPThreadPoolSize"); - if (udpThreadPoolSize != null) { + if (udpThreadPoolSize != null) { - log.debug("Setting UDP thread pool size to " + udpThreadPoolSize); - this.udpThreadPoolSize = udpThreadPoolSize; - } + log.debug("Setting UDP thread pool size to " + udpThreadPoolSize); + this.udpThreadPoolSize = udpThreadPoolSize; + } - Integer udpThreadPoolShutdownTimeout = configFile.getInteger("/Config/System/UDPThreadPoolShutdownTimeout"); + Integer udpThreadPoolShutdownTimeout = configFile.getInteger("/Config/System/UDPThreadPoolShutdownTimeout"); - if (udpThreadPoolShutdownTimeout != null) { + if (udpThreadPoolShutdownTimeout != null) { - log.debug("Setting UDP thread pool shutdown timeout to " + udpThreadPoolSize + " seconds"); - this.udpThreadPoolShutdownTimeout = udpThreadPoolShutdownTimeout; - } + log.debug("Setting UDP thread pool shutdown timeout to " + udpThreadPoolSize + " seconds"); + this.udpThreadPoolShutdownTimeout = udpThreadPoolShutdownTimeout; + } - this.remotePassword = configFile.getString("/Config/System/RemoteManagementPassword"); + this.remotePassword = configFile.getString("/Config/System/RemoteManagementPassword"); - log.debug("Remote management password set to " + remotePassword); + log.debug("Remote management password set to " + remotePassword); - this.remotePort = configFile.getInteger("/Config/System/RemoteManagementPort"); + this.remotePort = configFile.getInteger("/Config/System/RemoteManagementPort"); - log.debug("Remote management port set to " + remotePort); + log.debug("Remote management port set to " + remotePort); - Integer axfrTimeout = configFile.getInteger("/Config/System/AXFRTimeout"); + Integer axfrTimeout = configFile.getInteger("/Config/System/AXFRTimeout"); - if (axfrTimeout != null) { + if (axfrTimeout != null) { - log.debug("Setting AXFR timeout to " + axfrTimeout); - this.axfrTimeout = axfrTimeout; - } + log.debug("Setting AXFR timeout to " + axfrTimeout); + this.axfrTimeout = axfrTimeout; + } - // TODO TSIG stuff + // TODO TSIG stuff - List zoneProviderElements = configFile.getSettings("/Config/ZoneProviders/ZoneProvider"); + List zoneProviderElements = configFile.getSettings("/Config/ZoneProviders/ZoneProvider"); - for (XMLSettingNode settingNode : zoneProviderElements) { + for (XMLSettingNode settingNode : zoneProviderElements) { - String name = settingNode.getString("Name"); + String name = settingNode.getString("Name"); - if (StringUtils.isEmpty(name)) { + if (StringUtils.isEmpty(name)) { - log.error("ZoneProvider element with no name set found in config, ignoring element."); - continue; - } + log.error("ZoneProvider element with no name set found in config, ignoring element."); + continue; + } - String className = settingNode.getString("Class"); + String className = settingNode.getString("Class"); - if (StringUtils.isEmpty(className)) { + if (StringUtils.isEmpty(className)) { - log.error("ZoneProvider element with no class set found in config, ignoring element."); - continue; - } + log.error("ZoneProvider element with no class set found in config, ignoring element."); + continue; + } - try { + try { - log.debug("Instantiating zone provider " + name + " (" + className + ")"); + log.debug("Instantiating zone provider " + name + " (" + className + ")"); - ZoneProvider zoneProvider = (ZoneProvider) Class.forName(className).newInstance(); + ZoneProvider zoneProvider = (ZoneProvider) Class.forName(className).newInstance(); - log.debug("Zone provider " + name + " successfully instantiated"); + log.debug("Zone provider " + name + " successfully instantiated"); - List propertyElements = settingNode.getSettings("Properties/Property"); + List propertyElements = settingNode.getSettings("Properties/Property"); - for (SettingNode propertyElement : propertyElements) { + for (SettingNode propertyElement : propertyElements) { - String propertyName = propertyElement.getString("@name"); + String propertyName = propertyElement.getString("@name"); - if (StringUtils.isEmpty(propertyName)) { + if (StringUtils.isEmpty(propertyName)) { - log.error("Property element with no name set found in config, ignoring element"); - continue; - } + log.error("Property element with no name set found in config, ignoring element"); + continue; + } - String value = propertyElement.getString("."); + String value = propertyElement.getString("."); - log.debug("Found value " + value + " for property " + propertyName); + log.debug("Found value " + value + " for property " + propertyName); - try { - Method method = zoneProvider.getClass().getMethod("set" + StringUtils.toFirstLetterUppercase(propertyName), String.class); + try { + Method method = zoneProvider.getClass().getMethod("set" + StringUtils.toFirstLetterUppercase(propertyName), String.class); - ReflectionUtils.fixMethodAccess(method); + ReflectionUtils.fixMethodAccess(method); - log.debug("Setting property " + propertyName); + log.debug("Setting property " + propertyName); - try { + try { - method.invoke(zoneProvider, value); + method.invoke(zoneProvider, value); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { - log.error("Unable to set property " + propertyName + " on zone provider " + name + " (" + className + ")", e); + log.error("Unable to set property " + propertyName + " on zone provider " + name + " (" + className + ")", e); - } catch (InvocationTargetException e) { + } catch (InvocationTargetException e) { - log.error("Unable to set property " + propertyName + " on zone provider " + name + " (" + className + ")", e); - } + log.error("Unable to set property " + propertyName + " on zone provider " + name + " (" + className + ")", e); + } - } catch (SecurityException e) { + } catch (SecurityException e) { - log.error("Unable to find matching setter method for property " + propertyName + " in zone provider " + name + " (" + className + ")", e); + log.error("Unable to find matching setter method for property " + propertyName + " in zone provider " + name + " (" + className + ")", e); - } catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { - log.error("Unable to find matching setter method for property " + propertyName + " in zone provider " + name + " (" + className + ")", e); - } - } + log.error("Unable to find matching setter method for property " + propertyName + " in zone provider " + name + " (" + className + ")", e); + } + } - try { + try { - if (zoneProvider instanceof ZoneProviderUpdatable) { - ((ZoneProviderUpdatable) zoneProvider).setChangeListener(new ZoneChangeCallback() { - public void zoneDataChanged() { - reloadZones(); - } - }); - } + if (zoneProvider instanceof ZoneProviderUpdatable) { + ((ZoneProviderUpdatable) zoneProvider).setChangeListener(new ZoneChangeCallback() { + public void zoneDataChanged() { + reloadZones(); + } + }); + } - zoneProvider.init(name); + zoneProvider.init(name); - log.debug("Zone provider " + name + " (" + className + ") successfully initialized!"); + log.debug("Zone provider " + name + " (" + className + ") successfully initialized!"); - this.zoneProviders.put(name, zoneProvider); + this.zoneProviders.put(name, zoneProvider); - } catch (Throwable e) { + } catch (Throwable e) { - log.error("Error initializing zone provider " + name + " (" + className + ")", e); - } + log.error("Error initializing zone provider " + name + " (" + className + ")", e); + } - } catch (InstantiationException e) { + } catch (InstantiationException e) { - log.error("Unable to create instance of class " + className + " for zone provider " + name, e); + log.error("Unable to create instance of class " + className + " for zone provider " + name, e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - log.error("Unable to create instance of class " + className + " for zone provider " + name, e); + log.error("Unable to create instance of class " + className + " for zone provider " + name, e); - } catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { - log.error("Unable to create instance of class " + className + " for zone provider " + name, e); - } - } + log.error("Unable to create instance of class " + className + " for zone provider " + name, e); + } + } - if (zoneProviders.isEmpty()) { - log.fatal("No zone providers found or started, aborting startup!"); - return; - } + if (zoneProviders.isEmpty()) { + log.fatal("No zone providers found or started, aborting startup!"); + return; + } - this.reloadZones(); + this.reloadZones(); - if(remotePassword == null || remotePort == null){ + if(remotePassword == null || remotePort == null){ - log.debug("Remote managed port and/or password not set, remote managent will not be available."); + log.debug("Remote managed port and/or password not set, remote managent will not be available."); - }else{ + }else{ - log.debug("Starting remote interface on port " + remotePort); + log.debug("Starting remote interface on port " + remotePort); - this.loginHandler = new LoginHandler(this, this.remotePassword); + this.loginHandler = new LoginHandler(this, this.remotePassword); - try { - EagleLogin eagleLogin = (EagleLogin) UnicastRemoteObject.exportObject(loginHandler,remotePort); - UnicastRemoteObject.exportObject(this,remotePort); + try { + EagleLogin eagleLogin = (EagleLogin) UnicastRemoteObject.exportObject(loginHandler,remotePort); + UnicastRemoteObject.exportObject(this,remotePort); - Registry registry = LocateRegistry.createRegistry(remotePort); + Registry registry = LocateRegistry.createRegistry(remotePort); - registry.bind("eagleLogin", eagleLogin); + registry.bind("eagleLogin", eagleLogin); - } catch (AccessException e) { + } catch (AccessException e) { - log.fatal("Unable to start remote manangement interface, aborting startup!",e); - return; + log.fatal("Unable to start remote manangement interface, aborting startup!",e); + return; - } catch (RemoteException e) { + } catch (RemoteException e) { - log.fatal("Unable to start remote manangement interface, aborting startup!",e); - return; + log.fatal("Unable to start remote manangement interface, aborting startup!",e); + return; - } catch (AlreadyBoundException e) { + } catch (AlreadyBoundException e) { - log.fatal("Unable to start remote manangement interface, aborting startup!",e); - return; - } - } + log.fatal("Unable to start remote manangement interface, aborting startup!",e); + return; + } + } - log.debug("Initializing TCP thread pool..."); - this.tcpThreadPool = new ThreadPoolExecutor(this.tcpThreadPoolSize, this.tcpThreadPoolSize, 1, TimeUnit.SECONDS, new LinkedBlockingQueue()); + log.debug("Initializing TCP thread pool..."); + this.tcpThreadPool = new ThreadPoolExecutor(this.tcpThreadPoolSize, this.tcpThreadPoolSize, 1, TimeUnit.SECONDS, new LinkedBlockingQueue()); - log.debug("Initializing UDP thread pool..."); - this.udpThreadPool = new ThreadPoolExecutor(this.udpThreadPoolSize, this.udpThreadPoolSize, 1, TimeUnit.SECONDS, new LinkedBlockingQueue()); + log.debug("Initializing UDP thread pool..."); + this.udpThreadPool = new ThreadPoolExecutor(this.udpThreadPoolSize, this.udpThreadPoolSize, 1, TimeUnit.SECONDS, new LinkedBlockingQueue()); - Iterator iaddr = addresses.iterator(); - while (iaddr.hasNext()) { - InetAddress addr = iaddr.next(); - Iterator iport = ports.iterator(); - while (iport.hasNext()) { - int port = iport.next().intValue(); + Iterator iaddr = addresses.iterator(); + while (iaddr.hasNext()) { + InetAddress addr = iaddr.next(); + Iterator iport = ports.iterator(); + while (iport.hasNext()) { + int port = iport.next().intValue(); - try { - this.udpMonitorThreads.add(new UDPSocketMonitor(this, addr, port)); - } catch (SocketException e) { - log.error("Unable to open UDP server socket on address " + addr + ":" + port + ", " + e); - } + try { + this.udpMonitorThreads.add(new UDPSocketMonitor(this, addr, port)); + } catch (SocketException e) { + log.error("Unable to open UDP server socket on address " + addr + ":" + port + ", " + e); + } - try { - this.tcpMonitorThreads.add(new TCPSocketMonitor(this, addr, port)); - } catch (IOException e) { - log.error("Unable to open TCP server socket on address " + addr + ":" + port + ", " + e); - } - } - } + try { + this.tcpMonitorThreads.add(new TCPSocketMonitor(this, addr, port)); + } catch (IOException e) { + log.error("Unable to open TCP server socket on address " + addr + ":" + port + ", " + e); + } + } + } - if (this.tcpMonitorThreads.isEmpty() && this.udpMonitorThreads.isEmpty()) { + if (this.tcpMonitorThreads.isEmpty() && this.udpMonitorThreads.isEmpty()) { - log.fatal("Not bound on any sockets, aborting startup!"); - return; - } + log.fatal("Not bound on any sockets, aborting startup!"); + return; + } - log.debug("Starting secondary zone update timer..."); - this.timerTask = new RunnableTimerTask(this); - this.secondaryZoneUpdateTimer = new Timer(); - this.secondaryZoneUpdateTimer.schedule(timerTask, MillisecondTimeUnits.SECOND * 60, MillisecondTimeUnits.SECOND * 60); + log.debug("Starting secondary zone update timer..."); + this.timerTask = new RunnableTimerTask(this); + this.secondaryZoneUpdateTimer = new Timer(); + this.secondaryZoneUpdateTimer.schedule(timerTask, MillisecondTimeUnits.SECOND * 60, MillisecondTimeUnits.SECOND * 60); - log.info(VERSION + " started with " + this.primaryZoneMap.size() + " primary zones and " + this.secondaryZoneMap.size() + " secondary zones"); - } + log.info(VERSION + " started with " + this.primaryZoneMap.size() + " primary zones and " + this.secondaryZoneMap.size() + " secondary zones"); + } protected CountDownLatch shutdownLatch = new CountDownLatch(1); - public synchronized void shutdown() { + public synchronized void shutdown() { - new Thread(){@Override - public void run(){ + new Thread(){@Override + public void run(){ - //RMI thread workaround - actualShutdown(); + //RMI thread workaround + actualShutdown(); - }}.start(); + }}.start(); try { log.debug("Awaiting shutdown latch"); @@ -445,10 +445,10 @@ public void run(){ } } - void actualShutdown(){ + void actualShutdown(){ log.debug("In shutdown..."); - if (shutdown == false) { + if (shutdown == false) { try { @@ -517,525 +517,525 @@ void actualShutdown(){ } //System.exit(0); - } - } + } + } - public synchronized void reloadZones() { + public synchronized void reloadZones() { - this.primaryZoneMap.clear(); - this.secondaryZoneMap.clear(); + this.primaryZoneMap.clear(); + this.secondaryZoneMap.clear(); - for (Entry zoneProviderEntry : this.zoneProviders.entrySet()) { + for (Entry zoneProviderEntry : this.zoneProviders.entrySet()) { - log.debug("Getting primary zones from zone provider " + zoneProviderEntry.getKey()); + log.debug("Getting primary zones from zone provider " + zoneProviderEntry.getKey()); - Collection primaryZones; + Collection primaryZones; - try { - primaryZones = zoneProviderEntry.getValue().getPrimaryZones(); + try { + primaryZones = zoneProviderEntry.getValue().getPrimaryZones(); - } catch (Throwable e) { + } catch (Throwable e) { - log.error("Error getting primary zones from zone provider " + zoneProviderEntry.getKey(), e); - continue; - } + log.error("Error getting primary zones from zone provider " + zoneProviderEntry.getKey(), e); + continue; + } - if (primaryZones != null) { + if (primaryZones != null) { - for (Zone zone : primaryZones) { + for (Zone zone : primaryZones) { - log.debug("Got zone " + zone.getOrigin()); + log.debug("Got zone " + zone.getOrigin()); - this.primaryZoneMap.put(zone.getOrigin(), new CachedPrimaryZone(zone, zoneProviderEntry.getValue())); - } - } + this.primaryZoneMap.put(zone.getOrigin(), new CachedPrimaryZone(zone, zoneProviderEntry.getValue())); + } + } - log.debug("Getting secondary zones from zone provider " + zoneProviderEntry.getKey()); + log.debug("Getting secondary zones from zone provider " + zoneProviderEntry.getKey()); - Collection secondaryZones; + Collection secondaryZones; - try { - secondaryZones = zoneProviderEntry.getValue().getSecondaryZones(); + try { + secondaryZones = zoneProviderEntry.getValue().getSecondaryZones(); - } catch (Throwable e) { + } catch (Throwable e) { - log.error("Error getting secondary zones from zone provider " + zoneProviderEntry.getKey(), e); - continue; - } + log.error("Error getting secondary zones from zone provider " + zoneProviderEntry.getKey(), e); + continue; + } - if (secondaryZones != null) { + if (secondaryZones != null) { - for (SecondaryZone zone : secondaryZones) { + for (SecondaryZone zone : secondaryZones) { - log.debug("Got zone " + zone.getZoneName() + " (" + zone.getRemoteServerAddress() + ")"); + log.debug("Got zone " + zone.getZoneName() + " (" + zone.getRemoteServerAddress() + ")"); - CachedSecondaryZone cachedSecondaryZone = new CachedSecondaryZone(zoneProviderEntry.getValue(), zone); + CachedSecondaryZone cachedSecondaryZone = new CachedSecondaryZone(zoneProviderEntry.getValue(), zone); - this.secondaryZoneMap.put(cachedSecondaryZone.getSecondaryZone().getZoneName(), cachedSecondaryZone); - } - } - } - } + this.secondaryZoneMap.put(cachedSecondaryZone.getSecondaryZone().getZoneName(), cachedSecondaryZone); + } + } + } + } - // @SuppressWarnings("unused") - // private void addPrimaryZone(String zname, String zonefile) throws IOException { - // Name origin = null; - // if (zname != null) { - // origin = Name.fromString(zname, Name.root); - // } - // Zone newzone = new Zone(origin, zonefile); - // primaryZoneMap.put(newzone.getOrigin(), newzone); - // } - // - // @SuppressWarnings("unused") - // private void addSecondaryZone(String zone, String remote) throws IOException, ZoneTransferException { - // Name zname = Name.fromString(zone, Name.root); - // Zone newzone = new Zone(zname, DClass.IN, remote); - // primaryZoneMap.put(zname, newzone); - // } + // @SuppressWarnings("unused") + // private void addPrimaryZone(String zname, String zonefile) throws IOException { + // Name origin = null; + // if (zname != null) { + // origin = Name.fromString(zname, Name.root); + // } + // Zone newzone = new Zone(origin, zonefile); + // primaryZoneMap.put(newzone.getOrigin(), newzone); + // } + // + // @SuppressWarnings("unused") + // private void addSecondaryZone(String zone, String remote) throws IOException, ZoneTransferException { + // Name zname = Name.fromString(zone, Name.root); + // Zone newzone = new Zone(zname, DClass.IN, remote); + // primaryZoneMap.put(zname, newzone); + // } + + @SuppressWarnings("unused") + private void addTSIG(String algstr, String namestr, String key) throws IOException { + Name name = Name.fromString(namestr, Name.root); + TSIGs.put(name, new TSIG(algstr, namestr, key)); + } - @SuppressWarnings("unused") - private void addTSIG(String algstr, String namestr, String key) throws IOException { - Name name = Name.fromString(namestr, Name.root); - TSIGs.put(name, new TSIG(algstr, namestr, key)); - } + private Zone findBestZone(Name name) { - private Zone findBestZone(Name name) { + Zone foundzone = getZone(name); - Zone foundzone = getZone(name); + if (foundzone != null) { + return foundzone; + } - if (foundzone != null) { - return foundzone; - } + int labels = name.labels(); - int labels = name.labels(); + for (int i = 1; i < labels; i++) { - for (int i = 1; i < labels; i++) { + Name tname = new Name(name, i); + foundzone = getZone(tname); - Name tname = new Name(name, i); - foundzone = getZone(tname); + if (foundzone != null) { + return foundzone; + } + } - if (foundzone != null) { - return foundzone; - } - } + return null; + } - return null; - } - - private Zone getZone(Name name) { + private Zone getZone(Name name) { - CachedPrimaryZone cachedPrimaryZone = this.primaryZoneMap.get(name); - - if (cachedPrimaryZone != null) { - return cachedPrimaryZone.getZone(); - } - - CachedSecondaryZone cachedSecondaryZone = this.secondaryZoneMap.get(name); - - if (cachedSecondaryZone != null && cachedSecondaryZone.getSecondaryZone().getZoneCopy() != null) { - - return cachedSecondaryZone.getSecondaryZone().getZoneCopy(); - } - - return null; - } - - private RRset findExactMatch(Name name, int type, int dclass, boolean glue) { - Zone zone = findBestZone(name); - - if (zone != null) { - return zone.findExactMatch(name, type); - } - - return null; - } - - private void addRRset(Name name, Message response, RRset rrset, int section, int flags) { - for (int s = 1; s <= section; s++) { - if (response.findRRset(name, rrset.getType(), s)) { - return; - } - } - if ((flags & FLAG_SIGONLY) == 0) { - Iterator it = rrset.rrs(); - while (it.hasNext()) { - Record r = (Record) it.next(); - if (r.getName().isWild() && !name.isWild()) { - r = r.withName(name); - } - response.addRecord(r, section); - } - } - if ((flags & (FLAG_SIGONLY | FLAG_DNSSECOK)) != 0) { - Iterator it = rrset.sigs(); - while (it.hasNext()) { - Record r = (Record) it.next(); - if (r.getName().isWild() && !name.isWild()) { - r = r.withName(name); - } - response.addRecord(r, section); - } - } - } - - private void addSOA(Message response, Zone zone) { - response.addRecord(zone.getSOA(), Section.AUTHORITY); - } - - private void addNS(Message response, Zone zone, int flags) { - RRset nsRecords = zone.getNS(); - addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags); - } - - private void addGlue(Message response, Name name, int flags) { - RRset a = findExactMatch(name, Type.A, DClass.IN, true); - if (a == null) { - return; - } - addRRset(name, response, a, Section.ADDITIONAL, flags); - } - - private void addAdditional2(Message response, int section, int flags) { - Record[] records = response.getSectionArray(section); - for (Record r : records) { - Name glueName = r.getAdditionalName(); - if (glueName != null) { - addGlue(response, glueName, flags); - } - } - } - - private void addAdditional(Message response, int flags) { - addAdditional2(response, Section.ANSWER, flags); - addAdditional2(response, Section.AUTHORITY, flags); - } - - private byte addAnswer(Message response, Name name, int type, int dclass, int iterations, int flags) { - SetResponse sr; - byte rcode = Rcode.NOERROR; - - if (iterations > 6) { - return Rcode.NOERROR; - } - - if (type == Type.SIG || type == Type.RRSIG) { - type = Type.ANY; - flags |= FLAG_SIGONLY; - } - - Zone zone = findBestZone(name); - if (zone != null) { - sr = zone.findRecords(name, type); - - if (sr.isNXDOMAIN()) { - response.getHeader().setRcode(Rcode.NXDOMAIN); - if (zone != null) { - addSOA(response, zone); - if (iterations == 0) { - response.getHeader().setFlag(Flags.AA); - } - } - rcode = Rcode.NXDOMAIN; - } else if (sr.isNXRRSET()) { - if (zone != null) { - addSOA(response, zone); - if (iterations == 0) { - response.getHeader().setFlag(Flags.AA); - } - } - } else if (sr.isDelegation()) { - RRset nsRecords = sr.getNS(); - addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags); - } else if (sr.isCNAME()) { - CNAMERecord cname = sr.getCNAME(); - RRset rrset = new RRset(cname); - addRRset(name, response, rrset, Section.ANSWER, flags); - if (zone != null && iterations == 0) { - response.getHeader().setFlag(Flags.AA); - } - rcode = addAnswer(response, cname.getTarget(), type, dclass, iterations + 1, flags); - } else if (sr.isDNAME()) { - DNAMERecord dname = sr.getDNAME(); - RRset rrset = new RRset(dname); - addRRset(name, response, rrset, Section.ANSWER, flags); - Name newname; - try { - newname = name.fromDNAME(dname); - } catch (NameTooLongException e) { - return Rcode.YXDOMAIN; - } - rrset = new RRset(new CNAMERecord(name, dclass, 0, newname)); - addRRset(name, response, rrset, Section.ANSWER, flags); - if (zone != null && iterations == 0) { - response.getHeader().setFlag(Flags.AA); - } - rcode = addAnswer(response, newname, type, dclass, iterations + 1, flags); - } else if (sr.isSuccessful()) { - RRset[] rrsets = sr.answers(); - for (RRset rrset : rrsets) { - addRRset(name, response, rrset, Section.ANSWER, flags); - } - if (zone != null) { - addNS(response, zone, flags); - if (iterations == 0) { - response.getHeader().setFlag(Flags.AA); - } - } - } - } - - return rcode; - } - - private byte[] doAXFR(Name name, Message query, TSIG tsig, TSIGRecord qtsig, Socket s) { - - boolean first = true; - - Zone zone = this.findBestZone(name); - - if (zone == null) { - - return errorMessage(query, Rcode.REFUSED); - - } - - // Check that the IP requesting the AXFR is present as a NS in this zone - boolean axfrAllowed = false; - - Iterator nsIterator = zone.getNS().rrs(); - - while (nsIterator.hasNext()) { - - NSRecord record = (NSRecord) nsIterator.next(); - - try { - String nsIP = InetAddress.getByName(record.getTarget().toString()).getHostAddress(); - - if (s.getInetAddress().getHostAddress().equals(nsIP)) { - - axfrAllowed = true; - break; - } - - } catch (UnknownHostException e) { - - log.warn("Unable to resolve hostname of nameserver " + record.getTarget() + " in zone " + zone.getOrigin() + " while processing AXFR request from " + s.getRemoteSocketAddress()); - } - } - - if (!axfrAllowed) { - log.warn("AXFR request of zone " + zone.getOrigin() + " from " + s.getRemoteSocketAddress() + " refused!"); - return errorMessage(query, Rcode.REFUSED); - } - - Iterator it = zone.AXFR(); - - try { - DataOutputStream dataOut; - dataOut = new DataOutputStream(s.getOutputStream()); - int id = query.getHeader().getID(); - while (it.hasNext()) { - RRset rrset = (RRset) it.next(); - Message response = new Message(id); - Header header = response.getHeader(); - header.setFlag(Flags.QR); - header.setFlag(Flags.AA); - addRRset(rrset.getName(), response, rrset, Section.ANSWER, FLAG_DNSSECOK); - if (tsig != null) { - tsig.applyStream(response, qtsig, first); - qtsig = response.getTSIG(); - } - first = false; - byte[] out = response.toWire(); - dataOut.writeShort(out.length); - dataOut.write(out); - } - } catch (IOException ex) { - log.warn("AXFR failed", ex); - } - try { - s.close(); - } catch (IOException ex) { - } - return null; - } - - /* - * Note: a null return value means that the caller doesn't need to do - * anything. Currently this only happens if this is an AXFR request over - * TCP. - */ - byte[] generateReply(Message query, byte[] in, int length, Socket socket) throws IOException { - Header header; - // boolean badversion; - int maxLength; - int flags = 0; - - header = query.getHeader(); - if (header.getFlag(Flags.QR)) { - return null; - } - if (header.getRcode() != Rcode.NOERROR) { - return errorMessage(query, Rcode.FORMERR); - } - if (header.getOpcode() != Opcode.QUERY) { - return errorMessage(query, Rcode.NOTIMP); - } - - Record queryRecord = query.getQuestion(); - - TSIGRecord queryTSIG = query.getTSIG(); - TSIG tsig = null; - if (queryTSIG != null) { - tsig = TSIGs.get(queryTSIG.getName()); - if (tsig == null || tsig.verify(query, in, length, null) != Rcode.NOERROR) { - return formerrMessage(in); - } - } - - OPTRecord queryOPT = query.getOPT(); - if (queryOPT != null && queryOPT.getVersion() > 0) { - // badversion = true; - } - - if (socket != null) { - maxLength = 65535; - } else if (queryOPT != null) { - maxLength = Math.max(queryOPT.getPayloadSize(), 512); - } else { - maxLength = 512; - } - - if (queryOPT != null && (queryOPT.getFlags() & ExtendedFlags.DO) != 0) { - flags = FLAG_DNSSECOK; - } - - Message response = new Message(query.getHeader().getID()); - response.getHeader().setFlag(Flags.QR); - if (query.getHeader().getFlag(Flags.RD)) { - response.getHeader().setFlag(Flags.RD); - } - response.addRecord(queryRecord, Section.QUESTION); - - Name name = queryRecord.getName(); - int type = queryRecord.getType(); - int dclass = queryRecord.getDClass(); - if (type == Type.AXFR && socket != null) { - return doAXFR(name, query, tsig, queryTSIG, socket); - } - if (!Type.isRR(type) && type != Type.ANY) { - return errorMessage(query, Rcode.NOTIMP); - } - - byte rcode = addAnswer(response, name, type, dclass, 0, flags); - if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) { - return errorMessage(query, rcode); - } - - addAdditional(response, flags); - - if (queryOPT != null) { - int optflags = (flags == FLAG_DNSSECOK) ? ExtendedFlags.DO : 0; - OPTRecord opt = new OPTRecord((short) 4096, rcode, (byte) 0, optflags); - response.addRecord(opt, Section.ADDITIONAL); - } - - response.setTSIG(tsig, Rcode.NOERROR, queryTSIG); - return response.toWire(maxLength); - } - - private byte[] buildErrorMessage(Header header, int rcode, Record question) { - Message response = new Message(); - response.setHeader(header); - for (int i = 0; i < 4; i++) { - response.removeAllRecords(i); - } - if (rcode == Rcode.SERVFAIL) { - response.addRecord(question, Section.QUESTION); - } - header.setRcode(rcode); - return response.toWire(); - } - - byte[] formerrMessage(byte[] in) { - Header header; - try { - header = new Header(in); - } catch (IOException e) { - return null; - } - return buildErrorMessage(header, Rcode.FORMERR, null); - } + CachedPrimaryZone cachedPrimaryZone = this.primaryZoneMap.get(name); - private byte[] errorMessage(Message query, int rcode) { - return buildErrorMessage(query.getHeader(), rcode, query.getQuestion()); - } + if (cachedPrimaryZone != null) { + return cachedPrimaryZone.getZone(); + } - protected void UDPClient(DatagramSocket socket, DatagramPacket inDataPacket) { + CachedSecondaryZone cachedSecondaryZone = this.secondaryZoneMap.get(name); - } + if (cachedSecondaryZone != null && cachedSecondaryZone.getSecondaryZone().getZoneCopy() != null) { - public static String toString(Record record) { + return cachedSecondaryZone.getSecondaryZone().getZoneCopy(); + } - if (record == null) { + return null; + } - return null; - } + private RRset findExactMatch(Name name, int type, int dclass, boolean glue) { + Zone zone = findBestZone(name); - StringBuilder stringBuilder = new StringBuilder(); + if (zone != null) { + return zone.findExactMatch(name, type); + } - stringBuilder.append(record.getName()); + return null; + } - stringBuilder.append(" "); + private void addRRset(Name name, Message response, RRset rrset, int section, int flags) { + for (int s = 1; s <= section; s++) { + if (response.findRRset(name, rrset.getType(), s)) { + return; + } + } + if ((flags & FLAG_SIGONLY) == 0) { + Iterator it = rrset.rrs(); + while (it.hasNext()) { + Record r = (Record) it.next(); + if (r.getName().isWild() && !name.isWild()) { + r = r.withName(name); + } + response.addRecord(r, section); + } + } + if ((flags & (FLAG_SIGONLY | FLAG_DNSSECOK)) != 0) { + Iterator it = rrset.sigs(); + while (it.hasNext()) { + Record r = (Record) it.next(); + if (r.getName().isWild() && !name.isWild()) { + r = r.withName(name); + } + response.addRecord(r, section); + } + } + } - stringBuilder.append(record.getTTL()); + private void addSOA(Message response, Zone zone) { + response.addRecord(zone.getSOA(), Section.AUTHORITY); + } - stringBuilder.append(" "); + private void addNS(Message response, Zone zone, int flags) { + RRset nsRecords = zone.getNS(); + addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags); + } - stringBuilder.append(DClass.string(record.getDClass())); + private void addGlue(Message response, Name name, int flags) { + RRset a = findExactMatch(name, Type.A, DClass.IN, true); + if (a == null) { + return; + } + addRRset(name, response, a, Section.ADDITIONAL, flags); + } - stringBuilder.append(" "); + private void addAdditional2(Message response, int section, int flags) { + Record[] records = response.getSectionArray(section); + for (Record r : records) { + Name glueName = r.getAdditionalName(); + if (glueName != null) { + addGlue(response, glueName, flags); + } + } + } - stringBuilder.append(Type.string(record.getType())); + private void addAdditional(Message response, int flags) { + addAdditional2(response, Section.ANSWER, flags); + addAdditional2(response, Section.AUTHORITY, flags); + } - String rdata = record.rdataToString(); + private byte addAnswer(Message response, Name name, int type, int dclass, int iterations, int flags) { + SetResponse sr; + byte rcode = Rcode.NOERROR; - if (!rdata.equals("")) { - stringBuilder.append(" "); - stringBuilder.append(rdata); - } + if (iterations > 6) { + return Rcode.NOERROR; + } - return stringBuilder.toString(); - } + if (type == Type.SIG || type == Type.RRSIG) { + type = Type.ANY; + flags |= FLAG_SIGONLY; + } - public void run() { + Zone zone = findBestZone(name); + if (zone != null) { + sr = zone.findRecords(name, type); - log.debug("Checking secondary zones..."); + if (sr.isNXDOMAIN()) { + response.getHeader().setRcode(Rcode.NXDOMAIN); + if (zone != null) { + addSOA(response, zone); + if (iterations == 0) { + response.getHeader().setFlag(Flags.AA); + } + } + rcode = Rcode.NXDOMAIN; + } else if (sr.isNXRRSET()) { + if (zone != null) { + addSOA(response, zone); + if (iterations == 0) { + response.getHeader().setFlag(Flags.AA); + } + } + } else if (sr.isDelegation()) { + RRset nsRecords = sr.getNS(); + addRRset(nsRecords.getName(), response, nsRecords, Section.AUTHORITY, flags); + } else if (sr.isCNAME()) { + CNAMERecord cname = sr.getCNAME(); + RRset rrset = new RRset(cname); + addRRset(name, response, rrset, Section.ANSWER, flags); + if (zone != null && iterations == 0) { + response.getHeader().setFlag(Flags.AA); + } + rcode = addAnswer(response, cname.getTarget(), type, dclass, iterations + 1, flags); + } else if (sr.isDNAME()) { + DNAMERecord dname = sr.getDNAME(); + RRset rrset = new RRset(dname); + addRRset(name, response, rrset, Section.ANSWER, flags); + Name newname; + try { + newname = name.fromDNAME(dname); + } catch (NameTooLongException e) { + return Rcode.YXDOMAIN; + } + rrset = new RRset(new CNAMERecord(name, dclass, 0, newname)); + addRRset(name, response, rrset, Section.ANSWER, flags); + if (zone != null && iterations == 0) { + response.getHeader().setFlag(Flags.AA); + } + rcode = addAnswer(response, newname, type, dclass, iterations + 1, flags); + } else if (sr.isSuccessful()) { + RRset[] rrsets = sr.answers(); + for (RRset rrset : rrsets) { + addRRset(name, response, rrset, Section.ANSWER, flags); + } + if (zone != null) { + addNS(response, zone, flags); + if (iterations == 0) { + response.getHeader().setFlag(Flags.AA); + } + } + } + } - for(CachedSecondaryZone cachedSecondaryZone : this.secondaryZoneMap.values()){ + return rcode; + } - SecondaryZone secondaryZone = cachedSecondaryZone.getSecondaryZone(); + private byte[] doAXFR(Name name, Message query, TSIG tsig, TSIGRecord qtsig, Socket s) { - if(secondaryZone.getZoneCopy() == null || secondaryZone.getDownloaded() == null || (System.currentTimeMillis() - secondaryZone.getDownloaded().getTime()) > (secondaryZone.getZoneCopy().getSOA().getRefresh() * 1000)){ + boolean first = true; - cachedSecondaryZone.update(this.axfrTimeout); - } - } - } + Zone zone = this.findBestZone(name); - protected ThreadPoolExecutor getTcpThreadPool() { + if (zone == null) { - return tcpThreadPool; - } + return errorMessage(query, Rcode.REFUSED); - protected ThreadPoolExecutor getUdpThreadPool() { + } - return udpThreadPool; - } + // Check that the IP requesting the AXFR is present as a NS in this zone + boolean axfrAllowed = false; - public boolean isShutdown() { + Iterator nsIterator = zone.getNS().rrs(); - return shutdown; - } + while (nsIterator.hasNext()) { + + NSRecord record = (NSRecord) nsIterator.next(); + + try { + String nsIP = InetAddress.getByName(record.getTarget().toString()).getHostAddress(); + + if (s.getInetAddress().getHostAddress().equals(nsIP)) { + + axfrAllowed = true; + break; + } + + } catch (UnknownHostException e) { + + log.warn("Unable to resolve hostname of nameserver " + record.getTarget() + " in zone " + zone.getOrigin() + " while processing AXFR request from " + s.getRemoteSocketAddress()); + } + } + + if (!axfrAllowed) { + log.warn("AXFR request of zone " + zone.getOrigin() + " from " + s.getRemoteSocketAddress() + " refused!"); + return errorMessage(query, Rcode.REFUSED); + } + + Iterator it = zone.AXFR(); + + try { + DataOutputStream dataOut; + dataOut = new DataOutputStream(s.getOutputStream()); + int id = query.getHeader().getID(); + while (it.hasNext()) { + RRset rrset = (RRset) it.next(); + Message response = new Message(id); + Header header = response.getHeader(); + header.setFlag(Flags.QR); + header.setFlag(Flags.AA); + addRRset(rrset.getName(), response, rrset, Section.ANSWER, FLAG_DNSSECOK); + if (tsig != null) { + tsig.applyStream(response, qtsig, first); + qtsig = response.getTSIG(); + } + first = false; + byte[] out = response.toWire(); + dataOut.writeShort(out.length); + dataOut.write(out); + } + } catch (IOException ex) { + log.warn("AXFR failed", ex); + } + try { + s.close(); + } catch (IOException ex) { + } + return null; + } + + /* + * Note: a null return value means that the caller doesn't need to do + * anything. Currently this only happens if this is an AXFR request over + * TCP. + */ + byte[] generateReply(Message query, byte[] in, int length, Socket socket) throws IOException { + Header header; + // boolean badversion; + int maxLength; + int flags = 0; + + header = query.getHeader(); + if (header.getFlag(Flags.QR)) { + return null; + } + if (header.getRcode() != Rcode.NOERROR) { + return errorMessage(query, Rcode.FORMERR); + } + if (header.getOpcode() != Opcode.QUERY) { + return errorMessage(query, Rcode.NOTIMP); + } + + Record queryRecord = query.getQuestion(); + + TSIGRecord queryTSIG = query.getTSIG(); + TSIG tsig = null; + if (queryTSIG != null) { + tsig = TSIGs.get(queryTSIG.getName()); + if (tsig == null || tsig.verify(query, in, length, null) != Rcode.NOERROR) { + return formerrMessage(in); + } + } + + OPTRecord queryOPT = query.getOPT(); + if (queryOPT != null && queryOPT.getVersion() > 0) { + // badversion = true; + } + + if (socket != null) { + maxLength = 65535; + } else if (queryOPT != null) { + maxLength = Math.max(queryOPT.getPayloadSize(), 512); + } else { + maxLength = 512; + } + + if (queryOPT != null && (queryOPT.getFlags() & ExtendedFlags.DO) != 0) { + flags = FLAG_DNSSECOK; + } + + Message response = new Message(query.getHeader().getID()); + response.getHeader().setFlag(Flags.QR); + if (query.getHeader().getFlag(Flags.RD)) { + response.getHeader().setFlag(Flags.RD); + } + response.addRecord(queryRecord, Section.QUESTION); + + Name name = queryRecord.getName(); + int type = queryRecord.getType(); + int dclass = queryRecord.getDClass(); + if (type == Type.AXFR && socket != null) { + return doAXFR(name, query, tsig, queryTSIG, socket); + } + if (!Type.isRR(type) && type != Type.ANY) { + return errorMessage(query, Rcode.NOTIMP); + } + + byte rcode = addAnswer(response, name, type, dclass, 0, flags); + if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) { + return errorMessage(query, rcode); + } + + addAdditional(response, flags); + + if (queryOPT != null) { + int optflags = (flags == FLAG_DNSSECOK) ? ExtendedFlags.DO : 0; + OPTRecord opt = new OPTRecord((short) 4096, rcode, (byte) 0, optflags); + response.addRecord(opt, Section.ADDITIONAL); + } + + response.setTSIG(tsig, Rcode.NOERROR, queryTSIG); + return response.toWire(maxLength); + } + + private byte[] buildErrorMessage(Header header, int rcode, Record question) { + Message response = new Message(); + response.setHeader(header); + for (int i = 0; i < 4; i++) { + response.removeAllRecords(i); + } + if (rcode == Rcode.SERVFAIL) { + response.addRecord(question, Section.QUESTION); + } + header.setRcode(rcode); + return response.toWire(); + } + + byte[] formerrMessage(byte[] in) { + Header header; + try { + header = new Header(in); + } catch (IOException e) { + return null; + } + return buildErrorMessage(header, Rcode.FORMERR, null); + } + + private byte[] errorMessage(Message query, int rcode) { + return buildErrorMessage(query.getHeader(), rcode, query.getQuestion()); + } + + protected void UDPClient(DatagramSocket socket, DatagramPacket inDataPacket) { + + } + + public static String toString(Record record) { + + if (record == null) { + + return null; + } + + StringBuilder stringBuilder = new StringBuilder(); + + stringBuilder.append(record.getName()); + + stringBuilder.append(" "); + + stringBuilder.append(record.getTTL()); + + stringBuilder.append(" "); + + stringBuilder.append(DClass.string(record.getDClass())); + + stringBuilder.append(" "); + + stringBuilder.append(Type.string(record.getType())); + + String rdata = record.rdataToString(); + + if (!rdata.equals("")) { + stringBuilder.append(" "); + stringBuilder.append(rdata); + } + + return stringBuilder.toString(); + } + + public void run() { + + log.debug("Checking secondary zones..."); + + for(CachedSecondaryZone cachedSecondaryZone : this.secondaryZoneMap.values()){ + + SecondaryZone secondaryZone = cachedSecondaryZone.getSecondaryZone(); + + if(secondaryZone.getZoneCopy() == null || secondaryZone.getDownloaded() == null || (System.currentTimeMillis() - secondaryZone.getDownloaded().getTime()) > (secondaryZone.getZoneCopy().getSOA().getRefresh() * 1000)){ + + cachedSecondaryZone.update(this.axfrTimeout); + } + } + } + + protected ThreadPoolExecutor getTcpThreadPool() { + + return tcpThreadPool; + } + + protected ThreadPoolExecutor getUdpThreadPool() { + + return udpThreadPool; + } + + public boolean isShutdown() { + + return shutdown; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/EagleLogin.java b/eagledns/src/main/java/se/unlogic/eagledns/EagleLogin.java index 47fbc9586c8..06cf976dcd5 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/EagleLogin.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/EagleLogin.java @@ -6,5 +6,5 @@ public interface EagleLogin extends Remote{ - EagleManager login(String password) throws RemoteException; + EagleManager login(String password) throws RemoteException; } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/EagleManager.java b/eagledns/src/main/java/se/unlogic/eagledns/EagleManager.java index ba263b2c56b..3bb3eac5117 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/EagleManager.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/EagleManager.java @@ -5,8 +5,8 @@ public interface EagleManager extends Remote{ - void shutdown() throws RemoteException; + void shutdown() throws RemoteException; - void reloadZones() throws RemoteException; + void reloadZones() throws RemoteException; -} \ No newline at end of file +} diff --git a/eagledns/src/main/java/se/unlogic/eagledns/EagleManagerClient.java b/eagledns/src/main/java/se/unlogic/eagledns/EagleManagerClient.java index 7d1eba5161c..62a721729d0 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/EagleManagerClient.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/EagleManagerClient.java @@ -11,83 +11,83 @@ public class EagleManagerClient { - public static EagleManager getManager(String host, int port, String password) throws RemoteException, NotBoundException { + public static EagleManager getManager(String host, int port, String password) throws RemoteException, NotBoundException { - Registry registry = LocateRegistry.getRegistry(host,port); + Registry registry = LocateRegistry.getRegistry(host,port); - EagleLogin eagleLogin = (EagleLogin) registry.lookup("eagleLogin"); + EagleLogin eagleLogin = (EagleLogin) registry.lookup("eagleLogin"); - return eagleLogin.login(password); - } + return eagleLogin.login(password); + } - public static void main(String[] args) { + public static void main(String[] args) { - Logger LOG = Logger.getLogger(EagleManagerClient.class); + Logger LOG = Logger.getLogger(EagleManagerClient.class); - if(args.length != 3 || (!args[2].equals("reload") && !args[2].equals("shutdown"))){ + if(args.length != 3 || (!args[2].equals("reload") && !args[2].equals("shutdown"))){ - LOG.info("Usage EagleManagerClient config host command"); - LOG.info("Valid commands are: reload, shutdown"); - return; - } + LOG.info("Usage EagleManagerClient config host command"); + LOG.info("Valid commands are: reload, shutdown"); + return; + } - XMLSettingNode configFile; + XMLSettingNode configFile; - try { - configFile = new XMLSettingNode(args[0]); + try { + configFile = new XMLSettingNode(args[0]); - } catch (Exception e) { + } catch (Exception e) { - LOG.info("Unable to open config file " + args[0] + "!"); - return; - } + LOG.info("Unable to open config file " + args[0] + "!"); + return; + } - String password = configFile.getString("/Config/System/RemoteManagementPassword"); + String password = configFile.getString("/Config/System/RemoteManagementPassword"); - if(password == null){ + if(password == null){ - LOG.info("No remote management password found in config!"); - return; - } + LOG.info("No remote management password found in config!"); + return; + } - Integer port = configFile.getInteger("/Config/System/RemoteManagementPort"); + Integer port = configFile.getInteger("/Config/System/RemoteManagementPort"); - if(port == null){ + if(port == null){ - LOG.info("No remote management port found in config!"); - return; - } + LOG.info("No remote management port found in config!"); + return; + } - try { - EagleManager eagleManager = getManager(args[1], port, password); + try { + EagleManager eagleManager = getManager(args[1], port, password); - if(eagleManager == null){ + if(eagleManager == null){ - LOG.info("Invalid password!"); + LOG.info("Invalid password!"); - }else{ + }else{ - if(args[2].equals("reload")){ + if(args[2].equals("reload")){ - eagleManager.reloadZones(); - LOG.info("Zones reloaded"); + eagleManager.reloadZones(); + LOG.info("Zones reloaded"); - }else{ + }else{ - eagleManager.shutdown(); - LOG.info("Shutdown command sent"); - } - } + eagleManager.shutdown(); + LOG.info("Shutdown command sent"); + } + } - } catch (RemoteException e) { + } catch (RemoteException e) { - LOG.info("Unable to connect " + e); + LOG.info("Unable to connect " + e); - } catch (NotBoundException e) { + } catch (NotBoundException e) { - LOG.info("Unable to connect " + e); - } - } + LOG.info("Unable to connect " + e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/LoginHandler.java b/eagledns/src/main/java/se/unlogic/eagledns/LoginHandler.java index 19adb1561f9..9a4f10840cd 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/LoginHandler.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/LoginHandler.java @@ -8,34 +8,34 @@ public class LoginHandler implements EagleLogin { - private Logger log = Logger.getLogger(this.getClass()); + private Logger log = Logger.getLogger(this.getClass()); - private EagleManager eagleManager; - private String password; + private EagleManager eagleManager; + private String password; - public LoginHandler(EagleManager eagleManager, String password) { - super(); - this.eagleManager = eagleManager; - this.password = password; - } + public LoginHandler(EagleManager eagleManager, String password) { + super(); + this.eagleManager = eagleManager; + this.password = password; + } - public EagleManager login(String password) { + public EagleManager login(String password) { - if(password != null && password.equalsIgnoreCase(this.password)){ + if(password != null && password.equalsIgnoreCase(this.password)){ - try { - log.info("Remote login from " + UnicastRemoteObject.getClientHost()); - } catch (ServerNotActiveException e) {} + try { + log.info("Remote login from " + UnicastRemoteObject.getClientHost()); + } catch (ServerNotActiveException e) {} - return eagleManager; + return eagleManager; - } + } - try { - log.warn("Failed login attempt from " + UnicastRemoteObject.getClientHost()); - } catch (ServerNotActiveException e) {} + try { + log.warn("Failed login attempt from " + UnicastRemoteObject.getClientHost()); + } catch (ServerNotActiveException e) {} - return null; - } + return null; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/SecondaryZone.java b/eagledns/src/main/java/se/unlogic/eagledns/SecondaryZone.java index 911602cb225..348d8cf8d6e 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/SecondaryZone.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/SecondaryZone.java @@ -14,76 +14,76 @@ */ public class SecondaryZone { - private Name zoneName; - private String remoteServerAddress; - private String dclass; - private Timestamp downloaded; - private Zone zoneCopy; + private Name zoneName; + private String remoteServerAddress; + private String dclass; + private Timestamp downloaded; + private Zone zoneCopy; - public SecondaryZone(String zoneName, String remoteServerAddress, String dclass) throws TextParseException { + public SecondaryZone(String zoneName, String remoteServerAddress, String dclass) throws TextParseException { - super(); - this.zoneName = Name.fromString(zoneName, Name.root); - this.remoteServerAddress = remoteServerAddress; - this.dclass = dclass; - } + super(); + this.zoneName = Name.fromString(zoneName, Name.root); + this.remoteServerAddress = remoteServerAddress; + this.dclass = dclass; + } - public SecondaryZone(String zoneName, String remoteServerAddress, String dclass, Timestamp zoneDownloaded, Zone zone) throws TextParseException { + public SecondaryZone(String zoneName, String remoteServerAddress, String dclass, Timestamp zoneDownloaded, Zone zone) throws TextParseException { - this.zoneName = Name.fromString(zoneName, Name.root); - this.remoteServerAddress = remoteServerAddress; - this.dclass = dclass; - this.zoneCopy = zone; - this.downloaded = zoneDownloaded; - } + this.zoneName = Name.fromString(zoneName, Name.root); + this.remoteServerAddress = remoteServerAddress; + this.dclass = dclass; + this.zoneCopy = zone; + this.downloaded = zoneDownloaded; + } - public Name getZoneName() { + public Name getZoneName() { - return zoneName; - } + return zoneName; + } - public void setZoneName(Name zoneName) { + public void setZoneName(Name zoneName) { - this.zoneName = zoneName; - } + this.zoneName = zoneName; + } - public String getRemoteServerAddress() { + public String getRemoteServerAddress() { - return remoteServerAddress; - } + return remoteServerAddress; + } - public void setRemoteServerAddress(String remoteServerIP) { + public void setRemoteServerAddress(String remoteServerIP) { - this.remoteServerAddress = remoteServerIP; - } + this.remoteServerAddress = remoteServerIP; + } - public Zone getZoneCopy() { + public Zone getZoneCopy() { - return zoneCopy; - } + return zoneCopy; + } - public void setZoneCopy(Zone zone) { + public void setZoneCopy(Zone zone) { - this.zoneCopy = zone; - } + this.zoneCopy = zone; + } - public String getDclass() { - return dclass; - } + public String getDclass() { + return dclass; + } - public void setDclass(String dclass) { - this.dclass = dclass; - } + public void setDclass(String dclass) { + this.dclass = dclass; + } - - public Timestamp getDownloaded() { - - return downloaded; - } - - public void setDownloaded(Timestamp zoneDownloaded) { - - this.downloaded = zoneDownloaded; - } + public Timestamp getDownloaded() { + + return downloaded; + } + + + public void setDownloaded(Timestamp zoneDownloaded) { + + this.downloaded = zoneDownloaded; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/TCPConnection.java b/eagledns/src/main/java/se/unlogic/eagledns/TCPConnection.java index f9be3bd87ee..5f321ca1cfb 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/TCPConnection.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/TCPConnection.java @@ -12,65 +12,65 @@ public class TCPConnection implements Runnable { - private static Logger log = Logger.getLogger(TCPConnection.class); - - private EagleDNS eagleDNS; - private Socket socket; - - public TCPConnection(EagleDNS eagleDNS, Socket socket) { - super(); - this.eagleDNS = eagleDNS; - this.socket = socket; - } - - public void run() { - - try{ - - try { - int inLength; - DataInputStream dataIn; - DataOutputStream dataOut; - byte[] in; - - InputStream is = socket.getInputStream(); - dataIn = new DataInputStream(is); - inLength = dataIn.readUnsignedShort(); - in = new byte[inLength]; - dataIn.readFully(in); - - Message query; - byte[] response = null; - try { - query = new Message(in); - - log.debug("TCP query " + EagleDNS.toString(query.getQuestion()) + " from " + socket.getRemoteSocketAddress()); - - response = this.eagleDNS.generateReply(query, in, in.length, socket); - - if (response == null) { - return; - } - } catch (IOException e) { - response = this.eagleDNS.formerrMessage(in); - } - dataOut = new DataOutputStream(socket.getOutputStream()); - dataOut.writeShort(response.length); - dataOut.write(response); - } catch (IOException e) { - - log.debug("Error sending TCP response to " + socket.getRemoteSocketAddress() + ":" + socket.getPort() + ", " + e); - - } finally { - try { - socket.close(); - } catch (IOException e) { - } - } - - }catch(Throwable e){ - - log.warn("Error processing TCP connection from " + socket.getRemoteSocketAddress() + ":" + socket.getPort() + ", " + e); - } - } + private static Logger log = Logger.getLogger(TCPConnection.class); + + private EagleDNS eagleDNS; + private Socket socket; + + public TCPConnection(EagleDNS eagleDNS, Socket socket) { + super(); + this.eagleDNS = eagleDNS; + this.socket = socket; + } + + public void run() { + + try{ + + try { + int inLength; + DataInputStream dataIn; + DataOutputStream dataOut; + byte[] in; + + InputStream is = socket.getInputStream(); + dataIn = new DataInputStream(is); + inLength = dataIn.readUnsignedShort(); + in = new byte[inLength]; + dataIn.readFully(in); + + Message query; + byte[] response = null; + try { + query = new Message(in); + + log.debug("TCP query " + EagleDNS.toString(query.getQuestion()) + " from " + socket.getRemoteSocketAddress()); + + response = this.eagleDNS.generateReply(query, in, in.length, socket); + + if (response == null) { + return; + } + } catch (IOException e) { + response = this.eagleDNS.formerrMessage(in); + } + dataOut = new DataOutputStream(socket.getOutputStream()); + dataOut.writeShort(response.length); + dataOut.write(response); + } catch (IOException e) { + + log.debug("Error sending TCP response to " + socket.getRemoteSocketAddress() + ":" + socket.getPort() + ", " + e); + + } finally { + try { + socket.close(); + } catch (IOException e) { + } + } + + }catch(Throwable e){ + + log.warn("Error processing TCP connection from " + socket.getRemoteSocketAddress() + ":" + socket.getPort() + ", " + e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/TCPSocketMonitor.java b/eagledns/src/main/java/se/unlogic/eagledns/TCPSocketMonitor.java index 954e8fc9a1a..1fb7c538e90 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/TCPSocketMonitor.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/TCPSocketMonitor.java @@ -11,81 +11,81 @@ public class TCPSocketMonitor extends Thread { - private Logger log = Logger.getLogger(this.getClass()); + private Logger log = Logger.getLogger(this.getClass()); - private final EagleDNS eagleDNS; - private final InetAddress addr; - private final int port; - private final ServerSocket serverSocket; + private final EagleDNS eagleDNS; + private final InetAddress addr; + private final int port; + private final ServerSocket serverSocket; - public TCPSocketMonitor(EagleDNS eagleDNS, final InetAddress addr, final int port) throws IOException { - super(); - this.eagleDNS = eagleDNS; - this.addr = addr; - this.port = port; + public TCPSocketMonitor(EagleDNS eagleDNS, final InetAddress addr, final int port) throws IOException { + super(); + this.eagleDNS = eagleDNS; + this.addr = addr; + this.port = port; - serverSocket = new ServerSocket(port, 128, addr); + serverSocket = new ServerSocket(port, 128, addr); - this.setDaemon(true); - this.start(); - } + this.setDaemon(true); + this.start(); + } - @Override - public void run() { + @Override + public void run() { - log.debug("Starting TCP socket monitor on address " + getAddressAndPort()); + log.debug("Starting TCP socket monitor on address " + getAddressAndPort()); - while (!this.eagleDNS.isShutdown()) { + while (!this.eagleDNS.isShutdown()) { - try { + try { - final Socket socket = serverSocket.accept(); + final Socket socket = serverSocket.accept(); - log.debug("TCP connection from " + socket.getRemoteSocketAddress()); + log.debug("TCP connection from " + socket.getRemoteSocketAddress()); - this.eagleDNS.getTcpThreadPool().execute(new TCPConnection(eagleDNS, socket)); + this.eagleDNS.getTcpThreadPool().execute(new TCPConnection(eagleDNS, socket)); - } catch (SocketException e) { + } catch (SocketException e) { - //This is usally thrown on shutdown - log.debug("SocketException thrown from TCP socket on address " + getAddressAndPort() + ", " + e); + //This is usally thrown on shutdown + log.debug("SocketException thrown from TCP socket on address " + getAddressAndPort() + ", " + e); - } catch (IOException e) { + } catch (IOException e) { - log.info("IOException thrown by TCP socket on address " + getAddressAndPort() + ", " + e); - } - } + log.info("IOException thrown by TCP socket on address " + getAddressAndPort() + ", " + e); + } + } - log.debug("TCP socket monitor on address " + getAddressAndPort() + " shutdown"); - } + log.debug("TCP socket monitor on address " + getAddressAndPort() + " shutdown"); + } - public InetAddress getAddr() { + public InetAddress getAddr() { - return addr; - } + return addr; + } - public int getPort() { + public int getPort() { - return port; - } + return port; + } - public ServerSocket getServerSocket() { + public ServerSocket getServerSocket() { - return serverSocket; - } + return serverSocket; + } - public void closeSocket() throws IOException{ + public void closeSocket() throws IOException{ - log.debug("Closing TCP socket monitor on address " + getAddressAndPort() + "..."); + log.debug("Closing TCP socket monitor on address " + getAddressAndPort() + "..."); - this.serverSocket.close(); - } + this.serverSocket.close(); + } - public String getAddressAndPort(){ + public String getAddressAndPort(){ - return addr.getHostAddress() + ":" + port; - } + return addr.getHostAddress() + ":" + port; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/UDPConnection.java b/eagledns/src/main/java/se/unlogic/eagledns/UDPConnection.java index cf649680589..e1e2672ab9a 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/UDPConnection.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/UDPConnection.java @@ -10,57 +10,57 @@ public class UDPConnection implements Runnable { - private static final Logger log = Logger.getLogger(UDPConnection.class); + private static final Logger log = Logger.getLogger(UDPConnection.class); - private final EagleDNS eagleDNS; - private final DatagramSocket socket; - private final DatagramPacket inDataPacket; + private final EagleDNS eagleDNS; + private final DatagramSocket socket; + private final DatagramPacket inDataPacket; - public UDPConnection(EagleDNS eagleDNS, DatagramSocket socket, DatagramPacket inDataPacket) { - super(); - this.eagleDNS = eagleDNS; - this.socket = socket; - this.inDataPacket = inDataPacket; - } + public UDPConnection(EagleDNS eagleDNS, DatagramSocket socket, DatagramPacket inDataPacket) { + super(); + this.eagleDNS = eagleDNS; + this.socket = socket; + this.inDataPacket = inDataPacket; + } - public void run() { + public void run() { - try{ + try{ - byte[] response = null; + byte[] response = null; - try { - Message query = new Message(inDataPacket.getData()); + try { + Message query = new Message(inDataPacket.getData()); - log.debug("UDP query " + EagleDNS.toString(query.getQuestion()) + " from " + inDataPacket.getSocketAddress()); + log.debug("UDP query " + EagleDNS.toString(query.getQuestion()) + " from " + inDataPacket.getSocketAddress()); - response = this.eagleDNS.generateReply(query, inDataPacket.getData(), inDataPacket.getLength(), null); + response = this.eagleDNS.generateReply(query, inDataPacket.getData(), inDataPacket.getLength(), null); - if (response == null) { - return; - } - } catch (IOException e) { - response = this.eagleDNS.formerrMessage(inDataPacket.getData()); - } + if (response == null) { + return; + } + } catch (IOException e) { + response = this.eagleDNS.formerrMessage(inDataPacket.getData()); + } - DatagramPacket outdp = new DatagramPacket(response, response.length, inDataPacket.getAddress(), inDataPacket.getPort()); + DatagramPacket outdp = new DatagramPacket(response, response.length, inDataPacket.getAddress(), inDataPacket.getPort()); - outdp.setData(response); - outdp.setLength(response.length); - outdp.setAddress(inDataPacket.getAddress()); - outdp.setPort(inDataPacket.getPort()); + outdp.setData(response); + outdp.setLength(response.length); + outdp.setAddress(inDataPacket.getAddress()); + outdp.setPort(inDataPacket.getPort()); - try { - socket.send(outdp); + try { + socket.send(outdp); - } catch (IOException e) { + } catch (IOException e) { - log.debug("Error sending UDP response to " + inDataPacket.getAddress() + ", " + e); - } + log.debug("Error sending UDP response to " + inDataPacket.getAddress() + ", " + e); + } - }catch(Throwable e){ + }catch(Throwable e){ - log.warn("Error processing UDP connection from " + inDataPacket.getSocketAddress() + ", " + e); - } - } + log.warn("Error processing UDP connection from " + inDataPacket.getSocketAddress() + ", " + e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/UDPSocketMonitor.java b/eagledns/src/main/java/se/unlogic/eagledns/UDPSocketMonitor.java index 5f2d5f3f349..ac158a9920b 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/UDPSocketMonitor.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/UDPSocketMonitor.java @@ -11,72 +11,72 @@ public class UDPSocketMonitor extends Thread { - private Logger log = Logger.getLogger(this.getClass()); + private Logger log = Logger.getLogger(this.getClass()); - private final EagleDNS eagleDNS; - private final InetAddress addr; - private final int port; - private static final short udpLength = 512; - private final DatagramSocket socket; + private final EagleDNS eagleDNS; + private final InetAddress addr; + private final int port; + private static final short udpLength = 512; + private final DatagramSocket socket; - public UDPSocketMonitor(EagleDNS eagleDNS, final InetAddress addr, final int port) throws SocketException { - super(); - this.eagleDNS = eagleDNS; - this.addr = addr; - this.port = port; + public UDPSocketMonitor(EagleDNS eagleDNS, final InetAddress addr, final int port) throws SocketException { + super(); + this.eagleDNS = eagleDNS; + this.addr = addr; + this.port = port; - socket = new DatagramSocket(port, addr); + socket = new DatagramSocket(port, addr); - this.setDaemon(true); - this.start(); - } + this.setDaemon(true); + this.start(); + } - @Override - public void run() { + @Override + public void run() { - log.debug("Starting UDP socket monitor on address " + this.getAddressAndPort()); + log.debug("Starting UDP socket monitor on address " + this.getAddressAndPort()); - while (!this.eagleDNS.isShutdown()) { + while (!this.eagleDNS.isShutdown()) { - try { + try { - byte[] in = new byte[udpLength]; - DatagramPacket indp = new DatagramPacket(in, in.length); + byte[] in = new byte[udpLength]; + DatagramPacket indp = new DatagramPacket(in, in.length); - indp.setLength(in.length); - socket.receive(indp); + indp.setLength(in.length); + socket.receive(indp); - log.debug("UDP connection from " + indp.getSocketAddress()); + log.debug("UDP connection from " + indp.getSocketAddress()); - if(!this.eagleDNS.isShutdown()){ + if(!this.eagleDNS.isShutdown()){ - this.eagleDNS.getUdpThreadPool().execute(new UDPConnection(eagleDNS, socket, indp)); - } + this.eagleDNS.getUdpThreadPool().execute(new UDPConnection(eagleDNS, socket, indp)); + } - } catch (SocketException e) { + } catch (SocketException e) { - //This is usally thrown on shutdown - log.debug("SocketException thrown from UDP socket on address " + this.getAddressAndPort() + ", " + e); + //This is usally thrown on shutdown + log.debug("SocketException thrown from UDP socket on address " + this.getAddressAndPort() + ", " + e); - } catch (IOException e) { + } catch (IOException e) { - log.info("IOException thrown by UDP socket on address " + this.getAddressAndPort() + ", " + e); - } - } + log.info("IOException thrown by UDP socket on address " + this.getAddressAndPort() + ", " + e); + } + } - log.debug("UDP socket monitor on address " + getAddressAndPort() + " shutdown"); - } + log.debug("UDP socket monitor on address " + getAddressAndPort() + " shutdown"); + } - public void closeSocket() throws IOException{ + public void closeSocket() throws IOException{ - log.debug("Closing TCP socket monitor on address " + getAddressAndPort() + "..."); + log.debug("Closing TCP socket monitor on address " + getAddressAndPort() + "..."); - this.socket.close(); - } + this.socket.close(); + } - public String getAddressAndPort(){ + public String getAddressAndPort(){ - return addr.getHostAddress() + ":" + port; - } + return addr.getHostAddress() + ":" + port; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/ZoneChangeCallback.java b/eagledns/src/main/java/se/unlogic/eagledns/ZoneChangeCallback.java index 4a92ad98ea4..c4ac5df96d3 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/ZoneChangeCallback.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/ZoneChangeCallback.java @@ -9,9 +9,9 @@ */ public interface ZoneChangeCallback { - /** - * Calling this method causes Eagle DNS to reload all it's zone from the registered zone providers - */ - void zoneDataChanged(); + /** + * Calling this method causes Eagle DNS to reload all it's zone from the registered zone providers + */ + void zoneDataChanged(); } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/ZoneProvider.java b/eagledns/src/main/java/se/unlogic/eagledns/ZoneProvider.java index c3e4ea671bf..4ddd5b0e094 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/ZoneProvider.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/ZoneProvider.java @@ -13,55 +13,55 @@ */ public interface ZoneProvider { - /** - * This method is called after the ZoneProvider has been instantiated by EagleDNS and all properties - * specified in the config file for this zone provider have been set using their set methods. - */ - void init(String name) throws Exception; + /** + * This method is called after the ZoneProvider has been instantiated by EagleDNS and all properties + * specified in the config file for this zone provider have been set using their set methods. + */ + void init(String name) throws Exception; - /** - * This method is called each time EagleDNS reloads it's zones. - * If no zones are found or if an error occurs the the ZoneProvider should return null - * else it should return all primary zones available from the zone provider. - * - * @return - */ - Collection getPrimaryZones(); + /** + * This method is called each time EagleDNS reloads it's zones. + * If no zones are found or if an error occurs the the ZoneProvider should return null + * else it should return all primary zones available from the zone provider. + * + * @return + */ + Collection getPrimaryZones(); - /** - * This method is called each time EagleDNS reloads it's zones. - * If no zones are found or if an error occurs the the ZoneProvider should return null - * else it should return all secondary zones available from the zone provider. - * - * The returned secondary zones may contain a previously saved copy of the zone if the ZoneProvider supports this feature. - * - * @return - */ - Collection getSecondaryZones(); + /** + * This method is called each time EagleDNS reloads it's zones. + * If no zones are found or if an error occurs the the ZoneProvider should return null + * else it should return all secondary zones available from the zone provider. + * + * The returned secondary zones may contain a previously saved copy of the zone if the ZoneProvider supports this feature. + * + * @return + */ + Collection getSecondaryZones(); - /** - * This method is called when a change has been detected in a secondary zone previously - * loaded from this ZoneProvider. Failed AXFR requests will not trigger this method, although zone expiry will. - * - * The main purpose of this method is to enable the ZoneProviders to save the updated - * zone data which is useful in case EagleDNS is restarted when the primary DNS server of the zone is down. - * - * @param zone - */ - void zoneUpdated(SecondaryZone secondaryZone); + /** + * This method is called when a change has been detected in a secondary zone previously + * loaded from this ZoneProvider. Failed AXFR requests will not trigger this method, although zone expiry will. + * + * The main purpose of this method is to enable the ZoneProviders to save the updated + * zone data which is useful in case EagleDNS is restarted when the primary DNS server of the zone is down. + * + * @param zone + */ + void zoneUpdated(SecondaryZone secondaryZone); - /** - * This method is called each time a zone has been downloaded and no changes have been detected (by comparing the serial) - * - * @param secondaryZone - */ - void zoneChecked(SecondaryZone secondaryZone); + /** + * This method is called each time a zone has been downloaded and no changes have been detected (by comparing the serial) + * + * @param secondaryZone + */ + void zoneChecked(SecondaryZone secondaryZone); - /** - * This method is called when EagleDNS is shutdown or when the configuration has been updated and - * the ZoneProvider is no longer present in the configuration file. - */ - void unload(); + /** + * This method is called when EagleDNS is shutdown or when the configuration has been updated and + * the ZoneProvider is no longer present in the configuration file. + */ + void unload(); } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/ZoneProviderUpdatable.java b/eagledns/src/main/java/se/unlogic/eagledns/ZoneProviderUpdatable.java index 3cbca9f2352..fc03742ec43 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/ZoneProviderUpdatable.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/ZoneProviderUpdatable.java @@ -10,13 +10,13 @@ */ public interface ZoneProviderUpdatable { - /** - * This method is automatically called by Eagle DNS when the {@link ZoneProvider} has been instantiated, before the {@link ZoneProvider#init(String) init()} method is called. - * - * @see ZoneChangeCallback - * - * @param zoneChangeCallback Callback handle - */ - void setChangeListener(ZoneChangeCallback zoneChangeCallback); + /** + * This method is automatically called by Eagle DNS when the {@link ZoneProvider} has been instantiated, before the {@link ZoneProvider#init(String) init()} method is called. + * + * @see ZoneChangeCallback + * + * @param zoneChangeCallback Callback handle + */ + void setChangeListener(ZoneChangeCallback zoneChangeCallback); } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/test/ZoneDissasembler.java b/eagledns/src/main/java/se/unlogic/eagledns/test/ZoneDissasembler.java index 55d6ba08b2f..8d95f127d0b 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/test/ZoneDissasembler.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/test/ZoneDissasembler.java @@ -12,24 +12,24 @@ public class ZoneDissasembler { - public static void main(String[] args) throws TextParseException, IOException { + public static void main(String[] args) throws TextParseException, IOException { - File zoneFile = new File("zones/unlogic.se"); + File zoneFile = new File("zones/unlogic.se"); - Master master = new Master(zoneFile.getPath(),Name.fromString(zoneFile.getName(), Name.root)); + Master master = new Master(zoneFile.getPath(),Name.fromString(zoneFile.getName(), Name.root)); - Record record = master._nextRecord(); + Record record = master._nextRecord(); - Logger LOG = Logger.getLogger(ZoneDissasembler.class); + Logger LOG = Logger.getLogger(ZoneDissasembler.class); - while(record != null){ + while(record != null){ - LOG.info("Class: " + record.getClass()); - LOG.info("Name: " + record.getName()); - LOG.info("toString: " + record.toString()); + LOG.info("Class: " + record.getClass()); + LOG.info("Name: " + record.getName()); + LOG.info("toString: " + record.toString()); - record = master._nextRecord(); - } - } + record = master._nextRecord(); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/utils/PrimaryZones2DB.java b/eagledns/src/main/java/se/unlogic/eagledns/utils/PrimaryZones2DB.java index 9738a86137a..589e431b409 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/utils/PrimaryZones2DB.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/utils/PrimaryZones2DB.java @@ -17,70 +17,70 @@ public class PrimaryZones2DB { - private static final Logger LOG = Logger.getLogger(PrimaryZones2DB.class); + private static final Logger LOG = Logger.getLogger(PrimaryZones2DB.class); - public static void main(String[] args) throws Throwable{ + public static void main(String[] args) throws Throwable{ - if(args.length != 5){ + if(args.length != 5){ - LOG.info("Usage: PrimaryZones2DB zonedir driver url username password"); + LOG.info("Usage: PrimaryZones2DB zonedir driver url username password"); - }else{ + }else{ - importZones(args[0], args[1], args[2], args[3], args[4]); - } - } + importZones(args[0], args[1], args[2], args[3], args[4]); + } + } - public static void importZones(String directory, String driver, String url, String username, String password) throws Throwable { + public static void importZones(String directory, String driver, String url, String username, String password) throws Throwable { - FileZoneProvider fileZoneProvider = new FileZoneProvider(); + FileZoneProvider fileZoneProvider = new FileZoneProvider(); - fileZoneProvider.setZoneFileDirectory(directory); + fileZoneProvider.setZoneFileDirectory(directory); - Collection zones = fileZoneProvider.getPrimaryZones(); + Collection zones = fileZoneProvider.getPrimaryZones(); - ArrayList dbZones = new ArrayList(); + ArrayList dbZones = new ArrayList(); - for(Zone zone : zones){ + for(Zone zone : zones){ - LOG.info("Converting zone " + zone.getSOA().getName().toString() + "..."); + LOG.info("Converting zone " + zone.getSOA().getName().toString() + "..."); - dbZones.add(new DBZone(zone,false)); - } + dbZones.add(new DBZone(zone,false)); + } - DataSource dataSource = new SimpleDataSource(driver, url, username, password); + DataSource dataSource = new SimpleDataSource(driver, url, username, password); - SimpleAnnotatedDAOFactory annotatedDAOFactory = new SimpleAnnotatedDAOFactory(); - AnnotatedDAO zoneDAO = new AnnotatedDAO(dataSource,DBZone.class, annotatedDAOFactory); - AnnotatedDAO recordDAO = new AnnotatedDAO(dataSource,DBRecord.class, annotatedDAOFactory); + SimpleAnnotatedDAOFactory annotatedDAOFactory = new SimpleAnnotatedDAOFactory(); + AnnotatedDAO zoneDAO = new AnnotatedDAO(dataSource,DBZone.class, annotatedDAOFactory); + AnnotatedDAO recordDAO = new AnnotatedDAO(dataSource,DBRecord.class, annotatedDAOFactory); - TransactionHandler transactionHandler = zoneDAO.createTransaction(); + TransactionHandler transactionHandler = zoneDAO.createTransaction(); - try{ + try{ - for(DBZone zone : dbZones){ + for(DBZone zone : dbZones){ - LOG.info("Storing zone " + zone + "..."); + LOG.info("Storing zone " + zone + "..."); - zoneDAO.add(zone, transactionHandler, null); + zoneDAO.add(zone, transactionHandler, null); - for(DBRecord dbRecord : zone.getRecords()){ + for(DBRecord dbRecord : zone.getRecords()){ - LOG.info("Storing record " + dbRecord + "..."); + LOG.info("Storing record " + dbRecord + "..."); - dbRecord.setZone(zone); + dbRecord.setZone(zone); - recordDAO.add(dbRecord, transactionHandler, null); - } - } + recordDAO.add(dbRecord, transactionHandler, null); + } + } - transactionHandler.commit(); + transactionHandler.commit(); - }catch(Throwable e){ + }catch(Throwable e){ - transactionHandler.abort(); - - throw e; - } - } + transactionHandler.abort(); + + throw e; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/DBZoneProvider.java b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/DBZoneProvider.java index bce474317f0..e3437da5d88 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/DBZoneProvider.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/DBZoneProvider.java @@ -25,237 +25,237 @@ public class DBZoneProvider implements ZoneProvider { - private static final Field RECORD_RELATION = ReflectionUtils.getField(DBZone.class, "records"); + private static final Field RECORD_RELATION = ReflectionUtils.getField(DBZone.class, "records"); - private Logger log = Logger.getLogger(this.getClass()); + private Logger log = Logger.getLogger(this.getClass()); - private String name; - private String driver; - private String url; - private String username; - private String password; + private String name; + private String driver; + private String url; + private String username; + private String password; - private SimpleAnnotatedDAOFactory annotatedDAOFactory; - private AnnotatedDAO zoneDAO; - private AnnotatedDAO recordDAO; - private HighLevelQuery primaryZoneQuery; - private HighLevelQuery secondaryZoneQuery; - private QueryParameterFactory zoneIDQueryParameterFactory; - private QueryParameterFactory recordZoneQueryParameterFactory; + private SimpleAnnotatedDAOFactory annotatedDAOFactory; + private AnnotatedDAO zoneDAO; + private AnnotatedDAO recordDAO; + private HighLevelQuery primaryZoneQuery; + private HighLevelQuery secondaryZoneQuery; + private QueryParameterFactory zoneIDQueryParameterFactory; + private QueryParameterFactory recordZoneQueryParameterFactory; - public void init(String name) throws ClassNotFoundException { - this.name = name; + public void init(String name) throws ClassNotFoundException { + this.name = name; - DataSource dataSource; + DataSource dataSource; - try { - dataSource = new SimpleDataSource(driver, url, username, password); + try { + dataSource = new SimpleDataSource(driver, url, username, password); - } catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { - log.error("Unable to load JDBC driver " + driver, e); + log.error("Unable to load JDBC driver " + driver, e); - throw e; - } + throw e; + } - this.annotatedDAOFactory = new SimpleAnnotatedDAOFactory(); + this.annotatedDAOFactory = new SimpleAnnotatedDAOFactory(); - this.zoneDAO = new AnnotatedDAO(dataSource,DBZone.class, annotatedDAOFactory); - this.recordDAO = new AnnotatedDAO(dataSource,DBRecord.class, annotatedDAOFactory); + this.zoneDAO = new AnnotatedDAO(dataSource,DBZone.class, annotatedDAOFactory); + this.recordDAO = new AnnotatedDAO(dataSource,DBRecord.class, annotatedDAOFactory); - QueryParameterFactory zoneTypeParamFactory = zoneDAO.getParamFactory("secondary", boolean.class); + QueryParameterFactory zoneTypeParamFactory = zoneDAO.getParamFactory("secondary", boolean.class); - this.primaryZoneQuery = new HighLevelQuery(zoneTypeParamFactory.getParameter(false),RECORD_RELATION); - this.secondaryZoneQuery = new HighLevelQuery(zoneTypeParamFactory.getParameter(true),RECORD_RELATION); - - this.zoneIDQueryParameterFactory = zoneDAO.getParamFactory("zoneID", Integer.class); - this.recordZoneQueryParameterFactory = recordDAO.getParamFactory("zone", DBZone.class); - } + this.primaryZoneQuery = new HighLevelQuery(zoneTypeParamFactory.getParameter(false),RECORD_RELATION); + this.secondaryZoneQuery = new HighLevelQuery(zoneTypeParamFactory.getParameter(true),RECORD_RELATION); - public Collection getPrimaryZones() { + this.zoneIDQueryParameterFactory = zoneDAO.getParamFactory("zoneID", Integer.class); + this.recordZoneQueryParameterFactory = recordDAO.getParamFactory("zone", DBZone.class); + } - try { - List dbZones = this.zoneDAO.getAll(primaryZoneQuery); + public Collection getPrimaryZones() { - if(dbZones != null){ + try { + List dbZones = this.zoneDAO.getAll(primaryZoneQuery); - ArrayList zones = new ArrayList(dbZones.size()); + if(dbZones != null){ - for(DBZone dbZone : dbZones){ + ArrayList zones = new ArrayList(dbZones.size()); - try { - zones.add(dbZone.toZone()); + for(DBZone dbZone : dbZones){ - } catch (IOException e) { + try { + zones.add(dbZone.toZone()); - log.error("Unable to parse zone " + dbZone.getName(),e); - } - } + } catch (IOException e) { - return zones; - } + log.error("Unable to parse zone " + dbZone.getName(),e); + } + } - } catch (SQLException e) { + return zones; + } - log.error("Error getting primary zones from DB zone provider " + name,e); - } + } catch (SQLException e) { - return null; - } + log.error("Error getting primary zones from DB zone provider " + name,e); + } - public Collection getSecondaryZones() { + return null; + } - try { - List dbZones = this.zoneDAO.getAll(this.secondaryZoneQuery); + public Collection getSecondaryZones() { - if(dbZones != null){ + try { + List dbZones = this.zoneDAO.getAll(this.secondaryZoneQuery); - ArrayList zones = new ArrayList(dbZones.size()); + if(dbZones != null){ - for(DBZone dbZone : dbZones){ + ArrayList zones = new ArrayList(dbZones.size()); - try { - DBSecondaryZone secondaryZone = new DBSecondaryZone(dbZone.getZoneID() ,dbZone.getName(), dbZone.getPrimaryDNS(), dbZone.getDclass()); + for(DBZone dbZone : dbZones){ - if(dbZone.getRecords() != null){ - secondaryZone.setZoneCopy(dbZone.toZone()); - secondaryZone.setDownloaded(dbZone.getDownloaded()); - } + try { + DBSecondaryZone secondaryZone = new DBSecondaryZone(dbZone.getZoneID() ,dbZone.getName(), dbZone.getPrimaryDNS(), dbZone.getDclass()); - zones.add(secondaryZone); + if(dbZone.getRecords() != null){ + secondaryZone.setZoneCopy(dbZone.toZone()); + secondaryZone.setDownloaded(dbZone.getDownloaded()); + } - } catch (IOException e) { + zones.add(secondaryZone); - log.error("Unable to parse zone " + dbZone.getName(),e); - } - } + } catch (IOException e) { - return zones; - } + log.error("Unable to parse zone " + dbZone.getName(),e); + } + } - } catch (SQLException e) { + return zones; + } - log.error("Error getting secondary zones from DB zone provider " + name,e); - } + } catch (SQLException e) { - return null; - } + log.error("Error getting secondary zones from DB zone provider " + name,e); + } - public void zoneUpdated(SecondaryZone zone) { + return null; + } - if(!(zone instanceof DBSecondaryZone)){ + public void zoneUpdated(SecondaryZone zone) { - log.warn(zone.getClass() + " is not an instance of " + DBSecondaryZone.class + ", ignoring zone update"); + if(!(zone instanceof DBSecondaryZone)){ - return; - } + log.warn(zone.getClass() + " is not an instance of " + DBSecondaryZone.class + ", ignoring zone update"); - Integer zoneID = ((DBSecondaryZone)zone).getZoneID(); + return; + } - TransactionHandler transactionHandler = null; + Integer zoneID = ((DBSecondaryZone)zone).getZoneID(); - try { - transactionHandler = zoneDAO.createTransaction(); + TransactionHandler transactionHandler = null; - DBZone dbZone = this.zoneDAO.get(new HighLevelQuery(this.zoneIDQueryParameterFactory.getParameter(zoneID),(Field)null),transactionHandler); + try { + transactionHandler = zoneDAO.createTransaction(); + DBZone dbZone = this.zoneDAO.get(new HighLevelQuery(this.zoneIDQueryParameterFactory.getParameter(zoneID),(Field)null),transactionHandler); - if(dbZone == null){ - log.warn("Unable to find secondary zone with zoneID " + zoneID + " in DB, ignoring zone update"); + if(dbZone == null){ - return; - } + log.warn("Unable to find secondary zone with zoneID " + zoneID + " in DB, ignoring zone update"); - dbZone.parse(zone.getZoneCopy(), true); + return; + } - zoneDAO.update(dbZone,transactionHandler, null); + dbZone.parse(zone.getZoneCopy(), true); - recordDAO.delete(new HighLevelQuery(recordZoneQueryParameterFactory.getParameter(dbZone),(Field)null), transactionHandler); + zoneDAO.update(dbZone,transactionHandler, null); - if(dbZone.getRecords() != null){ + recordDAO.delete(new HighLevelQuery(recordZoneQueryParameterFactory.getParameter(dbZone),(Field)null), transactionHandler); - for(DBRecord dbRecord : dbZone.getRecords()){ + if(dbZone.getRecords() != null){ - dbRecord.setZone(dbZone); + for(DBRecord dbRecord : dbZone.getRecords()){ - this.recordDAO.add(dbRecord, transactionHandler, null); - } - } + dbRecord.setZone(dbZone); - transactionHandler.commit(); + this.recordDAO.add(dbRecord, transactionHandler, null); + } + } - log.debug("Changes in seconday zone " + dbZone + " saved"); + transactionHandler.commit(); - } catch (SQLException e) { + log.debug("Changes in seconday zone " + dbZone + " saved"); - log.error("Unable to save changes in secondary zone " + zone.getZoneName(), e); - TransactionHandler.autoClose(transactionHandler); - } - } + } catch (SQLException e) { - public void zoneChecked(SecondaryZone zone) { + log.error("Unable to save changes in secondary zone " + zone.getZoneName(), e); + TransactionHandler.autoClose(transactionHandler); + } + } - if(!(zone instanceof DBSecondaryZone)){ + public void zoneChecked(SecondaryZone zone) { - log.warn(zone.getClass() + " is not an instance of " + DBSecondaryZone.class + ", ignoring zone check"); + if(!(zone instanceof DBSecondaryZone)){ - return; - } + log.warn(zone.getClass() + " is not an instance of " + DBSecondaryZone.class + ", ignoring zone check"); - Integer zoneID = ((DBSecondaryZone)zone).getZoneID(); + return; + } - TransactionHandler transactionHandler = null; + Integer zoneID = ((DBSecondaryZone)zone).getZoneID(); - try { - transactionHandler = zoneDAO.createTransaction(); + TransactionHandler transactionHandler = null; - DBZone dbZone = this.zoneDAO.get(new HighLevelQuery(this.zoneIDQueryParameterFactory.getParameter(zoneID), (Field)null),transactionHandler); + try { + transactionHandler = zoneDAO.createTransaction(); - if(dbZone == null){ + DBZone dbZone = this.zoneDAO.get(new HighLevelQuery(this.zoneIDQueryParameterFactory.getParameter(zoneID), (Field)null),transactionHandler); - log.warn("Unable to find secondary zone with zoneID " + zoneID + " in DB, ignoring zone update"); + if(dbZone == null){ - return; - } + log.warn("Unable to find secondary zone with zoneID " + zoneID + " in DB, ignoring zone update"); - dbZone.parse(zone.getZoneCopy(), true); + return; + } - zoneDAO.update(dbZone,transactionHandler, null); + dbZone.parse(zone.getZoneCopy(), true); - transactionHandler.commit(); + zoneDAO.update(dbZone,transactionHandler, null); - log.debug("Changes in seconday zone " + dbZone + " saved"); + transactionHandler.commit(); - } catch (SQLException e) { + log.debug("Changes in seconday zone " + dbZone + " saved"); - log.error("Unable to save changes in secondary zone " + zone.getZoneName(), e); - TransactionHandler.autoClose(transactionHandler); - } - } + } catch (SQLException e) { - public void unload() { + log.error("Unable to save changes in secondary zone " + zone.getZoneName(), e); + TransactionHandler.autoClose(transactionHandler); + } + } - //Nothing to do here... - } + public void unload() { - public void setDriver(String driver) { + //Nothing to do here... + } - this.driver = driver; - } + public void setDriver(String driver) { - public void setUsername(String username) { + this.driver = driver; + } - this.username = username; - } + public void setUsername(String username) { - public void setPassword(String password) { + this.username = username; + } - this.password = password; - } + public void setPassword(String password) { - public void setUrl(String url) { + this.password = password; + } - this.url = url; - } + public void setUrl(String url) { + + this.url = url; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBRecord.java b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBRecord.java index 0abc475f6f5..0167738266a 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBRecord.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBRecord.java @@ -21,167 +21,167 @@ @Table(name="records") public class DBRecord implements Elementable { - @DAOManaged(autoGenerated = true) - @Key - @XMLElement - private Integer recordID; + @DAOManaged(autoGenerated = true) + @Key + @XMLElement + private Integer recordID; - @DAOManaged(columnName = "zoneID") - @ManyToOne(remoteKeyField="zoneID") - @XMLElement - private DBZone zone; + @DAOManaged(columnName = "zoneID") + @ManyToOne(remoteKeyField="zoneID") + @XMLElement + private DBZone zone; - @DAOManaged - @XMLElement - private String name; + @DAOManaged + @XMLElement + private String name; - @DAOManaged - @XMLElement - private String type; + @DAOManaged + @XMLElement + private String type; - @DAOManaged - @XMLElement - private String dclass; + @DAOManaged + @XMLElement + private String dclass; - @DAOManaged - @XMLElement - private String content; + @DAOManaged + @XMLElement + private String content; - @DAOManaged - @XMLElement - private Long ttl; + @DAOManaged + @XMLElement + private Long ttl; - public DBRecord(){} + public DBRecord(){} - public DBRecord(Record record, Name origin, long zoneTTL) { + public DBRecord(Record record, Name origin, long zoneTTL) { - this.name = record.getName().relativize(origin).toString(); - this.type = Type.string(record.getType()); - this.dclass = DClass.string(record.getDClass()); - this.content = record.rdataToString(); - - if(record.getTTL() == zoneTTL){ - - this.ttl = null; - - }else{ - - this.ttl = record.getTTL(); - } - } + this.name = record.getName().relativize(origin).toString(); + this.type = Type.string(record.getType()); + this.dclass = DClass.string(record.getDClass()); + this.content = record.rdataToString(); - public Integer getRecordID() { + if(record.getTTL() == zoneTTL){ - return recordID; - } + this.ttl = null; - public void setRecordID(Integer recordID) { + }else{ - this.recordID = recordID; - } + this.ttl = record.getTTL(); + } + } - public String getName() { + public Integer getRecordID() { - return name; - } + return recordID; + } - public void setName(String name) { + public void setRecordID(Integer recordID) { - this.name = name; - } + this.recordID = recordID; + } - public String getType() { + public String getName() { - return type; - } + return name; + } - public void setType(String type) { + public void setName(String name) { - this.type = type; - } + this.name = name; + } - public String getContent() { + public String getType() { - return content; - } + return type; + } - public void setContent(String content) { + public void setType(String type) { - this.content = content; - } + this.type = type; + } - public Long getTtl() { + public String getContent() { - return ttl; - } + return content; + } - public void setTtl(Long ttl) { + public void setContent(String content) { - this.ttl = ttl; - } + this.content = content; + } - public Element toXML(Document doc) { + public Long getTtl() { - return XMLGenerator.toXML(this, doc); - } + return ttl; + } - public DBZone getZone() { + public void setTtl(Long ttl) { - return zone; - } + this.ttl = ttl; + } - public void setZone(DBZone zone) { + public Element toXML(Document doc) { - this.zone = zone; - } + return XMLGenerator.toXML(this, doc); + } - public Record getRecord(long zoneTTL, Name origin) throws TextParseException, IOException { + public DBZone getZone() { - long ttl; + return zone; + } - if(this.ttl == null){ + public void setZone(DBZone zone) { - ttl = zoneTTL; + this.zone = zone; + } - }else{ + public Record getRecord(long zoneTTL, Name origin) throws TextParseException, IOException { - ttl = this.ttl; - } + long ttl; - StringBuilder stringBuilder = new StringBuilder(); + if(this.ttl == null){ - stringBuilder.append(this.content); + ttl = zoneTTL; - String rdata = stringBuilder.toString(); + }else{ - Record record = Record.fromString(Name.fromString(this.name,origin), Type.value(type), DClass.value(dclass), ttl, rdata, origin); + ttl = this.ttl; + } - return record; - } + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(this.content); - public String getDclass() { + String rdata = stringBuilder.toString(); - return dclass; - } + Record record = Record.fromString(Name.fromString(this.name,origin), Type.value(type), DClass.value(dclass), ttl, rdata, origin); + return record; + } - public void setDclass(String dclass) { - this.dclass = dclass; - } + public String getDclass() { - @Override - public String toString() { + return dclass; + } - if(zone != null){ - - return name + " (ID: " + zone.getZoneID() + ")"; - - }else{ - - return name; - } - - } + + public void setDclass(String dclass) { + + this.dclass = dclass; + } + + @Override + public String toString() { + + if(zone != null){ + + return name + " (ID: " + zone.getZoneID() + ")"; + + }else{ + + return name; + } + + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBSecondaryZone.java b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBSecondaryZone.java index 65fd50deff8..45b022969c7 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBSecondaryZone.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBSecondaryZone.java @@ -6,17 +6,17 @@ public class DBSecondaryZone extends SecondaryZone { - private Integer zoneID; - - public DBSecondaryZone(Integer zoneID, String zoneName, String remoteServerAddress, String dclass) throws TextParseException { - - super(zoneName, remoteServerAddress, dclass); - this.zoneID = zoneID; - } - - - public Integer getZoneID() { - - return zoneID; - } + private Integer zoneID; + + public DBSecondaryZone(Integer zoneID, String zoneName, String remoteServerAddress, String dclass) throws TextParseException { + + super(zoneName, remoteServerAddress, dclass); + this.zoneID = zoneID; + } + + + public Integer getZoneID() { + + return zoneID; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBZone.java b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBZone.java index 309a4a80465..165c892a051 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBZone.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/db/beans/DBZone.java @@ -27,346 +27,346 @@ @Table(name="zones") public class DBZone implements Elementable{ - @DAOManaged(autoGenerated=true) - @Key - @XMLElement - private Integer zoneID; + @DAOManaged(autoGenerated=true) + @Key + @XMLElement + private Integer zoneID; - @DAOManaged - @XMLElement - private String name; + @DAOManaged + @XMLElement + private String name; - @DAOManaged - @XMLElement - private String dclass; + @DAOManaged + @XMLElement + private String dclass; - @DAOManaged - @XMLElement - private Long ttl; + @DAOManaged + @XMLElement + private Long ttl; - @DAOManaged - @XMLElement - private String primaryDNS; + @DAOManaged + @XMLElement + private String primaryDNS; - @DAOManaged - @XMLElement - private String adminEmail; + @DAOManaged + @XMLElement + private String adminEmail; - @DAOManaged - @XMLElement - private Long serial; + @DAOManaged + @XMLElement + private Long serial; - @DAOManaged - @XMLElement - private Long refresh; + @DAOManaged + @XMLElement + private Long refresh; - @DAOManaged - @XMLElement - private Long retry; + @DAOManaged + @XMLElement + private Long retry; - @DAOManaged - @XMLElement - private Long expire; + @DAOManaged + @XMLElement + private Long expire; - @DAOManaged - @XMLElement - private Long minimum; + @DAOManaged + @XMLElement + private Long minimum; - @DAOManaged - @OneToMany - @XMLElement - private List records; + @DAOManaged + @OneToMany + @XMLElement + private List records; - @DAOManaged - @XMLElement - private boolean secondary; + @DAOManaged + @XMLElement + private boolean secondary; - @DAOManaged - @XMLElement - private Timestamp downloaded; + @DAOManaged + @XMLElement + private Timestamp downloaded; - public DBZone() { + public DBZone() { - super(); - } + super(); + } - public DBZone(Zone zone, boolean secondary) { + public DBZone(Zone zone, boolean secondary) { - this.parse(zone, secondary); - } + this.parse(zone, secondary); + } - public void parse(Zone zone, boolean secondary) { + public void parse(Zone zone, boolean secondary) { - if(zone == null){ + if(zone == null){ - this.ttl = null; - this.adminEmail = null; - this.serial = null; - this.refresh = null; - this.retry = null; - this.expire = null; - this.minimum = null; - this.records = null; - this.downloaded = null; + this.ttl = null; + this.adminEmail = null; + this.serial = null; + this.refresh = null; + this.retry = null; + this.expire = null; + this.minimum = null; + this.records = null; + this.downloaded = null; - }else{ + }else{ - SOARecord soaRecord = zone.getSOA(); + SOARecord soaRecord = zone.getSOA(); - this.name = soaRecord.getName().toString(); - this.dclass = DClass.string(soaRecord.getDClass()); - this.ttl = soaRecord.getTTL(); - this.primaryDNS = soaRecord.getHost().toString(); - this.adminEmail = soaRecord.getAdmin().toString(); - this.serial = soaRecord.getSerial(); - this.refresh = soaRecord.getRefresh(); - this.retry = soaRecord.getRetry(); - this.expire = soaRecord.getExpire(); - this.minimum = soaRecord.getMinimum(); - this.secondary = secondary; + this.name = soaRecord.getName().toString(); + this.dclass = DClass.string(soaRecord.getDClass()); + this.ttl = soaRecord.getTTL(); + this.primaryDNS = soaRecord.getHost().toString(); + this.adminEmail = soaRecord.getAdmin().toString(); + this.serial = soaRecord.getSerial(); + this.refresh = soaRecord.getRefresh(); + this.retry = soaRecord.getRetry(); + this.expire = soaRecord.getExpire(); + this.minimum = soaRecord.getMinimum(); + this.secondary = secondary; - if(secondary){ - this.downloaded = new java.sql.Timestamp(System.currentTimeMillis()); - } + if(secondary){ + this.downloaded = new java.sql.Timestamp(System.currentTimeMillis()); + } - this.records = new ArrayList(); + this.records = new ArrayList(); - Iterator iterator = zone.iterator(); + Iterator iterator = zone.iterator(); - while(iterator.hasNext()){ + while(iterator.hasNext()){ - RRset rRset = (RRset) iterator.next(); + RRset rRset = (RRset) iterator.next(); - Iterator rrSetIterator = rRset.rrs(); + Iterator rrSetIterator = rRset.rrs(); - while(rrSetIterator.hasNext()){ + while(rrSetIterator.hasNext()){ - Record record = (Record) rrSetIterator.next(); + Record record = (Record) rrSetIterator.next(); - if(record.getType() == Type.SOA){ - continue; - } + if(record.getType() == Type.SOA){ + continue; + } - this.records.add(new DBRecord(record, zone.getSOA().getName(), this.ttl)); - } - } - } - } + this.records.add(new DBRecord(record, zone.getSOA().getName(), this.ttl)); + } + } + } + } - public String getName() { + public String getName() { - return name; - } + return name; + } - public void setName(String name) { + public void setName(String name) { - this.name = name; - } + this.name = name; + } - public String getDclass() { + public String getDclass() { - return dclass; - } + return dclass; + } - public void setDclass(String dclass) { + public void setDclass(String dclass) { - this.dclass = dclass; - } + this.dclass = dclass; + } - public Long getTtl() { + public Long getTtl() { - return ttl; - } + return ttl; + } - public void setTtl(Long ttl) { + public void setTtl(Long ttl) { - this.ttl = ttl; - } + this.ttl = ttl; + } - public String getPrimaryDNS() { + public String getPrimaryDNS() { - return primaryDNS; - } + return primaryDNS; + } - public void setPrimaryDNS(String primaryDns) { + public void setPrimaryDNS(String primaryDns) { - this.primaryDNS = primaryDns; - } + this.primaryDNS = primaryDns; + } - public String getAdminEmail() { + public String getAdminEmail() { - return adminEmail; - } + return adminEmail; + } - public void setAdminEmail(String adminEmail) { + public void setAdminEmail(String adminEmail) { - this.adminEmail = adminEmail; - } + this.adminEmail = adminEmail; + } - public Long getSerial() { + public Long getSerial() { - return serial; - } + return serial; + } - public void setSerial(Long serial) { + public void setSerial(Long serial) { - this.serial = serial; - } + this.serial = serial; + } - public Long getRefresh() { + public Long getRefresh() { - return refresh; - } + return refresh; + } - public void setRefresh(Long refresh) { + public void setRefresh(Long refresh) { - this.refresh = refresh; - } + this.refresh = refresh; + } - public Long getRetry() { + public Long getRetry() { - return retry; - } + return retry; + } - public void setRetry(Long retry) { + public void setRetry(Long retry) { - this.retry = retry; - } + this.retry = retry; + } - public Long getExpire() { + public Long getExpire() { - return expire; - } + return expire; + } - public void setExpire(Long expire) { + public void setExpire(Long expire) { - this.expire = expire; - } + this.expire = expire; + } - public Long getMinimum() { + public Long getMinimum() { - return minimum; - } + return minimum; + } - public void setMinimum(Long minimum) { + public void setMinimum(Long minimum) { - this.minimum = minimum; - } + this.minimum = minimum; + } - public List getRecords() { + public List getRecords() { - return records; - } + return records; + } - public void setRecords(List records) { + public void setRecords(List records) { - this.records = records; - } + this.records = records; + } - public Integer getZoneID() { + public Integer getZoneID() { - return zoneID; - } + return zoneID; + } - public void setZoneID(Integer zoneID) { + public void setZoneID(Integer zoneID) { - this.zoneID = zoneID; - } + this.zoneID = zoneID; + } - public Element toXML(Document doc) { + public Element toXML(Document doc) { - return XMLGenerator.toXML(this, doc); - } + return XMLGenerator.toXML(this, doc); + } - public Zone toZone() throws IOException{ + public Zone toZone() throws IOException{ - Name zoneName = Name.fromString(name); - Name primaryNS = Name.fromString(this.primaryDNS); + Name zoneName = Name.fromString(name); + Name primaryNS = Name.fromString(this.primaryDNS); - SOARecord soaRecord = new SOARecord(zoneName, DClass.value(dclass), ttl, primaryNS, Name.fromString(this.adminEmail), serial, refresh, retry, expire, minimum); + SOARecord soaRecord = new SOARecord(zoneName, DClass.value(dclass), ttl, primaryNS, Name.fromString(this.adminEmail), serial, refresh, retry, expire, minimum); - //Record primaryNSRecord = Record.newRecord(primaryNS, Type.NS, DClass.value(dclass), ttl); + //Record primaryNSRecord = Record.newRecord(primaryNS, Type.NS, DClass.value(dclass), ttl); - int recordCount; + int recordCount; - if(this.records != null){ + if(this.records != null){ - recordCount = 1 + this.records.size(); + recordCount = 1 + this.records.size(); - }else{ + }else{ - recordCount = 1; - } + recordCount = 1; + } - Record[] recordArray = new Record[recordCount]; + Record[] recordArray = new Record[recordCount]; - recordArray[0] = soaRecord; - //recordArray[1] = primaryNSRecord; + recordArray[0] = soaRecord; + //recordArray[1] = primaryNSRecord; - if(records != null){ + if(records != null){ - int pos = 1; + int pos = 1; - for(DBRecord record : this.records){ + for(DBRecord record : this.records){ - recordArray[pos] = record.getRecord(ttl,zoneName); + recordArray[pos] = record.getRecord(ttl,zoneName); - pos++; - } - } + pos++; + } + } - return new Zone(zoneName,recordArray); - } + return new Zone(zoneName,recordArray); + } - public boolean isSecondary() { + public boolean isSecondary() { - return secondary; - } + return secondary; + } - public void setSecondary(boolean secondary) { + public void setSecondary(boolean secondary) { - this.secondary = secondary; - } + this.secondary = secondary; + } - @Override - public String toString() { + @Override + public String toString() { - return name + " (ID: " + zoneID + ")"; - } + return name + " (ID: " + zoneID + ")"; + } - public Timestamp getDownloaded() { + public Timestamp getDownloaded() { - return downloaded; - } + return downloaded; + } - public void setDownloaded(Timestamp zoneDownloaded) { + public void setDownloaded(Timestamp zoneDownloaded) { - this.downloaded = zoneDownloaded; - } + this.downloaded = zoneDownloaded; + } } diff --git a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/file/FileZoneProvider.java b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/file/FileZoneProvider.java index 6e3eaa439a9..0d94e2fcd9f 100644 --- a/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/file/FileZoneProvider.java +++ b/eagledns/src/main/java/se/unlogic/eagledns/zoneproviders/file/FileZoneProvider.java @@ -31,183 +31,183 @@ */ public class FileZoneProvider implements ZoneProvider, ZoneProviderUpdatable, Runnable { - private final Logger log = Logger.getLogger(this.getClass()); + private final Logger log = Logger.getLogger(this.getClass()); - private String name; - private String zoneFileDirectory; + private String name; + private String zoneFileDirectory; - private boolean autoReloadZones; - private Long pollingInterval; + private boolean autoReloadZones; + private Long pollingInterval; - private Map lastFileList = new HashMap(); + private Map lastFileList = new HashMap(); - private ZoneChangeCallback changeCallback; + private ZoneChangeCallback changeCallback; - private Timer watcher; + private Timer watcher; - public void init(String name) { + public void init(String name) { - this.name = name; + this.name = name; - if(autoReloadZones && pollingInterval != null){ + if(autoReloadZones && pollingInterval != null){ - watcher = new Timer(true); - watcher.schedule(new RunnableTimerTask(this), 5000, pollingInterval); - } - } + watcher = new Timer(true); + watcher.schedule(new RunnableTimerTask(this), 5000, pollingInterval); + } + } - public void run() { + public void run() { - if (changeCallback != null && hasDirectoryChanged()){ + if (changeCallback != null && hasDirectoryChanged()){ - log.info("Changes in directory " + zoneFileDirectory + " detected"); + log.info("Changes in directory " + zoneFileDirectory + " detected"); - changeCallback.zoneDataChanged(); - } - } + changeCallback.zoneDataChanged(); + } + } - private boolean hasDirectoryChanged() { - File folder = new File(this.zoneFileDirectory); - File[] files = folder.listFiles(); - if (files.length != lastFileList.size()) { - return true; - } - for (File f : folder.listFiles()) { - if (!lastFileList.containsKey(f.getName())) { - return true; - } - if (f.lastModified() > lastFileList.get(f.getName())) { - return true; - } - } + private boolean hasDirectoryChanged() { + File folder = new File(this.zoneFileDirectory); + File[] files = folder.listFiles(); + if (files.length != lastFileList.size()) { + return true; + } + for (File f : folder.listFiles()) { + if (!lastFileList.containsKey(f.getName())) { + return true; + } + if (f.lastModified() > lastFileList.get(f.getName())) { + return true; + } + } - return false; - } + return false; + } - /** Refresh our list of zone files for watching */ - private void updateZoneFiles(File[] files) { - lastFileList = new HashMap(); - for (File f : files) { - lastFileList.put(f.getName(), f.lastModified()); - } - } + /** Refresh our list of zone files for watching */ + private void updateZoneFiles(File[] files) { + lastFileList = new HashMap(); + for (File f : files) { + lastFileList.put(f.getName(), f.lastModified()); + } + } - public Collection getPrimaryZones() { + public Collection getPrimaryZones() { - File zoneDir = new File(this.zoneFileDirectory); + File zoneDir = new File(this.zoneFileDirectory); - if(!zoneDir.exists() || !zoneDir.isDirectory()){ + if(!zoneDir.exists() || !zoneDir.isDirectory()){ - log.error("Zone file directory specified for FileZoneProvider " + name + " does not exist!"); - return null; + log.error("Zone file directory specified for FileZoneProvider " + name + " does not exist!"); + return null; - }else if(!zoneDir.canRead()){ + }else if(!zoneDir.canRead()){ - log.error("Zone file directory specified for FileZoneProvider " + name + " is not readable!"); - return null; - } + log.error("Zone file directory specified for FileZoneProvider " + name + " is not readable!"); + return null; + } - File[] files = zoneDir.listFiles(); - updateZoneFiles(files); + File[] files = zoneDir.listFiles(); + updateZoneFiles(files); - if(files == null || files.length == 0){ + if(files == null || files.length == 0){ - log.info("No zone files found for FileZoneProvider " + name + " in directory " + zoneDir.getPath()); - return null; - } + log.info("No zone files found for FileZoneProvider " + name + " in directory " + zoneDir.getPath()); + return null; + } - ArrayList zones = new ArrayList(files.length); + ArrayList zones = new ArrayList(files.length); - for(File zoneFile : files){ + for(File zoneFile : files){ - if(!zoneFile.canRead()){ - log.error("FileZoneProvider " + name + " unable to access zone file " + zoneFile ); - continue; - } + if(!zoneFile.canRead()){ + log.error("FileZoneProvider " + name + " unable to access zone file " + zoneFile ); + continue; + } - Name origin; - try { + Name origin; + try { - origin = Name.fromString(zoneFile.getName(), Name.root); - Zone zone = new Zone(origin, zoneFile.getPath()); + origin = Name.fromString(zoneFile.getName(), Name.root); + Zone zone = new Zone(origin, zoneFile.getPath()); - log.debug("FileZoneProvider " + name + " successfully parsed zone file " + zoneFile.getName()); + log.debug("FileZoneProvider " + name + " successfully parsed zone file " + zoneFile.getName()); - zones.add(zone); + zones.add(zone); - } catch (TextParseException e) { + } catch (TextParseException e) { - log.error("FileZoneProvider " + name + " unable to parse zone file " + zoneFile.getName(),e); + log.error("FileZoneProvider " + name + " unable to parse zone file " + zoneFile.getName(),e); - } catch (IOException e) { + } catch (IOException e) { - log.error("Unable to parse zone file " + zoneFile + " in FileZoneProvider " + name,e); - } - } + log.error("Unable to parse zone file " + zoneFile + " in FileZoneProvider " + name,e); + } + } - if(!zones.isEmpty()){ + if(!zones.isEmpty()){ - return zones; - } + return zones; + } - return null; - } + return null; + } - public void unload() { + public void unload() { - } + } - public String getZoneFileDirectory() { - return zoneFileDirectory; - } + public String getZoneFileDirectory() { + return zoneFileDirectory; + } - public void setZoneFileDirectory(String zoneFileDirectory) { + public void setZoneFileDirectory(String zoneFileDirectory) { - this.zoneFileDirectory = zoneFileDirectory; + this.zoneFileDirectory = zoneFileDirectory; - log.debug("zoneFileDirectory set to " + zoneFileDirectory); - } + log.debug("zoneFileDirectory set to " + zoneFileDirectory); + } - public Collection getSecondaryZones() { + public Collection getSecondaryZones() { - //Not supported - return null; - } + //Not supported + return null; + } - public void zoneUpdated(SecondaryZone secondaryZone) { + public void zoneUpdated(SecondaryZone secondaryZone) { - //Not supported - } + //Not supported + } - public void zoneChecked(SecondaryZone secondaryZone) { + public void zoneChecked(SecondaryZone secondaryZone) { - //Not supported - } + //Not supported + } - public void setChangeListener(ZoneChangeCallback ev) { - this.changeCallback = ev; - } + public void setChangeListener(ZoneChangeCallback ev) { + this.changeCallback = ev; + } - public void setAutoReloadZones(String autoReloadZones) { - this.autoReloadZones = Boolean.parseBoolean(autoReloadZones); - } + public void setAutoReloadZones(String autoReloadZones) { + this.autoReloadZones = Boolean.parseBoolean(autoReloadZones); + } - public void setPollingInterval(String pollingInterval) { + public void setPollingInterval(String pollingInterval) { - Long value = NumberUtils.toLong(pollingInterval); + Long value = NumberUtils.toLong(pollingInterval); - if(value != null && value > 0){ + if(value != null && value > 0){ - this.pollingInterval = value; + this.pollingInterval = value; - }else{ + }else{ - log.warn("Invalid polling interval specified: " + pollingInterval); - } - } + log.warn("Invalid polling interval specified: " + pollingInterval); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsFoundException.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsFoundException.java index 1d60a097fb1..63fd2b0b5f2 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsFoundException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsFoundException.java @@ -11,23 +11,23 @@ public class NoAnnotatedFieldsFoundException extends RuntimeException { - private static final long serialVersionUID = 5295557583550461676L; - private final Class beanClass; - private final Class[] annotations; + private static final long serialVersionUID = 5295557583550461676L; + private final Class beanClass; + private final Class[] annotations; - public NoAnnotatedFieldsFoundException(Class beanClass,Class... annotations) { + public NoAnnotatedFieldsFoundException(Class beanClass,Class... annotations) { - super("No annotated fields found in class " + beanClass + " with annotations " + annotations); + super("No annotated fields found in class " + beanClass + " with annotations " + annotations); - this.beanClass = beanClass; - this.annotations = annotations; - } + this.beanClass = beanClass; + this.annotations = annotations; + } - public Class getBeanClass() { - return beanClass; - } + public Class getBeanClass() { + return beanClass; + } - public Class[] getAnnotations() { - return annotations; - } + public Class[] getAnnotations() { + return annotations; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsOrMethodsFoundException.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsOrMethodsFoundException.java index 5549c49aa2e..a6f84f825a0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsOrMethodsFoundException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/NoAnnotatedFieldsOrMethodsFoundException.java @@ -11,23 +11,23 @@ public class NoAnnotatedFieldsOrMethodsFoundException extends RuntimeException { - private static final long serialVersionUID = 5295557583550461676L; - private final Class beanClass; - private final Class[] annotations; + private static final long serialVersionUID = 5295557583550461676L; + private final Class beanClass; + private final Class[] annotations; - public NoAnnotatedFieldsOrMethodsFoundException(Class beanClass,Class... annotations) { + public NoAnnotatedFieldsOrMethodsFoundException(Class beanClass,Class... annotations) { - super("No annotated fields found in class " + beanClass + " with annotations " + annotations); + super("No annotated fields found in class " + beanClass + " with annotations " + annotations); - this.beanClass = beanClass; - this.annotations = annotations; - } + this.beanClass = beanClass; + this.annotations = annotations; + } - public Class getBeanClass() { - return beanClass; - } + public Class getBeanClass() { + return beanClass; + } - public Class[] getAnnotations() { - return annotations; - } + public Class[] getAnnotations() { + return annotations; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/PopulateOnlyIfSet.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/PopulateOnlyIfSet.java index 9434cfc66a2..c747adf440e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/PopulateOnlyIfSet.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/PopulateOnlyIfSet.java @@ -17,6 +17,6 @@ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.METHOD}) public @interface PopulateOnlyIfSet { - String[] paramNames() default ""; - String[] paramValues() default ""; + String[] paramNames() default ""; + String[] paramValues() default ""; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfNotSet.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfNotSet.java index ec0ebf65d8f..bd8a43da085 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfNotSet.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfNotSet.java @@ -17,6 +17,6 @@ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.METHOD}) public @interface RequiredIfNotSet { - String[] paramNames() default ""; - String[] paramValues() default ""; + String[] paramNames() default ""; + String[] paramValues() default ""; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfSet.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfSet.java index b411f0c8b83..0c2a5f7073a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfSet.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/RequiredIfSet.java @@ -17,6 +17,6 @@ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.METHOD}) public @interface RequiredIfSet { - String paramName(); - String value() default ""; + String paramName(); + String value() default ""; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedFieldTypeException.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedFieldTypeException.java index 9160e536e2f..a43df8b1426 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedFieldTypeException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedFieldTypeException.java @@ -12,28 +12,28 @@ public class UnsupportedFieldTypeException extends RuntimeException { - private static final long serialVersionUID = -6723843186067887845L; - private final Class beanClass; - private final Class annotation; - private final Field field; - - public UnsupportedFieldTypeException(String message, Field field, Class annotation, Class beanClass) { - super(message); - - this.beanClass = beanClass; - this.annotation = annotation; - this.field = field; - } - - public Class getBeanClass() { - return beanClass; - } - - public Field getField() { - return field; - } - - public Class getAnnotation() { - return annotation; - } + private static final long serialVersionUID = -6723843186067887845L; + private final Class beanClass; + private final Class annotation; + private final Field field; + + public UnsupportedFieldTypeException(String message, Field field, Class annotation, Class beanClass) { + super(message); + + this.beanClass = beanClass; + this.annotation = annotation; + this.field = field; + } + + public Class getBeanClass() { + return beanClass; + } + + public Field getField() { + return field; + } + + public Class getAnnotation() { + return annotation; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedMethodArgumentException.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedMethodArgumentException.java index a733f116bde..21548765af9 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedMethodArgumentException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/UnsupportedMethodArgumentException.java @@ -6,29 +6,29 @@ public class UnsupportedMethodArgumentException extends RuntimeException { - private static final long serialVersionUID = 2449699127133031293L; - - private final Class beanClass; - private final Class annotation; - private final Method method; - - public UnsupportedMethodArgumentException(String message, Method method, Class annotation, Class beanClass) { - super(message); - - this.beanClass = beanClass; - this.annotation = annotation; - this.method = method; - } - - public Class getBeanClass() { - return beanClass; - } - - public Method getMethod() { - return method; - } - - public Class getAnnotation() { - return annotation; - } + private static final long serialVersionUID = 2449699127133031293L; + + private final Class beanClass; + private final Class annotation; + private final Method method; + + public UnsupportedMethodArgumentException(String message, Method method, Class annotation, Class beanClass) { + super(message); + + this.beanClass = beanClass; + this.annotation = annotation; + this.method = method; + } + + public Class getBeanClass() { + return beanClass; + } + + public Method getMethod() { + return method; + } + + public Class getAnnotation() { + return annotation; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/annotations/WebPopulate.java b/eagledns/src/main/java/se/unlogic/standardutils/annotations/WebPopulate.java index fa9527efaea..2d82166f5e0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/annotations/WebPopulate.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/annotations/WebPopulate.java @@ -27,11 +27,11 @@ @Target({ElementType.FIELD,ElementType.METHOD}) public @interface WebPopulate { - String paramName() default ""; - boolean required() default false; - long maxLength() default 0; - long minLength() default 0; - String populatorID() default ""; - boolean trim() default true; - Class> populator() default DummyPopulator.class; + String paramName() default ""; + boolean required() default false; + long maxLength() default 0; + long minLength() default 0; + String populatorID() default ""; + boolean trim() default true; + Class> populator() default DummyPopulator.class; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/arrays/ArrayUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/arrays/ArrayUtils.java index 664521d9cec..3f75fc0c98e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/arrays/ArrayUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/arrays/ArrayUtils.java @@ -9,26 +9,26 @@ public class ArrayUtils { - public static T[] toArray(T... values) { - - return values; - } - - public static boolean isEmpty(Object[] array) { - - if(array == null || array.length == 0){ - - return true; - } - - for(Object value : array){ - - if(value != null){ - - return false; - } - } - - return true; - } + public static T[] toArray(T... values) { + + return values; + } + + public static boolean isEmpty(Object[] array) { + + if(array == null || array.length == 0){ + + return true; + } + + for(Object value : array){ + + if(value != null){ + + return false; + } + } + + return true; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanSignal.java b/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanSignal.java index 131c95c2c13..b1d3e044f18 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanSignal.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanSignal.java @@ -9,15 +9,15 @@ public class BooleanSignal { - private boolean signal; + private boolean signal; - public boolean isSignal() { + public boolean isSignal() { - return signal; - } + return signal; + } - public void setSignal(boolean signal) { + public void setSignal(boolean signal) { - this.signal = signal; - } + this.signal = signal; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanUtils.java index a3ae9634230..2018274a2c8 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/bool/BooleanUtils.java @@ -9,12 +9,12 @@ public class BooleanUtils { - public static boolean valueOf(Boolean bool){ + public static boolean valueOf(Boolean bool){ - if(bool == null){ - return false; - }else{ - return bool; - } - } + if(bool == null){ + return false; + }else{ + return bool; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/callback/Callback.java b/eagledns/src/main/java/se/unlogic/standardutils/callback/Callback.java index 612cc8d5ae0..fe624b01e3d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/callback/Callback.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/callback/Callback.java @@ -3,5 +3,5 @@ public interface Callback { - void callback(T type); + void callback(T type); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/callback/SysoutCallback.java b/eagledns/src/main/java/se/unlogic/standardutils/callback/SysoutCallback.java index 4d4a7132b9e..a94ee9036ec 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/callback/SysoutCallback.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/callback/SysoutCallback.java @@ -5,29 +5,29 @@ public class SysoutCallback implements Callback { - protected String prefix; - protected String suffix; - - private static final Logger LOG = Logger.getLogger(SysoutCallback.class); - - public SysoutCallback(String prefix, String suffix) { - - super(); - this.prefix = prefix; - this.suffix = suffix; - - if(prefix == null){ - - this.prefix = ""; - } - - if(suffix == null){ - - this.suffix = ""; - } - } - public void callback(T type) { - - LOG.info(prefix + type.toString() + suffix); - } + protected String prefix; + protected String suffix; + + private static final Logger LOG = Logger.getLogger(SysoutCallback.class); + + public SysoutCallback(String prefix, String suffix) { + + super(); + this.prefix = prefix; + this.suffix = suffix; + + if(prefix == null){ + + this.prefix = ""; + } + + if(suffix == null){ + + this.suffix = ""; + } + } + public void callback(T type) { + + LOG.info(prefix + type.toString() + suffix); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/CollectionUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/CollectionUtils.java index 6b9e19cdc05..d1b377c17a9 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/CollectionUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/CollectionUtils.java @@ -15,128 +15,128 @@ public class CollectionUtils { - public static List getGenericList(Class clazz, int size) { - - return new ArrayList(size); - } - - public static List getGenericList(Class clazz) { + public static List getGenericList(Class clazz, int size) { - return new ArrayList(); - } - - public static List getGenericSingletonList(T bean) { - - ArrayList list = new ArrayList(1); - - list.add(bean); - - return list; - } - - public static boolean isEmpty(Collection collection) { - - if (collection == null || collection.isEmpty()) { - - return true; - } - - return false; - } - - public static List conjunction(Collection c1, Collection c2) { - - if (c1 == null || c2 == null) { - - return null; - - } else { - - List result = new ArrayList(c1.size()); - - for (T o : c1) { - - if (c2.contains(o)) { - - result.add(o); - } - } - return result; - } - } - - /** - * Returns the part of a disjunction of two collections that comes from the first collection (in argument order) - * @param - * @param c1 Collection of objects - * @param c2 Collection of objects - * @return all elements that exists exclusively in c1 - */ - public static Collection exclusiveDisjunction(Collection c1, Collection c2) { - - Collection result = new ArrayList(); - - if(c1 == null && c2 == null) { - - return result; - - } - - if(c1 == null && c2 != null){ - - return c2; - - } - - if(c1 != null && c2 == null) { - - return c1; - - } - - for (T o : c1) { - - if (!c2.contains(o)) { - - result.add(o); - } - } - - return result; - - } - - public static List getList(T... objects) { - - return Arrays.asList(objects); - } - - public static void removeNullValues(List list) { - - Iterator iterator = list.iterator(); - - while (iterator.hasNext()) { - - Object value = iterator.next(); - - if (value == null) { - - iterator.remove(); - } - } - } - - /** - * @param list - * @return the size of the collection or 0 if the collection is null - */ - public static int getSize(Collection collection) { - - if(collection == null){ - - return 0; - } - - return collection.size(); - } + return new ArrayList(size); + } + + public static List getGenericList(Class clazz) { + + return new ArrayList(); + } + + public static List getGenericSingletonList(T bean) { + + ArrayList list = new ArrayList(1); + + list.add(bean); + + return list; + } + + public static boolean isEmpty(Collection collection) { + + if (collection == null || collection.isEmpty()) { + + return true; + } + + return false; + } + + public static List conjunction(Collection c1, Collection c2) { + + if (c1 == null || c2 == null) { + + return null; + + } else { + + List result = new ArrayList(c1.size()); + + for (T o : c1) { + + if (c2.contains(o)) { + + result.add(o); + } + } + return result; + } + } + + /** + * Returns the part of a disjunction of two collections that comes from the first collection (in argument order) + * @param + * @param c1 Collection of objects + * @param c2 Collection of objects + * @return all elements that exists exclusively in c1 + */ + public static Collection exclusiveDisjunction(Collection c1, Collection c2) { + + Collection result = new ArrayList(); + + if(c1 == null && c2 == null) { + + return result; + + } + + if(c1 == null && c2 != null){ + + return c2; + + } + + if(c1 != null && c2 == null) { + + return c1; + + } + + for (T o : c1) { + + if (!c2.contains(o)) { + + result.add(o); + } + } + + return result; + + } + + public static List getList(T... objects) { + + return Arrays.asList(objects); + } + + public static void removeNullValues(List list) { + + Iterator iterator = list.iterator(); + + while (iterator.hasNext()) { + + Object value = iterator.next(); + + if (value == null) { + + iterator.remove(); + } + } + } + + /** + * @param list + * @return the size of the collection or 0 if the collection is null + */ + public static int getSize(Collection collection) { + + if(collection == null){ + + return 0; + } + + return collection.size(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyAlreadyCachedException.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyAlreadyCachedException.java index eef98458e55..422e7299a0c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyAlreadyCachedException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyAlreadyCachedException.java @@ -9,26 +9,26 @@ public class KeyAlreadyCachedException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 6139847169384918434L; - private Object key; - - public KeyAlreadyCachedException(Object key) { - this.key = key; - } + /** + * + */ + private static final long serialVersionUID = 6139847169384918434L; + private Object key; - public Object getKey() { - return key; - } + public KeyAlreadyCachedException(Object key) { + this.key = key; + } - @Override - public String toString() { - if(key != null){ - return "KeyAlreadyCachedException, key: " + key.toString(); - }else{ - return "KeyAlreadyCachedException, key: null"; - } - } + public Object getKey() { + return key; + } + + @Override + public String toString() { + if(key != null){ + return "KeyAlreadyCachedException, key: " + key.toString(); + }else{ + return "KeyAlreadyCachedException, key: null"; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyNotCachedException.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyNotCachedException.java index 59bf31932a0..a79e1a7b466 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyNotCachedException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/KeyNotCachedException.java @@ -9,26 +9,26 @@ public class KeyNotCachedException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1833583474702621444L; - private Object key; - - public KeyNotCachedException(Object key) { - this.key = key; - } + /** + * + */ + private static final long serialVersionUID = 1833583474702621444L; + private Object key; - public Object getKey() { - return key; - } + public KeyNotCachedException(Object key) { + this.key = key; + } - @Override - public String toString() { - if(key != null){ - return "KeyNotCachedException, key: " + key.toString(); - }else{ - return "KeyNotCachedException, key: null"; - } - } + public Object getKey() { + return key; + } + + @Override + public String toString() { + if(key != null){ + return "KeyNotCachedException, key: " + key.toString(); + }else{ + return "KeyNotCachedException, key: null"; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/MethodComparator.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/MethodComparator.java index 3137e8922a3..b97a86a475e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/MethodComparator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/MethodComparator.java @@ -9,56 +9,56 @@ public class MethodComparator implements Comparator { - protected Method method; - protected final Order order; - - public MethodComparator(Class clazz, String methodName, Order order){ - - Method[] methods = clazz.getDeclaredMethods(); - - for(Method method : methods){ - - if(method.getName().equals(methodName) && Comparable.class.isAssignableFrom(method.getReturnType()) && method.getParameterTypes().length == 0){ - - this.method = method; - break; - } - } - - if(method == null){ - - throw new RuntimeException("No method named " + methodName + " returning a comparable class and taking no paramaters found in " + clazz); - } - - this.order = order; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public int compare(T o1, T o2) { - - try { - - if(order == Order.ASC){ - - return ((Comparable)method.invoke(o1)).compareTo(method.invoke(o2)); - - }else{ - - return ((Comparable)method.invoke(o2)).compareTo(method.invoke(o1)); - } - - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - - } catch (InvocationTargetException e) { - - throw new RuntimeException(e); - } - } + protected Method method; + protected final Order order; + + public MethodComparator(Class clazz, String methodName, Order order){ + + Method[] methods = clazz.getDeclaredMethods(); + + for(Method method : methods){ + + if(method.getName().equals(methodName) && Comparable.class.isAssignableFrom(method.getReturnType()) && method.getParameterTypes().length == 0){ + + this.method = method; + break; + } + } + + if(method == null){ + + throw new RuntimeException("No method named " + methodName + " returning a comparable class and taking no paramaters found in " + clazz); + } + + this.order = order; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public int compare(T o1, T o2) { + + try { + + if(order == Order.ASC){ + + return ((Comparable)method.invoke(o1)).compareTo(method.invoke(o2)); + + }else{ + + return ((Comparable)method.invoke(o2)).compareTo(method.invoke(o1)); + } + + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + + } catch (InvocationTargetException e) { + + throw new RuntimeException(e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/NotNullTreeSet.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/NotNullTreeSet.java index 30e27fa5c90..f722a4bceec 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/NotNullTreeSet.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/NotNullTreeSet.java @@ -12,25 +12,25 @@ public class NotNullTreeSet extends TreeSet { - private static final long serialVersionUID = -7808520266670296566L; - - @Override - public boolean add(Type o) { - - if(o == null){ - throw new NullPointerException(this.getClass() + " does not allow null values!"); - } - - return super.add(o); - } - - @Override - public boolean addAll(Collection c) { - - if(c == null || c.contains(null)){ - throw new NullPointerException(this.getClass() + " does not allow null values!"); - } - - return super.addAll(c); - } + private static final long serialVersionUID = -7808520266670296566L; + + @Override + public boolean add(Type o) { + + if(o == null){ + throw new NullPointerException(this.getClass() + " does not allow null values!"); + } + + return super.add(o); + } + + @Override + public boolean addAll(Collection c) { + + if(c == null || c.contains(null)){ + throw new NullPointerException(this.getClass() + " does not allow null values!"); + } + + return super.addAll(c); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictHashMap.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictHashMap.java index 194da4c703e..f938d059bee 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictHashMap.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictHashMap.java @@ -14,98 +14,98 @@ public class StrictHashMap implements StrictMap{ - HashMap hashMap = new HashMap(); - - public Value put(Key key, Value value) throws KeyAlreadyCachedException { - if (this.hashMap.containsKey(key)) { - throw new KeyAlreadyCachedException(key); - } else { - return hashMap.put(key, value); - } - } - - public Value update(Key key, Value value) throws KeyNotCachedException { - if (this.hashMap.containsKey(key)) { - hashMap.remove(key); - return hashMap.put(key, value); - } else { - throw new KeyNotCachedException(key); - } - } - - public Value remove(Object key) throws KeyNotCachedException { - if (hashMap.containsKey(key)) { - return hashMap.remove(key); - } else { - throw new KeyNotCachedException(key); - } - } - - public void clear() { - hashMap.clear(); - } - - @Override - public Object clone() { - return hashMap.clone(); - } - - public boolean containsKey(Object key) { - return hashMap.containsKey(key); - } - - public boolean containsValue(Object value) { - return hashMap.containsValue(value); - } - - public Set> entrySet() { - return hashMap.entrySet(); - } - - @Override - public boolean equals(Object o) { - return hashMap.equals(o); - } - - public Value get(Object key) { - return hashMap.get(key); - } - - @Override - public int hashCode() { - return hashMap.hashCode(); - } - - public boolean isEmpty() { - return hashMap.isEmpty(); - } - - public Set keySet() { - return hashMap.keySet(); - } - - public int size() { - return hashMap.size(); - } - - @Override - public String toString() { - return hashMap.toString(); - } - - public Collection values() { - return hashMap.values(); - } - - public void putAll(Map map) throws KeyAlreadyCachedException{ - - for (Entry entry : map.entrySet()) { - - if (this.hashMap.containsKey(entry.getKey())) { - throw new KeyAlreadyCachedException(entry.getKey()); - } - } - - this.hashMap.putAll(map); - } + HashMap hashMap = new HashMap(); + + public Value put(Key key, Value value) throws KeyAlreadyCachedException { + if (this.hashMap.containsKey(key)) { + throw new KeyAlreadyCachedException(key); + } else { + return hashMap.put(key, value); + } + } + + public Value update(Key key, Value value) throws KeyNotCachedException { + if (this.hashMap.containsKey(key)) { + hashMap.remove(key); + return hashMap.put(key, value); + } else { + throw new KeyNotCachedException(key); + } + } + + public Value remove(Object key) throws KeyNotCachedException { + if (hashMap.containsKey(key)) { + return hashMap.remove(key); + } else { + throw new KeyNotCachedException(key); + } + } + + public void clear() { + hashMap.clear(); + } + + @Override + public Object clone() { + return hashMap.clone(); + } + + public boolean containsKey(Object key) { + return hashMap.containsKey(key); + } + + public boolean containsValue(Object value) { + return hashMap.containsValue(value); + } + + public Set> entrySet() { + return hashMap.entrySet(); + } + + @Override + public boolean equals(Object o) { + return hashMap.equals(o); + } + + public Value get(Object key) { + return hashMap.get(key); + } + + @Override + public int hashCode() { + return hashMap.hashCode(); + } + + public boolean isEmpty() { + return hashMap.isEmpty(); + } + + public Set keySet() { + return hashMap.keySet(); + } + + public int size() { + return hashMap.size(); + } + + @Override + public String toString() { + return hashMap.toString(); + } + + public Collection values() { + return hashMap.values(); + } + + public void putAll(Map map) throws KeyAlreadyCachedException{ + + for (Entry entry : map.entrySet()) { + + if (this.hashMap.containsKey(entry.getKey())) { + throw new KeyAlreadyCachedException(entry.getKey()); + } + } + + this.hashMap.putAll(map); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictMap.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictMap.java index d23d193b999..a302cd3f311 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictMap.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictMap.java @@ -5,9 +5,9 @@ public interface StrictMap extends Map { - Value put(Key key, Value value) throws KeyAlreadyCachedException; + Value put(Key key, Value value) throws KeyAlreadyCachedException; - Value update(Key key, Value value) throws KeyNotCachedException; + Value update(Key key, Value value) throws KeyNotCachedException; - Value remove(Object key) throws KeyNotCachedException; + Value remove(Object key) throws KeyNotCachedException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictTreeMap.java b/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictTreeMap.java index a8cd5142063..f146eca6c95 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictTreeMap.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/collections/StrictTreeMap.java @@ -15,103 +15,103 @@ public class StrictTreeMap implements StrictMap { - protected final TreeMap treeMap; - - public StrictTreeMap (Comparator comparator){ - - treeMap = new TreeMap(comparator); - } - - public Value put(Key key, Value value) throws KeyAlreadyCachedException { - if (this.treeMap.containsKey(key)) { - throw new KeyAlreadyCachedException(key); - } else { - return treeMap.put(key, value); - } - } - - public Value update(Key key, Value value) throws KeyNotCachedException { - if (this.treeMap.containsKey(key)) { - treeMap.remove(key); - return treeMap.put(key, value); - } else { - throw new KeyNotCachedException(key); - } - } - - public Value remove(Object key) throws KeyNotCachedException { - if (treeMap.containsKey(key)) { - return treeMap.remove(key); - } else { - throw new KeyNotCachedException(key); - } - } - - public void clear() { - treeMap.clear(); - } - - @Override - public Object clone() { - return treeMap.clone(); - } - - public boolean containsKey(Object key) { - return treeMap.containsKey(key); - } - - public boolean containsValue(Object value) { - return treeMap.containsValue(value); - } - - public Set> entrySet() { - return treeMap.entrySet(); - } - - @Override - public boolean equals(Object o) { - return treeMap.equals(o); - } - - public Value get(Object key) { - return treeMap.get(key); - } - - @Override - public int hashCode() { - return treeMap.hashCode(); - } - - public boolean isEmpty() { - return treeMap.isEmpty(); - } - - public Set keySet() { - return treeMap.keySet(); - } - - public int size() { - return treeMap.size(); - } - - @Override - public String toString() { - return treeMap.toString(); - } - - public Collection values() { - return treeMap.values(); - } - - public void putAll(Map map) throws KeyAlreadyCachedException{ - - for (Entry entry : map.entrySet()) { - - if (this.treeMap.containsKey(entry.getKey())) { - throw new KeyAlreadyCachedException(entry.getKey()); - } - } - - this.treeMap.putAll(map); - } + protected final TreeMap treeMap; + + public StrictTreeMap (Comparator comparator){ + + treeMap = new TreeMap(comparator); + } + + public Value put(Key key, Value value) throws KeyAlreadyCachedException { + if (this.treeMap.containsKey(key)) { + throw new KeyAlreadyCachedException(key); + } else { + return treeMap.put(key, value); + } + } + + public Value update(Key key, Value value) throws KeyNotCachedException { + if (this.treeMap.containsKey(key)) { + treeMap.remove(key); + return treeMap.put(key, value); + } else { + throw new KeyNotCachedException(key); + } + } + + public Value remove(Object key) throws KeyNotCachedException { + if (treeMap.containsKey(key)) { + return treeMap.remove(key); + } else { + throw new KeyNotCachedException(key); + } + } + + public void clear() { + treeMap.clear(); + } + + @Override + public Object clone() { + return treeMap.clone(); + } + + public boolean containsKey(Object key) { + return treeMap.containsKey(key); + } + + public boolean containsValue(Object value) { + return treeMap.containsValue(value); + } + + public Set> entrySet() { + return treeMap.entrySet(); + } + + @Override + public boolean equals(Object o) { + return treeMap.equals(o); + } + + public Value get(Object key) { + return treeMap.get(key); + } + + @Override + public int hashCode() { + return treeMap.hashCode(); + } + + public boolean isEmpty() { + return treeMap.isEmpty(); + } + + public Set keySet() { + return treeMap.keySet(); + } + + public int size() { + return treeMap.size(); + } + + @Override + public String toString() { + return treeMap.toString(); + } + + public Collection values() { + return treeMap.values(); + } + + public void putAll(Map map) throws KeyAlreadyCachedException{ + + for (Entry entry : map.entrySet()) { + + if (this.treeMap.containsKey(entry.getKey())) { + throw new KeyAlreadyCachedException(entry.getKey()); + } + } + + this.treeMap.putAll(map); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/context/ContextUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/context/ContextUtils.java index 8e7dd774936..d7d26881315 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/context/ContextUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/context/ContextUtils.java @@ -13,13 +13,13 @@ public class ContextUtils { - public static boolean isBound(String resource) throws NamingException { - Context initial = new InitialContext(); - try { - initial.lookup(resource); - return true; - } catch(NamingException e) { - return false; - } - } + public static boolean isBound(String resource) throws NamingException { + Context initial = new InitialContext(); + try { + initial.lookup(resource); + return true; + } catch(NamingException e) { + return false; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/crypto/Base64.java b/eagledns/src/main/java/se/unlogic/standardutils/crypto/Base64.java index 5d54ad43c21..44a2449a209 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/crypto/Base64.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/crypto/Base64.java @@ -117,1804 +117,1804 @@ */ public class Base64 { - /* ******** P U B L I C F I E L D S ******** */ - - /** No options specified. Value is zero. */ - public final static int NO_OPTIONS = 0; - - /** Specify encoding in first bit. Value is one. */ - public final static int ENCODE = 1; - - /** Specify decoding in first bit. Value is zero. */ - public final static int DECODE = 0; - - /** Specify that data should be gzip-compressed in second bit. Value is two. */ - public final static int GZIP = 2; - - /** Specify that gzipped data should not be automatically gunzipped. */ - public final static int DONT_GUNZIP = 4; - - /** Do break lines when encoding. Value is 8. */ - public final static int DO_BREAK_LINES = 8; - - /** - * Encode using Base64-like encoding that is URL- and Filename-safe as described in Section 4 of RFC3548: http://www.faqs.org/rfcs/rfc3548.html. It is important to note that data encoded this way is - * not officially valid Base64, or at the very least should not be called Base64 without also specifying that is was encoded using the URL- and - * Filename-safe dialect. - */ - public final static int URL_SAFE = 16; - - /** - * Encode using the special "ordered" dialect of Base64 described here: http://www.faqs.org/qa/rfcc-1940.html. - */ - public final static int ORDERED = 32; - - /* ******** P R I V A T E F I E L D S ******** */ - - /** Maximum line length (76) of Base64 output. */ - private final static int MAX_LINE_LENGTH = 76; - - /** The equals sign (=) as a byte. */ - private final static byte EQUALS_SIGN = (byte) '='; - - /** The new line character (\n) as a byte. */ - private final static byte NEW_LINE = (byte) '\n'; - - /** Preferred encoding. */ - private final static String PREFERRED_ENCODING = "US-ASCII"; - - private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding - private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding - - private final static Logger logger = Logger.getLogger(Base64.class); - - /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ - - /** The 64 valid Base64 values. */ - /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ - private final static byte[] _STANDARD_ALPHABET = { - (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', - (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', - (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', - (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', - (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', - (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', - (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', - (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', - (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', - (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' - }; - - /** - * Translates a Base64 value to either its 6-bit reconstruction value or a negative number indicating some other meaning. - **/ - private final static byte[] _STANDARD_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9, -9, -9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' - -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 - }; - - /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ - - /** - * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: http://www.faqs.org/rfcs/rfc3548.html. Notice that the last two bytes become "hyphen" and "underscore" - * instead of "plus" and "slash." - */ - private final static byte[] _URL_SAFE_ALPHABET = { - (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', - (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', - (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', - (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', - (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', - (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', - (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', - (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', - (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', - (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' - }; - - /** - * Used in decoding URL- and Filename-safe dialects of Base64. - */ - private final static byte[] _URL_SAFE_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 62, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' - -9, -9, -9, -9, // Decimal 91 - 94 - 63, // Underscore at decimal 95 - -9, // Decimal 96 - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 - }; - - /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ - - /** - * I don't get the point of this technique, but someone requested it, and it is described here: http://www.faqs.org/qa/rfcc-1940.html. - */ - private final static byte[] _ORDERED_ALPHABET = { - (byte) '-', - (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', - (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', - (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', - (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', - (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', - (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', - (byte) '_', - (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', - (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', - (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', - (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' - }; - - /** - * Used in decoding the "ordered" dialect of Base64. - */ - private final static byte[] _ORDERED_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 0, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' - 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' - -9, -9, -9, -9, // Decimal 91 - 94 - 37, // Underscore at decimal 95 - -9, // Decimal 96 - 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' - 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 - }; - - /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ - - /** - * Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified. It's possible, though silly, to specify ORDERED and URLSAFE - * in which case one of them will be picked, though there is no guarantee as to which one will be picked. - */ - private static byte[] getAlphabet(int options) { - - if ((options & URL_SAFE) == URL_SAFE) { - return _URL_SAFE_ALPHABET; - } else if ((options & ORDERED) == ORDERED) { - return _ORDERED_ALPHABET; - } else { - return _STANDARD_ALPHABET; - } - } // end getAlphabet - - /** - * Returns one of the _SOMETHING_DECODABET byte arrays depending on the options specified. It's possible, though silly, to specify ORDERED and URL_SAFE in - * which case one of them will be picked, though there is no guarantee as to which one will be picked. - */ - private static byte[] getDecodabet(int options) { - - if ((options & URL_SAFE) == URL_SAFE) { - return _URL_SAFE_DECODABET; - } else if ((options & ORDERED) == ORDERED) { - return _ORDERED_DECODABET; - } else { - return _STANDARD_DECODABET; - } - } // end getAlphabet - - /** Defeats instantiation. */ - private Base64() { - - } - - /* ******** E N C O D I N G M E T H O D S ******** */ - - /** - * Encodes up to the first three bytes of array threeBytes and returns a four-byte array in Base64 notation. The actual number of significant - * bytes in your array is given by numSigBytes. The array threeBytes needs only be as big as numSigBytes. Code can reuse a - * byte array by passing a four-byte array as b4. - * - * @param b4 A reusable byte array to reduce array instantiation - * @param threeBytes the array to convert - * @param numSigBytes the number of significant bytes in your array - * @return four byte array in Base64 notation. - * @since 1.5.1 - */ - private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) { - - encode3to4(threeBytes, 0, numSigBytes, b4, 0, options); - return b4; - } // end encode3to4 - - /** - *

- * Encodes up to three bytes of the array source and writes the resulting four Base64 bytes to destination. The source and destination - * arrays can be manipulated anywhere along their length by specifying srcOffset and destOffset. This method does not check to make - * sure your arrays are large enough to accomodate srcOffset + 3 for the source array or destOffset + 4 for the - * destination array. The actual number of significant bytes in your array is given by numSigBytes. - *

- *

- * This is the lowest level of the encoding methods with all possible parameters. - *

- * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param numSigBytes the number of significant bytes in your array - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @return the destination array - * @since 1.3 - */ - private static byte[] encode3to4( - byte[] source, int srcOffset, int numSigBytes, - byte[] destination, int destOffset, int options) { - - byte[] ALPHABET = getAlphabet(options); - - // 1 2 3 - // 01234567890123456789012345678901 Bit position - // --------000000001111111122222222 Array position from threeBytes - // --------| || || || | Six bit groups to index ALPHABET - // >>18 >>12 >> 6 >> 0 Right shift necessary - // 0x3f 0x3f 0x3f Additional AND - - // Create buffer with zero-padding if there are only one or two - // significant bytes passed in the array. - // We have to shift left 24 in order to flush out the 1's that appear - // when Java treats a value as negative that is cast from a byte to an int. - int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) - | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) - | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); - - switch (numSigBytes) { - case 3: - destination[destOffset] = ALPHABET[(inBuff >>> 18)]; - destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; - destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; - destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; - return destination; - - case 2: - destination[destOffset] = ALPHABET[(inBuff >>> 18)]; - destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; - destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; - destination[destOffset + 3] = EQUALS_SIGN; - return destination; - - case 1: - destination[destOffset] = ALPHABET[(inBuff >>> 18)]; - destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; - destination[destOffset + 2] = EQUALS_SIGN; - destination[destOffset + 3] = EQUALS_SIGN; - return destination; - - default: - return destination; - } // end switch - } // end encode3to4 - - /** - * Performs Base64 encoding on the raw ByteBuffer, writing it to the encoded ByteBuffer. This is an experimental feature. - * Currently it does not pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}. - * - * @param raw input buffer - * @param encoded output buffer - * @since 2.3 - */ - public static void encode(java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded) { - - byte[] raw3 = new byte[3]; - byte[] enc4 = new byte[4]; - - while (raw.hasRemaining()) { - int rem = Math.min(3, raw.remaining()); - raw.get(raw3, 0, rem); - Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); - encoded.put(enc4); - } // end input remaining - } - - /** - * Performs Base64 encoding on the raw ByteBuffer, writing it to the encoded CharBuffer. This is an experimental feature. - * Currently it does not pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}. - * - * @param raw input buffer - * @param encoded output buffer - * @since 2.3 - */ - public static void encode(java.nio.ByteBuffer raw, java.nio.CharBuffer encoded) { - - byte[] raw3 = new byte[3]; - byte[] enc4 = new byte[4]; - - while (raw.hasRemaining()) { - int rem = Math.min(3, raw.remaining()); - raw.get(raw3, 0, rem); - Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); - for (int i = 0; i < 4; i++) { - encoded.put((char) (enc4[i] & 0xFF)); - } - } // end input remaining - } - - /** - * Serializes an object and returns the Base64-encoded version of that serialized object. - * - *

- * As of v 2.3, if the object cannot be serialized or there is another error, the method will throw an java.io.IOException. This is new to v2.3! In - * earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to handle it. - *

- * - * The object is not GZip-compressed before being encoded. - * - * @param serializableObject The object to encode - * @return The Base64-encoded object - * @throws java.io.IOException if there is an error - * @throws NullPointerException if serializedObject is null - * @since 1.4 - */ - public static String encodeObject(java.io.Serializable serializableObject) - throws java.io.IOException { - - return encodeObject(serializableObject, NO_OPTIONS); - } // end encodeObject - - /** - * Serializes an object and returns the Base64-encoded version of that serialized object. - * - *

- * As of v 2.3, if the object cannot be serialized or there is another error, the method will throw an java.io.IOException. This is new to v2.3! In - * earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to handle it. - *

- * - * The object is not GZip-compressed before being encoded. - *

- * Example options: - * - *

-	 *   GZIP: gzip-compresses object before encoding it.
-	 *   DO_BREAK_LINES: break lines at 76 characters
-	 * 
- *

- * Example: encodeObject( myObj, Base64.GZIP ) or - *

- * Example: encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES ) - * - * @param serializableObject The object to encode - * @param options Specified options - * @return The Base64-encoded object - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @since 2.0 - */ - public static String encodeObject(java.io.Serializable serializableObject, int options) - throws java.io.IOException { - - if (serializableObject == null) { - throw new NullPointerException("Cannot serialize a null object."); - } // end if: null - - // Streams - java.io.ByteArrayOutputStream baos = null; - java.io.OutputStream b64os = null; - java.util.zip.GZIPOutputStream gzos = null; - java.io.ObjectOutputStream oos = null; - - try { - // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream - baos = new java.io.ByteArrayOutputStream(); - b64os = new Base64.OutputStream(baos, ENCODE | options); - if ((options & GZIP) != 0) { - // Gzip - gzos = new java.util.zip.GZIPOutputStream(b64os); - oos = new java.io.ObjectOutputStream(gzos); - } else { - // Not gzipped - oos = new java.io.ObjectOutputStream(b64os); - } - oos.writeObject(serializableObject); - } // end try - catch (java.io.IOException e) { - // Catch it and then throw it immediately so that - // the finally{} block is called for cleanup. - throw e; - } // end catch - finally { - try { - oos.close(); - } catch (Exception e) {} - try { - gzos.close(); - } catch (Exception e) {} - try { - b64os.close(); - } catch (Exception e) {} - try { - baos.close(); - } catch (Exception e) {} - } // end finally - - // Return value according to relevant encoding. - try { - return new String(baos.toByteArray(), PREFERRED_ENCODING); - } // end try - catch (java.io.UnsupportedEncodingException uue) { - // Fall back to some Java default - return new String(baos.toByteArray()); - } // end catch - - } // end encode - - /** - * Encodes a byte array into Base64 notation. Does not GZip-compress data. - * - * @param source The data to convert - * @return The data in Base64-encoded form - * @throws NullPointerException if source array is null - * @since 1.4 - */ - public static String encodeBytes(byte[] source) { - - // Since we're not going to have the GZIP encoding turned on, - // we're not going to have an java.io.IOException thrown, so - // we should not force the user to have to catch it. - String encoded = null; - try { - encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); - } catch (java.io.IOException ex) { - assert false : ex.getMessage(); - } // end catch - assert encoded != null; - return encoded; - } // end encodeBytes - - /** - * Encodes a byte array into Base64 notation. - *

- * Example options: - * - *

-	 *   GZIP: gzip-compresses object before encoding it.
-	 *   DO_BREAK_LINES: break lines at 76 characters
-	 *     Note: Technically, this makes your encoding non-compliant.
-	 * 
- *

- * Example: encodeBytes( myData, Base64.GZIP ) or - *

- * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) - * - * - *

- * As of v 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it - * just returned a null value, but in retrospect that's a pretty poor way to handle it. - *

- * - * - * @param source The data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws NullPointerException if source array is null - * @since 2.0 - */ - public static String encodeBytes(byte[] source, int options) throws java.io.IOException { - - return encodeBytes(source, 0, source.length, options); - } // end encodeBytes - - /** - * Encodes a byte array into Base64 notation. Does not GZip-compress data. - * - *

- * As of v 2.3, if there is an error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned a null - * value, but in retrospect that's a pretty poor way to handle it. - *

- * - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @return The Base64-encoded data as a String - * @throws NullPointerException if source array is null - * @throws IllegalArgumentException if source array, offset, or length are invalid - * @since 1.4 - */ - public static String encodeBytes(byte[] source, int off, int len) { - - // Since we're not going to have the GZIP encoding turned on, - // we're not going to have an java.io.IOException thrown, so - // we should not force the user to have to catch it. - String encoded = null; - try { - encoded = encodeBytes(source, off, len, NO_OPTIONS); - } catch (java.io.IOException ex) { - assert false : ex.getMessage(); - } // end catch - assert encoded != null; - return encoded; - } // end encodeBytes - - /** - * Encodes a byte array into Base64 notation. - *

- * Example options: - * - *

-	 *   GZIP: gzip-compresses object before encoding it.
-	 *   DO_BREAK_LINES: break lines at 76 characters
-	 *     Note: Technically, this makes your encoding non-compliant.
-	 * 
- *

- * Example: encodeBytes( myData, Base64.GZIP ) or - *

- * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) - * - * - *

- * As of v 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it - * just returned a null value, but in retrospect that's a pretty poor way to handle it. - *

- * - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws NullPointerException if source array is null - * @throws IllegalArgumentException if source array, offset, or length are invalid - * @since 2.0 - */ - public static String encodeBytes(byte[] source, int off, int len, int options) throws java.io.IOException { - - byte[] encoded = encodeBytesToBytes(source, off, len, options); - - // Return value according to relevant encoding. - try { - return new String(encoded, PREFERRED_ENCODING); - } // end try - catch (java.io.UnsupportedEncodingException uue) { - return new String(encoded); - } // end catch - - } // end encodeBytes - - /** - * Similar to {@link #encodeBytes(byte[])} but returns a byte array instead of instantiating a String. This is more efficient if you're working with I/O - * streams and have large data sets to encode. - * - * - * @param source The data to convert - * @return The Base64-encoded data as a byte[] (of ASCII characters) - * @throws NullPointerException if source array is null - * @since 2.3.1 - */ - public static byte[] encodeBytesToBytes(byte[] source) { - - byte[] encoded = null; - try { - encoded = encodeBytesToBytes(source, 0, source.length, Base64.NO_OPTIONS); - } catch (java.io.IOException ex) { - assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); - } - return encoded; - } - - /** - * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte array instead of instantiating a String. This is more efficient if you're - * working with I/O streams and have large data sets to encode. - * - * - * @param source The data to convert - * @param off Offset in array where conversion should begin - * @param len Length of data to convert - * @param options Specified options - * @return The Base64-encoded data as a String - * @see Base64#GZIP - * @see Base64#DO_BREAK_LINES - * @throws java.io.IOException if there is an error - * @throws NullPointerException if source array is null - * @throws IllegalArgumentException if source array, offset, or length are invalid - * @since 2.3.1 - */ - public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) throws java.io.IOException { - - if (source == null) { - throw new NullPointerException("Cannot serialize a null array."); - } // end if: null - - if (off < 0) { - throw new IllegalArgumentException("Cannot have negative offset: " + off); - } // end if: off < 0 - - if (len < 0) { - throw new IllegalArgumentException("Cannot have length offset: " + len); - } // end if: len < 0 - - if (off + len > source.length) { - throw new IllegalArgumentException( - String.format("Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); - } // end if: off < 0 - - // Compress? - if ((options & GZIP) != 0) { - java.io.ByteArrayOutputStream baos = null; - java.util.zip.GZIPOutputStream gzos = null; - Base64.OutputStream b64os = null; - - try { - // GZip -> Base64 -> ByteArray - baos = new java.io.ByteArrayOutputStream(); - b64os = new Base64.OutputStream(baos, ENCODE | options); - gzos = new java.util.zip.GZIPOutputStream(b64os); - - gzos.write(source, off, len); - gzos.close(); - } // end try - catch (java.io.IOException e) { - // Catch it and then throw it immediately so that - // the finally{} block is called for cleanup. - throw e; - } // end catch - finally { - try { - gzos.close(); - } catch (Exception e) {} - try { - b64os.close(); - } catch (Exception e) {} - try { - baos.close(); - } catch (Exception e) {} - } // end finally - - return baos.toByteArray(); - } // end if: compress - - // Else, don't compress. Better not to use streams at all then. - else { - boolean breakLines = (options & DO_BREAK_LINES) != 0; - - //int len43 = len * 4 / 3; - //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 - // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding - // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines - // Try to determine more precisely how big the array needs to be. - // If we get it right, we don't have to do an array copy, and - // we save a bunch of memory. - int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding - if (breakLines) { - encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters - } - byte[] outBuff = new byte[encLen]; - - int d = 0; - int e = 0; - int len2 = len - 2; - int lineLength = 0; - for (; d < len2; d += 3, e += 4) { - encode3to4(source, d + off, 3, outBuff, e, options); - - lineLength += 4; - if (breakLines && lineLength >= MAX_LINE_LENGTH) { - outBuff[e + 4] = NEW_LINE; - e++; - lineLength = 0; - } // end if: end of line - } // en dfor: each piece of array - - if (d < len) { - encode3to4(source, d + off, len - d, outBuff, e, options); - e += 4; - } // end if: some padding needed - - // Only resize array if we didn't guess it right. - if (e <= outBuff.length - 1) { - // If breaking lines and the last byte falls right at - // the line length (76 bytes per line), there will be - // one extra byte, and the array will need to be resized. - // Not too bad of an estimate on array size, I'd say. - byte[] finalOut = new byte[e]; - System.arraycopy(outBuff, 0, finalOut, 0, e); - //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); - return finalOut; - } else { - //System.err.println("No need to resize array."); - return outBuff; - } - - } // end else: don't compress - - } // end encodeBytesToBytes - - /* ******** D E C O D I N G M E T H O D S ******** */ - - /** - * Decodes four bytes from array source and writes the resulting bytes (up to three of them) to destination. The source and - * destination arrays can be manipulated anywhere along their length by specifying srcOffset and destOffset. This method does not - * check to make sure your arrays are large enough to accomodate srcOffset + 4 for the source array or destOffset + 3 for - * the destination array. This method returns the actual number of bytes that were converted from the Base64 encoding. - *

- * This is the lowest level of the decoding methods with all possible parameters. - *

- * - * - * @param source the array to convert - * @param srcOffset the index where conversion begins - * @param destination the array to hold the conversion - * @param destOffset the index where output will be put - * @param options alphabet type is pulled from this (standard, url-safe, ordered) - * @return the number of decoded bytes converted - * @throws NullPointerException if source or destination arrays are null - * @throws IllegalArgumentException if srcOffset or destOffset are invalid or there is not enough room in the array. - * @since 1.3 - */ - private static int decode4to3( - byte[] source, int srcOffset, - byte[] destination, int destOffset, int options) { - - // Lots of error checking and exception throwing - if (source == null) { - throw new NullPointerException("Source array was null."); - } // end if - if (destination == null) { - throw new NullPointerException("Destination array was null."); - } // end if - if (srcOffset < 0 || srcOffset + 3 >= source.length) { - throw new IllegalArgumentException(String.format( - "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset)); - } // end if - if (destOffset < 0 || destOffset + 2 >= destination.length) { - throw new IllegalArgumentException(String.format( - "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset)); - } // end if - - byte[] DECODABET = getDecodabet(options); - - // Example: Dk== - if (source[srcOffset + 2] == EQUALS_SIGN) { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); - int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) - | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); - - destination[destOffset] = (byte) (outBuff >>> 16); - return 1; - } - - // Example: DkL= - else if (source[srcOffset + 3] == EQUALS_SIGN) { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); - int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) - | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) - | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); - - destination[destOffset] = (byte) (outBuff >>> 16); - destination[destOffset + 1] = (byte) (outBuff >>> 8); - return 2; - } - - // Example: DkLE - else { - // Two ways to do the same thing. Don't know which way I like best. - //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) - // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) - // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) - // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); - int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) - | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) - | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) - | ((DECODABET[source[srcOffset + 3]] & 0xFF)); - - destination[destOffset] = (byte) (outBuff >> 16); - destination[destOffset + 1] = (byte) (outBuff >> 8); - destination[destOffset + 2] = (byte) (outBuff); - - return 3; - } - } // end decodeToBytes - - /** - * Low-level access to decoding ASCII characters in the form of a byte array. Ignores GUNZIP option, if it's set. This is not generally a - * recommended method, although it is used internally as part of the decoding process. Special case: if len = 0, an empty array is returned. Still, if you - * need more speed and reduced memory footprint (and aren't gzipping), consider this method. - * - * @param source The Base64 encoded data - * @return decoded data - * @since 2.3.1 - */ - public static byte[] decode(byte[] source) - throws java.io.IOException { - - byte[] decoded = null; - // try { - decoded = decode(source, 0, source.length, Base64.NO_OPTIONS); - // } catch( java.io.IOException ex ) { - // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); - // } - return decoded; - } - - /** - * Low-level access to decoding ASCII characters in the form of a byte array. Ignores GUNZIP option, if it's set. This is not generally a - * recommended method, although it is used internally as part of the decoding process. Special case: if len = 0, an empty array is returned. Still, if you - * need more speed and reduced memory footprint (and aren't gzipping), consider this method. - * - * @param source The Base64 encoded data - * @param off The offset of where to begin decoding - * @param len The length of characters to decode - * @param options Can specify options such as alphabet type to use - * @return decoded data - * @throws java.io.IOException If bogus characters exist in source data - * @since 1.3 - */ - public static byte[] decode(byte[] source, int off, int len, int options) - throws java.io.IOException { - - // Lots of error checking and exception throwing - if (source == null) { - throw new NullPointerException("Cannot decode null source array."); - } // end if - if (off < 0 || off + len > source.length) { - throw new IllegalArgumentException(String.format( - "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len)); - } // end if - - if (len == 0) { - return new byte[0]; - } else if (len < 4) { - throw new IllegalArgumentException( - "Base64-encoded string must have at least four characters, but length specified was " + len); - } // end if - - byte[] DECODABET = getDecodabet(options); - - int len34 = len * 3 / 4; // Estimate on array size - byte[] outBuff = new byte[len34]; // Upper limit on size of output - int outBuffPosn = 0; // Keep track of where we're writing - - byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space - int b4Posn = 0; // Keep track of four byte input buffer - int i = 0; // Source array counter - byte sbiDecode = 0; // Special value from DECODABET - - for (i = off; i < off + len; i++) { // Loop through source - - sbiDecode = DECODABET[source[i] & 0xFF]; - - // White space, Equals sign, or legit Base64 character - // Note the values such as -5 and -9 in the - // DECODABETs at the top of the file. - if (sbiDecode >= WHITE_SPACE_ENC) { - if (sbiDecode >= EQUALS_SIGN_ENC) { - b4[b4Posn++] = source[i]; // Save non-whitespace - if (b4Posn > 3) { // Time to decode? - outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options); - b4Posn = 0; - - // If that was the equals sign, break out of 'for' loop - if (source[i] == EQUALS_SIGN) { - break; - } // end if: equals sign - } // end if: quartet built - } // end if: equals sign or better - } // end if: white space, equals sign or better - else { - // There's a bad input character in the Base64 stream. - throw new java.io.IOException(String.format( - "Bad Base64 input character decimal %d in array position %d", (source[i]) & 0xFF, i)); - } // end else: - } // each input character - - byte[] out = new byte[outBuffPosn]; - System.arraycopy(outBuff, 0, out, 0, outBuffPosn); - return out; - } // end decode - - /** - * Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it. - * - * @param s the string to decode - * @return the decoded data - * @throws java.io.IOException If there is a problem - * @since 1.4 - */ - public static byte[] decode(String s) throws java.io.IOException { - - return decode(s, NO_OPTIONS); - } - - /** - * Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it. - * - * @param s the string to decode - * @param options encode options such as URL_SAFE - * @return the decoded data - * @throws java.io.IOException if there is an error - * @throws NullPointerException if s is null - * @since 1.4 - */ - public static byte[] decode(String s, int options) throws java.io.IOException { - - if (s == null) { - throw new NullPointerException("Input string was null."); - } // end if - - byte[] bytes; - try { - bytes = s.getBytes(PREFERRED_ENCODING); - } // end try - catch (java.io.UnsupportedEncodingException uee) { - bytes = s.getBytes(); - } // end catch - // - - // Decode - bytes = decode(bytes, 0, bytes.length, options); - - // Check to see if it's gzip-compressed - // GZIP Magic Two-Byte Number: 0x8b1f (35615) - boolean dontGunzip = (options & DONT_GUNZIP) != 0; - if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) { - - int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); - if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { - java.io.ByteArrayInputStream bais = null; - java.util.zip.GZIPInputStream gzis = null; - java.io.ByteArrayOutputStream baos = null; - byte[] buffer = new byte[2048]; - int length = 0; - - try { - baos = new java.io.ByteArrayOutputStream(); - bais = new java.io.ByteArrayInputStream(bytes); - gzis = new java.util.zip.GZIPInputStream(bais); - - while ((length = gzis.read(buffer)) >= 0) { - baos.write(buffer, 0, length); - } // end while: reading input - - // No error? Get new bytes. - bytes = baos.toByteArray(); - - } // end try - catch (java.io.IOException e) { - logger.error(e.getMessage(), e); - // Just return originally-decoded bytes - } // end catch - finally { - try { - baos.close(); - } catch (Exception e) {} - try { - gzis.close(); - } catch (Exception e) {} - try { - bais.close(); - } catch (Exception e) {} - } // end finally - - } // end if: gzipped - } // end if: bytes.length >= 2 - - return bytes; - } // end decode - - /** - * Attempts to decode Base64 data and deserialize a Java Object within. Returns null if there was an error. - * - * @param encodedObject The Base64 data to decode - * @return The decoded and deserialized object - * @throws NullPointerException if encodedObject is null - * @throws java.io.IOException if there is a general error - * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by the JVM - * @since 1.5 - */ - public static Object decodeToObject(String encodedObject) - throws java.io.IOException, java.lang.ClassNotFoundException { - - return decodeToObject(encodedObject, NO_OPTIONS, null); - } - - /** - * Attempts to decode Base64 data and deserialize a Java Object within. Returns null if there was an error. If loader is not null, it will - * be the class loader used when deserializing. - * - * @param encodedObject The Base64 data to decode - * @param options Various parameters related to decoding - * @param loader Optional class loader to use in deserializing classes. - * @return The decoded and deserialized object - * @throws NullPointerException if encodedObject is null - * @throws java.io.IOException if there is a general error - * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by the JVM - * @since 2.3.4 - */ - public static Object decodeToObject( - String encodedObject, int options, final ClassLoader loader) - throws java.io.IOException, java.lang.ClassNotFoundException { - - // Decode and gunzip if necessary - byte[] objBytes = decode(encodedObject, options); - - java.io.ByteArrayInputStream bais = null; - java.io.ObjectInputStream ois = null; - Object obj = null; - - try { - bais = new java.io.ByteArrayInputStream(objBytes); - - // If no custom class loader is provided, use Java's builtin OIS. - if (loader == null) { - ois = new java.io.ObjectInputStream(bais); - } // end if: no loader provided - - // Else make a customized object input stream that uses - // the provided class loader. - else { - ois = new java.io.ObjectInputStream(bais) { - - @Override - public Class resolveClass(java.io.ObjectStreamClass streamClass) - throws java.io.IOException, ClassNotFoundException { - - Class c = Class.forName(streamClass.getName(), false, loader); - if (c == null) { - return super.resolveClass(streamClass); - } else { - return c; // Class loader knows of this class. - } // end else: not null - } // end resolveClass - }; // end ois - } // end else: no custom class loader - - obj = ois.readObject(); - } // end try - catch (java.io.IOException e) { - throw e; // Catch and throw in order to execute finally{} - } // end catch - catch (java.lang.ClassNotFoundException e) { - throw e; // Catch and throw in order to execute finally{} - } // end catch - finally { - try { - bais.close(); - } catch (Exception e) {} - try { - ois.close(); - } catch (Exception e) {} - } // end finally - - return obj; - } // end decodeObject - - /** - * Convenience method for encoding data to a file. - * - *

- * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, - * but in retrospect that's a pretty poor way to handle it. - *

- * - * @param dataToEncode byte array of data to encode in base64 form - * @param filename Filename for saving encoded data - * @throws java.io.IOException if there is an error - * @throws NullPointerException if dataToEncode is null - * @since 2.1 - */ - public static void encodeToFile(byte[] dataToEncode, String filename) - throws java.io.IOException { - - if (dataToEncode == null) { - throw new NullPointerException("Data to encode was null."); - } // end iff - - Base64.OutputStream bos = null; - try { - bos = new Base64.OutputStream( - new java.io.FileOutputStream(filename), Base64.ENCODE); - bos.write(dataToEncode); - } // end try - catch (java.io.IOException e) { - throw e; // Catch and throw to execute finally{} block - } // end catch: java.io.IOException - finally { - try { - bos.close(); - } catch (Exception e) {} - } // end finally - - } // end encodeToFile - - /** - * Convenience method for decoding data to a file. - * - *

- * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, - * but in retrospect that's a pretty poor way to handle it. - *

- * - * @param dataToDecode Base64-encoded data as a string - * @param filename Filename for saving decoded data - * @throws java.io.IOException if there is an error - * @since 2.1 - */ - public static void decodeToFile(String dataToDecode, String filename) - throws java.io.IOException { - - Base64.OutputStream bos = null; - try { - bos = new Base64.OutputStream( - new java.io.FileOutputStream(filename), Base64.DECODE); - bos.write(dataToDecode.getBytes(PREFERRED_ENCODING)); - } // end try - catch (java.io.IOException e) { - throw e; // Catch and throw to execute finally{} block - } // end catch: java.io.IOException - finally { - try { - bos.close(); - } catch (Exception e) {} - } // end finally - - } // end decodeToFile - - /** - * Convenience method for reading a base64-encoded file and decoding it. - * - *

- * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, - * but in retrospect that's a pretty poor way to handle it. - *

- * - * @param filename Filename for reading encoded data - * @return decoded byte array - * @throws java.io.IOException if there is an error - * @since 2.1 - */ - public static byte[] decodeFromFile(String filename) - throws java.io.IOException { - - byte[] decodedData = null; - Base64.InputStream bis = null; - try { - // Set up some useful variables - java.io.File file = new java.io.File(filename); - byte[] buffer = null; - int length = 0; - int numBytes = 0; - - // Check for size of file - if (file.length() > Integer.MAX_VALUE) { - throw new java.io.IOException("File is too big for this convenience method (" + file.length() + " bytes)."); - } // end if: file too big for int index - buffer = new byte[(int) file.length()]; - - // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream(file)), Base64.DECODE); - - // Read until done - while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { - length += numBytes; - } // end while - - // Save in a variable to return - decodedData = new byte[length]; - System.arraycopy(buffer, 0, decodedData, 0, length); - - } // end try - catch (java.io.IOException e) { - throw e; // Catch and release to execute finally{} - } // end catch: java.io.IOException - finally { - try { - bis.close(); - } catch (Exception e) {} - } // end finally - - return decodedData; - } // end decodeFromFile - - /** - * Convenience method for reading a binary file and base64-encoding it. - * - *

- * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, - * but in retrospect that's a pretty poor way to handle it. - *

- * - * @param filename Filename for reading binary data - * @return base64-encoded string - * @throws java.io.IOException if there is an error - * @since 2.1 - */ - public static String encodeFromFile(String filename) - throws java.io.IOException { - - String encodedData = null; - Base64.InputStream bis = null; - try { - // Set up some useful variables - java.io.File file = new java.io.File(filename); - byte[] buffer = new byte[Math.max((int) (file.length() * 1.4 + 1), 40)]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) - int length = 0; - int numBytes = 0; - - // Open a stream - bis = new Base64.InputStream( - new java.io.BufferedInputStream( - new java.io.FileInputStream(file)), Base64.ENCODE); - - // Read until done - while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { - length += numBytes; - } // end while - - // Save in a variable to return - encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING); - - } // end try - catch (java.io.IOException e) { - throw e; // Catch and release to execute finally{} - } // end catch: java.io.IOException - finally { - try { - bis.close(); - } catch (Exception e) {} - } // end finally - - return encodedData; - } // end encodeFromFile - - /** - * Reads infile and encodes it to outfile. - * - * @param infile Input file - * @param outfile Output file - * @throws java.io.IOException if there is an error - * @since 2.2 - */ - public static void encodeFileToFile(String infile, String outfile) - throws java.io.IOException { - - String encoded = Base64.encodeFromFile(infile); - java.io.OutputStream out = null; - try { - out = new java.io.BufferedOutputStream( - new java.io.FileOutputStream(outfile)); - out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output. - } // end try - catch (java.io.IOException e) { - throw e; // Catch and release to execute finally{} - } // end catch - finally { - try { - out.close(); - } catch (Exception ex) {} - } // end finally - } // end encodeFileToFile - - /** - * Reads infile and decodes it to outfile. - * - * @param infile Input file - * @param outfile Output file - * @throws java.io.IOException if there is an error - * @since 2.2 - */ - public static void decodeFileToFile(String infile, String outfile) - throws java.io.IOException { - - byte[] decoded = Base64.decodeFromFile(infile); - java.io.OutputStream out = null; - try { - out = new java.io.BufferedOutputStream( - new java.io.FileOutputStream(outfile)); - out.write(decoded); - } // end try - catch (java.io.IOException e) { - throw e; // Catch and release to execute finally{} - } // end catch - finally { - try { - out.close(); - } catch (Exception ex) {} - } // end finally - } // end decodeFileToFile - - /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ - - /** - * A {@link Base64.InputStream} will read data from another java.io.InputStream, given in the constructor, and encode/decode to/from Base64 - * notation on the fly. - * - * @see Base64 - * @since 1.3 - */ - public static class InputStream extends java.io.FilterInputStream { - - private boolean encode; // Encoding or decoding - private int position; // Current position in the buffer - private byte[] buffer; // Small buffer holding converted data - private int bufferLength; // Length of buffer (3 or 4) - private int numSigBytes; // Number of meaningful bytes in the buffer - private int lineLength; - private boolean breakLines; // Break lines at less than 80 characters - private int options; // Record options used to create the stream. - private byte[] decodabet; // Local copies to avoid extra method calls - - /** - * Constructs a {@link Base64.InputStream} in DECODE mode. - * - * @param in the java.io.InputStream from which to read data. - * @since 1.3 - */ - public InputStream(java.io.InputStream in) { - - this(in, DECODE); - } // end constructor - - /** - * Constructs a {@link Base64.InputStream} in either ENCODE or DECODE mode. - *

- * Valid options: - * - *

-		 *   ENCODE or DECODE: Encode or Decode as data is read.
-		 *   DO_BREAK_LINES: break lines at 76 characters
-		 *     (only meaningful when encoding)
-		 * 
- *

- * Example: new Base64.InputStream( in, Base64.DECODE ) - * - * - * @param in the java.io.InputStream from which to read data. - * @param options Specified options - * @see Base64#ENCODE - * @see Base64#DECODE - * @see Base64#DO_BREAK_LINES - * @since 2.0 - */ - public InputStream(java.io.InputStream in, int options) { - - super(in); - this.options = options; // Record for later - this.breakLines = (options & DO_BREAK_LINES) > 0; - this.encode = (options & ENCODE) > 0; - this.bufferLength = encode ? 4 : 3; - this.buffer = new byte[bufferLength]; - this.position = -1; - this.lineLength = 0; - this.decodabet = getDecodabet(options); - } // end constructor - - /** - * Reads enough of the input stream to convert to/from Base64 and returns the next byte. - * - * @return next byte - * @since 1.3 - */ - @Override - public int read() throws java.io.IOException { - - // Do we need to get data? - if (position < 0) { - if (encode) { - byte[] b3 = new byte[3]; - int numBinaryBytes = 0; - for (int i = 0; i < 3; i++) { - int b = in.read(); - - // If end of stream, b is -1. - if (b >= 0) { - b3[i] = (byte) b; - numBinaryBytes++; - } else { - break; // out of for loop - } // end else: end of stream - - } // end for: each needed input byte - - if (numBinaryBytes > 0) { - encode3to4(b3, 0, numBinaryBytes, buffer, 0, options); - position = 0; - numSigBytes = 4; - } // end if: got data - else { - return -1; // Must be end of stream - } // end else - } // end if: encoding - - // Else decoding - else { - byte[] b4 = new byte[4]; - int i = 0; - for (i = 0; i < 4; i++) { - // Read four "meaningful" bytes: - int b = 0; - do { - b = in.read(); - } while (b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC); - - if (b < 0) { - break; // Reads a -1 if end of stream - } // end if: end of stream - - b4[i] = (byte) b; - } // end for: each needed input byte - - if (i == 4) { - numSigBytes = decode4to3(b4, 0, buffer, 0, options); - position = 0; - } // end if: got four characters - else if (i == 0) { - return -1; - } // end else if: also padded correctly - else { - // Must have broken out from above. - throw new java.io.IOException("Improperly padded Base64 input."); - } // end - - } // end else: decode - } // end else: get data - - // Got data? - if (position >= 0) { - // End of relevant data? - if ( /* !encode && */position >= numSigBytes) { - return -1; - } // end if: got data - - if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { - lineLength = 0; - return '\n'; - } // end if - else { - lineLength++; // This isn't important when decoding - // but throwing an extra "if" seems - // just as wasteful. - - int b = buffer[position++]; - - if (position >= bufferLength) { - position = -1; - } // end if: end - - return b & 0xFF; // This is how you "cast" a byte that's - // intended to be unsigned. - } // end else - } // end if: position >= 0 - - // Else error - else { - throw new java.io.IOException("Error in Base64 code reading stream."); - } // end else - } // end read - - /** - * Calls {@link #read()} repeatedly until the end of stream is reached or len bytes are read. Returns number of bytes read into array or -1 - * if end of stream is encountered. - * - * @param dest array to hold values - * @param off offset for array - * @param len max number of bytes to read into array - * @return bytes read into array or -1 if end of stream is encountered. - * @since 1.3 - */ - @Override - public int read(byte[] dest, int off, int len) - throws java.io.IOException { - - int i; - int b; - for (i = 0; i < len; i++) { - b = read(); - - if (b >= 0) { - dest[off + i] = (byte) b; - } else if (i == 0) { - return -1; - } else { - break; // Out of 'for' loop - } // Out of 'for' loop - } // end for: each byte read - return i; - } // end read - - } // end inner class InputStream - - /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ - - /** - * A {@link Base64.OutputStream} will write data to another java.io.OutputStream, given in the constructor, and encode/decode to/from Base64 - * notation on the fly. - * - * @see Base64 - * @since 1.3 - */ - public static class OutputStream extends java.io.FilterOutputStream { - - private boolean encode; - private int position; - private byte[] buffer; - private int bufferLength; - private int lineLength; - private boolean breakLines; - private byte[] b4; // Scratch used in a few places - private boolean suspendEncoding; - private int options; // Record for later - private byte[] decodabet; // Local copies to avoid extra method calls - - /** - * Constructs a {@link Base64.OutputStream} in ENCODE mode. - * - * @param out the java.io.OutputStream to which data will be written. - * @since 1.3 - */ - public OutputStream(java.io.OutputStream out) { - - this(out, ENCODE); - } // end constructor - - /** - * Constructs a {@link Base64.OutputStream} in either ENCODE or DECODE mode. - *

- * Valid options: - * - *

-		 *   ENCODE or DECODE: Encode or Decode as data is read.
-		 *   DO_BREAK_LINES: don't break lines at 76 characters
-		 *     (only meaningful when encoding)
-		 * 
- *

- * Example: new Base64.OutputStream( out, Base64.ENCODE ) - * - * @param out the java.io.OutputStream to which data will be written. - * @param options Specified options. - * @see Base64#ENCODE - * @see Base64#DECODE - * @see Base64#DO_BREAK_LINES - * @since 1.3 - */ - public OutputStream(java.io.OutputStream out, int options) { - - super(out); - this.breakLines = (options & DO_BREAK_LINES) != 0; - this.encode = (options & ENCODE) != 0; - this.bufferLength = encode ? 3 : 4; - this.buffer = new byte[bufferLength]; - this.position = 0; - this.lineLength = 0; - this.suspendEncoding = false; - this.b4 = new byte[4]; - this.options = options; - this.decodabet = getDecodabet(options); - } // end constructor - - /** - * Writes the byte to the output stream after converting to/from Base64 notation. When encoding, bytes are buffered three at a time before the output - * stream actually gets a write() call. When decoding, bytes are buffered four at a time. - * - * @param theByte the byte to write - * @since 1.3 - */ - @Override - public void write(int theByte) - throws java.io.IOException { - - // Encoding suspended? - if (suspendEncoding) { - this.out.write(theByte); - return; - } // end if: supsended - - // Encode? - if (encode) { - buffer[position++] = (byte) theByte; - if (position >= bufferLength) { // Enough to encode. - - this.out.write(encode3to4(b4, buffer, bufferLength, options)); - - lineLength += 4; - if (breakLines && lineLength >= MAX_LINE_LENGTH) { - this.out.write(NEW_LINE); - lineLength = 0; - } // end if: end of line - - position = 0; - } // end if: enough to output - } // end if: encoding - - // Else, Decoding - else { - // Meaningful Base64 character? - if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) { - buffer[position++] = (byte) theByte; - if (position >= bufferLength) { // Enough to output. - - int len = Base64.decode4to3(buffer, 0, b4, 0, options); - out.write(b4, 0, len); - position = 0; - } // end if: enough to output - } // end if: meaningful base64 character - else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) { - throw new java.io.IOException("Invalid character in Base64 data."); - } // end else: not white space either - } // end else: decoding - } // end write - - /** - * Calls {@link #write(int)} repeatedly until len bytes are written. - * - * @param theBytes array from which to read bytes - * @param off offset for array - * @param len max number of bytes to read into array - * @since 1.3 - */ - @Override - public void write(byte[] theBytes, int off, int len) - throws java.io.IOException { - - // Encoding suspended? - if (suspendEncoding) { - this.out.write(theBytes, off, len); - return; - } // end if: supsended - - for (int i = 0; i < len; i++) { - write(theBytes[off + i]); - } // end for: each byte written - - } // end write - - /** - * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer without closing the stream. - * - * @throws java.io.IOException if there's an error. - */ - public void flushBase64() throws java.io.IOException { - - if (position > 0) { - if (encode) { - out.write(encode3to4(b4, buffer, position, options)); - position = 0; - } // end if: encoding - else { - throw new java.io.IOException("Base64 input not properly padded."); - } // end else: decoding - } // end if: buffer partially full - - } // end flush - - /** - * Flushes and closes (I think, in the superclass) the stream. - * - * @since 1.3 - */ - @Override - public void close() throws java.io.IOException { - - // 1. Ensure that pending characters are written - flushBase64(); - - // 2. Actually close the stream - // Base class both flushes and closes. - super.close(); - - buffer = null; - out = null; - } // end close - - /** - * Suspends encoding of the stream. May be helpful if you need to embed a piece of base64-encoded data in a stream. - * - * @throws java.io.IOException if there's an error flushing - * @since 1.5.1 - */ - public void suspendEncoding() throws java.io.IOException { - - flushBase64(); - this.suspendEncoding = true; - } // end suspendEncoding - - /** - * Resumes encoding of the stream. May be helpful if you need to embed a piece of base64-encoded data in a stream. - * - * @since 1.5.1 - */ - public void resumeEncoding() { - - this.suspendEncoding = false; - } // end resumeEncoding - - } // end inner class OutputStream + /* ******** P U B L I C F I E L D S ******** */ + + /** No options specified. Value is zero. */ + public final static int NO_OPTIONS = 0; + + /** Specify encoding in first bit. Value is one. */ + public final static int ENCODE = 1; + + /** Specify decoding in first bit. Value is zero. */ + public final static int DECODE = 0; + + /** Specify that data should be gzip-compressed in second bit. Value is two. */ + public final static int GZIP = 2; + + /** Specify that gzipped data should not be automatically gunzipped. */ + public final static int DONT_GUNZIP = 4; + + /** Do break lines when encoding. Value is 8. */ + public final static int DO_BREAK_LINES = 8; + + /** + * Encode using Base64-like encoding that is URL- and Filename-safe as described in Section 4 of RFC3548: http://www.faqs.org/rfcs/rfc3548.html. It is important to note that data encoded this way is + * not officially valid Base64, or at the very least should not be called Base64 without also specifying that is was encoded using the URL- and + * Filename-safe dialect. + */ + public final static int URL_SAFE = 16; + + /** + * Encode using the special "ordered" dialect of Base64 described here: http://www.faqs.org/qa/rfcc-1940.html. + */ + public final static int ORDERED = 32; + + /* ******** P R I V A T E F I E L D S ******** */ + + /** Maximum line length (76) of Base64 output. */ + private final static int MAX_LINE_LENGTH = 76; + + /** The equals sign (=) as a byte. */ + private final static byte EQUALS_SIGN = (byte) '='; + + /** The new line character (\n) as a byte. */ + private final static byte NEW_LINE = (byte) '\n'; + + /** Preferred encoding. */ + private final static String PREFERRED_ENCODING = "US-ASCII"; + + private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding + private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding + + private final static Logger logger = Logger.getLogger(Base64.class); + + /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ + + /** The 64 valid Base64 values. */ + /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ + private final static byte[] _STANDARD_ALPHABET = { + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', + (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' + }; + + /** + * Translates a Base64 value to either its 6-bit reconstruction value or a negative number indicating some other meaning. + **/ + private final static byte[] _STANDARD_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + 62, // Plus sign at decimal 43 + -9, -9, -9, // Decimal 44 - 46 + 63, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + }; + + /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ + + /** + * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: http://www.faqs.org/rfcs/rfc3548.html. Notice that the last two bytes become "hyphen" and "underscore" + * instead of "plus" and "slash." + */ + private final static byte[] _URL_SAFE_ALPHABET = { + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', + (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' + }; + + /** + * Used in decoding URL- and Filename-safe dialects of Base64. + */ + private final static byte[] _URL_SAFE_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 62, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 + 63, // Underscore at decimal 95 + -9, // Decimal 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + }; + + /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ + + /** + * I don't get the point of this technique, but someone requested it, and it is described here: http://www.faqs.org/qa/rfcc-1940.html. + */ + private final static byte[] _ORDERED_ALPHABET = { + (byte) '-', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', + (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) '_', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' + }; + + /** + * Used in decoding the "ordered" dialect of Base64. + */ + private final static byte[] _ORDERED_DECODABET = { + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 0, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' + 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 + 37, // Underscore at decimal 95 + -9, // Decimal 96 + 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + }; + + /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ + + /** + * Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified. It's possible, though silly, to specify ORDERED and URLSAFE + * in which case one of them will be picked, though there is no guarantee as to which one will be picked. + */ + private static byte[] getAlphabet(int options) { + + if ((options & URL_SAFE) == URL_SAFE) { + return _URL_SAFE_ALPHABET; + } else if ((options & ORDERED) == ORDERED) { + return _ORDERED_ALPHABET; + } else { + return _STANDARD_ALPHABET; + } + } // end getAlphabet + + /** + * Returns one of the _SOMETHING_DECODABET byte arrays depending on the options specified. It's possible, though silly, to specify ORDERED and URL_SAFE in + * which case one of them will be picked, though there is no guarantee as to which one will be picked. + */ + private static byte[] getDecodabet(int options) { + + if ((options & URL_SAFE) == URL_SAFE) { + return _URL_SAFE_DECODABET; + } else if ((options & ORDERED) == ORDERED) { + return _ORDERED_DECODABET; + } else { + return _STANDARD_DECODABET; + } + } // end getAlphabet + + /** Defeats instantiation. */ + private Base64() { + + } + + /* ******** E N C O D I N G M E T H O D S ******** */ + + /** + * Encodes up to the first three bytes of array threeBytes and returns a four-byte array in Base64 notation. The actual number of significant + * bytes in your array is given by numSigBytes. The array threeBytes needs only be as big as numSigBytes. Code can reuse a + * byte array by passing a four-byte array as b4. + * + * @param b4 A reusable byte array to reduce array instantiation + * @param threeBytes the array to convert + * @param numSigBytes the number of significant bytes in your array + * @return four byte array in Base64 notation. + * @since 1.5.1 + */ + private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) { + + encode3to4(threeBytes, 0, numSigBytes, b4, 0, options); + return b4; + } // end encode3to4 + + /** + *

+ * Encodes up to three bytes of the array source and writes the resulting four Base64 bytes to destination. The source and destination + * arrays can be manipulated anywhere along their length by specifying srcOffset and destOffset. This method does not check to make + * sure your arrays are large enough to accomodate srcOffset + 3 for the source array or destOffset + 4 for the + * destination array. The actual number of significant bytes in your array is given by numSigBytes. + *

+ *

+ * This is the lowest level of the encoding methods with all possible parameters. + *

+ * + * @param source the array to convert + * @param srcOffset the index where conversion begins + * @param numSigBytes the number of significant bytes in your array + * @param destination the array to hold the conversion + * @param destOffset the index where output will be put + * @return the destination array + * @since 1.3 + */ + private static byte[] encode3to4( + byte[] source, int srcOffset, int numSigBytes, + byte[] destination, int destOffset, int options) { + + byte[] ALPHABET = getAlphabet(options); + + // 1 2 3 + // 01234567890123456789012345678901 Bit position + // --------000000001111111122222222 Array position from threeBytes + // --------| || || || | Six bit groups to index ALPHABET + // >>18 >>12 >> 6 >> 0 Right shift necessary + // 0x3f 0x3f 0x3f Additional AND + + // Create buffer with zero-padding if there are only one or two + // significant bytes passed in the array. + // We have to shift left 24 in order to flush out the 1's that appear + // when Java treats a value as negative that is cast from a byte to an int. + int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) + | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) + | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); + + switch (numSigBytes) { + case 3: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f]; + return destination; + + case 2: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f]; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + case 1: + destination[destOffset] = ALPHABET[(inBuff >>> 18)]; + destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f]; + destination[destOffset + 2] = EQUALS_SIGN; + destination[destOffset + 3] = EQUALS_SIGN; + return destination; + + default: + return destination; + } // end switch + } // end encode3to4 + + /** + * Performs Base64 encoding on the raw ByteBuffer, writing it to the encoded ByteBuffer. This is an experimental feature. + * Currently it does not pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}. + * + * @param raw input buffer + * @param encoded output buffer + * @since 2.3 + */ + public static void encode(java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded) { + + byte[] raw3 = new byte[3]; + byte[] enc4 = new byte[4]; + + while (raw.hasRemaining()) { + int rem = Math.min(3, raw.remaining()); + raw.get(raw3, 0, rem); + Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); + encoded.put(enc4); + } // end input remaining + } + + /** + * Performs Base64 encoding on the raw ByteBuffer, writing it to the encoded CharBuffer. This is an experimental feature. + * Currently it does not pass along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}. + * + * @param raw input buffer + * @param encoded output buffer + * @since 2.3 + */ + public static void encode(java.nio.ByteBuffer raw, java.nio.CharBuffer encoded) { + + byte[] raw3 = new byte[3]; + byte[] enc4 = new byte[4]; + + while (raw.hasRemaining()) { + int rem = Math.min(3, raw.remaining()); + raw.get(raw3, 0, rem); + Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS); + for (int i = 0; i < 4; i++) { + encoded.put((char) (enc4[i] & 0xFF)); + } + } // end input remaining + } + + /** + * Serializes an object and returns the Base64-encoded version of that serialized object. + * + *

+ * As of v 2.3, if the object cannot be serialized or there is another error, the method will throw an java.io.IOException. This is new to v2.3! In + * earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to handle it. + *

+ * + * The object is not GZip-compressed before being encoded. + * + * @param serializableObject The object to encode + * @return The Base64-encoded object + * @throws java.io.IOException if there is an error + * @throws NullPointerException if serializedObject is null + * @since 1.4 + */ + public static String encodeObject(java.io.Serializable serializableObject) + throws java.io.IOException { + + return encodeObject(serializableObject, NO_OPTIONS); + } // end encodeObject + + /** + * Serializes an object and returns the Base64-encoded version of that serialized object. + * + *

+ * As of v 2.3, if the object cannot be serialized or there is another error, the method will throw an java.io.IOException. This is new to v2.3! In + * earlier versions, it just returned a null value, but in retrospect that's a pretty poor way to handle it. + *

+ * + * The object is not GZip-compressed before being encoded. + *

+ * Example options: + * + *

+    *   GZIP: gzip-compresses object before encoding it.
+    *   DO_BREAK_LINES: break lines at 76 characters
+    * 
+ *

+ * Example: encodeObject( myObj, Base64.GZIP ) or + *

+ * Example: encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES ) + * + * @param serializableObject The object to encode + * @param options Specified options + * @return The Base64-encoded object + * @see Base64#GZIP + * @see Base64#DO_BREAK_LINES + * @throws java.io.IOException if there is an error + * @since 2.0 + */ + public static String encodeObject(java.io.Serializable serializableObject, int options) + throws java.io.IOException { + + if (serializableObject == null) { + throw new NullPointerException("Cannot serialize a null object."); + } // end if: null + + // Streams + java.io.ByteArrayOutputStream baos = null; + java.io.OutputStream b64os = null; + java.util.zip.GZIPOutputStream gzos = null; + java.io.ObjectOutputStream oos = null; + + try { + // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream + baos = new java.io.ByteArrayOutputStream(); + b64os = new Base64.OutputStream(baos, ENCODE | options); + if ((options & GZIP) != 0) { + // Gzip + gzos = new java.util.zip.GZIPOutputStream(b64os); + oos = new java.io.ObjectOutputStream(gzos); + } else { + // Not gzipped + oos = new java.io.ObjectOutputStream(b64os); + } + oos.writeObject(serializableObject); + } // end try + catch (java.io.IOException e) { + // Catch it and then throw it immediately so that + // the finally{} block is called for cleanup. + throw e; + } // end catch + finally { + try { + oos.close(); + } catch (Exception e) {} + try { + gzos.close(); + } catch (Exception e) {} + try { + b64os.close(); + } catch (Exception e) {} + try { + baos.close(); + } catch (Exception e) {} + } // end finally + + // Return value according to relevant encoding. + try { + return new String(baos.toByteArray(), PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uue) { + // Fall back to some Java default + return new String(baos.toByteArray()); + } // end catch + + } // end encode + + /** + * Encodes a byte array into Base64 notation. Does not GZip-compress data. + * + * @param source The data to convert + * @return The data in Base64-encoded form + * @throws NullPointerException if source array is null + * @since 1.4 + */ + public static String encodeBytes(byte[] source) { + + // Since we're not going to have the GZIP encoding turned on, + // we're not going to have an java.io.IOException thrown, so + // we should not force the user to have to catch it. + String encoded = null; + try { + encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); + } catch (java.io.IOException ex) { + assert false : ex.getMessage(); + } // end catch + assert encoded != null; + return encoded; + } // end encodeBytes + + /** + * Encodes a byte array into Base64 notation. + *

+ * Example options: + * + *

+    *   GZIP: gzip-compresses object before encoding it.
+    *   DO_BREAK_LINES: break lines at 76 characters
+    *     Note: Technically, this makes your encoding non-compliant.
+    * 
+ *

+ * Example: encodeBytes( myData, Base64.GZIP ) or + *

+ * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) + * + * + *

+ * As of v 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it + * just returned a null value, but in retrospect that's a pretty poor way to handle it. + *

+ * + * + * @param source The data to convert + * @param options Specified options + * @return The Base64-encoded data as a String + * @see Base64#GZIP + * @see Base64#DO_BREAK_LINES + * @throws java.io.IOException if there is an error + * @throws NullPointerException if source array is null + * @since 2.0 + */ + public static String encodeBytes(byte[] source, int options) throws java.io.IOException { + + return encodeBytes(source, 0, source.length, options); + } // end encodeBytes + + /** + * Encodes a byte array into Base64 notation. Does not GZip-compress data. + * + *

+ * As of v 2.3, if there is an error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned a null + * value, but in retrospect that's a pretty poor way to handle it. + *

+ * + * + * @param source The data to convert + * @param off Offset in array where conversion should begin + * @param len Length of data to convert + * @return The Base64-encoded data as a String + * @throws NullPointerException if source array is null + * @throws IllegalArgumentException if source array, offset, or length are invalid + * @since 1.4 + */ + public static String encodeBytes(byte[] source, int off, int len) { + + // Since we're not going to have the GZIP encoding turned on, + // we're not going to have an java.io.IOException thrown, so + // we should not force the user to have to catch it. + String encoded = null; + try { + encoded = encodeBytes(source, off, len, NO_OPTIONS); + } catch (java.io.IOException ex) { + assert false : ex.getMessage(); + } // end catch + assert encoded != null; + return encoded; + } // end encodeBytes + + /** + * Encodes a byte array into Base64 notation. + *

+ * Example options: + * + *

+    *   GZIP: gzip-compresses object before encoding it.
+    *   DO_BREAK_LINES: break lines at 76 characters
+    *     Note: Technically, this makes your encoding non-compliant.
+    * 
+ *

+ * Example: encodeBytes( myData, Base64.GZIP ) or + *

+ * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES ) + * + * + *

+ * As of v 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it + * just returned a null value, but in retrospect that's a pretty poor way to handle it. + *

+ * + * + * @param source The data to convert + * @param off Offset in array where conversion should begin + * @param len Length of data to convert + * @param options Specified options + * @return The Base64-encoded data as a String + * @see Base64#GZIP + * @see Base64#DO_BREAK_LINES + * @throws java.io.IOException if there is an error + * @throws NullPointerException if source array is null + * @throws IllegalArgumentException if source array, offset, or length are invalid + * @since 2.0 + */ + public static String encodeBytes(byte[] source, int off, int len, int options) throws java.io.IOException { + + byte[] encoded = encodeBytesToBytes(source, off, len, options); + + // Return value according to relevant encoding. + try { + return new String(encoded, PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uue) { + return new String(encoded); + } // end catch + + } // end encodeBytes + + /** + * Similar to {@link #encodeBytes(byte[])} but returns a byte array instead of instantiating a String. This is more efficient if you're working with I/O + * streams and have large data sets to encode. + * + * + * @param source The data to convert + * @return The Base64-encoded data as a byte[] (of ASCII characters) + * @throws NullPointerException if source array is null + * @since 2.3.1 + */ + public static byte[] encodeBytesToBytes(byte[] source) { + + byte[] encoded = null; + try { + encoded = encodeBytesToBytes(source, 0, source.length, Base64.NO_OPTIONS); + } catch (java.io.IOException ex) { + assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); + } + return encoded; + } + + /** + * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte array instead of instantiating a String. This is more efficient if you're + * working with I/O streams and have large data sets to encode. + * + * + * @param source The data to convert + * @param off Offset in array where conversion should begin + * @param len Length of data to convert + * @param options Specified options + * @return The Base64-encoded data as a String + * @see Base64#GZIP + * @see Base64#DO_BREAK_LINES + * @throws java.io.IOException if there is an error + * @throws NullPointerException if source array is null + * @throws IllegalArgumentException if source array, offset, or length are invalid + * @since 2.3.1 + */ + public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options) throws java.io.IOException { + + if (source == null) { + throw new NullPointerException("Cannot serialize a null array."); + } // end if: null + + if (off < 0) { + throw new IllegalArgumentException("Cannot have negative offset: " + off); + } // end if: off < 0 + + if (len < 0) { + throw new IllegalArgumentException("Cannot have length offset: " + len); + } // end if: len < 0 + + if (off + len > source.length) { + throw new IllegalArgumentException( + String.format("Cannot have offset of %d and length of %d with array of length %d", off, len, source.length)); + } // end if: off < 0 + + // Compress? + if ((options & GZIP) != 0) { + java.io.ByteArrayOutputStream baos = null; + java.util.zip.GZIPOutputStream gzos = null; + Base64.OutputStream b64os = null; + + try { + // GZip -> Base64 -> ByteArray + baos = new java.io.ByteArrayOutputStream(); + b64os = new Base64.OutputStream(baos, ENCODE | options); + gzos = new java.util.zip.GZIPOutputStream(b64os); + + gzos.write(source, off, len); + gzos.close(); + } // end try + catch (java.io.IOException e) { + // Catch it and then throw it immediately so that + // the finally{} block is called for cleanup. + throw e; + } // end catch + finally { + try { + gzos.close(); + } catch (Exception e) {} + try { + b64os.close(); + } catch (Exception e) {} + try { + baos.close(); + } catch (Exception e) {} + } // end finally + + return baos.toByteArray(); + } // end if: compress + + // Else, don't compress. Better not to use streams at all then. + else { + boolean breakLines = (options & DO_BREAK_LINES) != 0; + + //int len43 = len * 4 / 3; + //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines + // Try to determine more precisely how big the array needs to be. + // If we get it right, we don't have to do an array copy, and + // we save a bunch of memory. + int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding + if (breakLines) { + encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters + } + byte[] outBuff = new byte[encLen]; + + int d = 0; + int e = 0; + int len2 = len - 2; + int lineLength = 0; + for (; d < len2; d += 3, e += 4) { + encode3to4(source, d + off, 3, outBuff, e, options); + + lineLength += 4; + if (breakLines && lineLength >= MAX_LINE_LENGTH) { + outBuff[e + 4] = NEW_LINE; + e++; + lineLength = 0; + } // end if: end of line + } // en dfor: each piece of array + + if (d < len) { + encode3to4(source, d + off, len - d, outBuff, e, options); + e += 4; + } // end if: some padding needed + + // Only resize array if we didn't guess it right. + if (e <= outBuff.length - 1) { + // If breaking lines and the last byte falls right at + // the line length (76 bytes per line), there will be + // one extra byte, and the array will need to be resized. + // Not too bad of an estimate on array size, I'd say. + byte[] finalOut = new byte[e]; + System.arraycopy(outBuff, 0, finalOut, 0, e); + //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); + return finalOut; + } else { + //System.err.println("No need to resize array."); + return outBuff; + } + + } // end else: don't compress + + } // end encodeBytesToBytes + + /* ******** D E C O D I N G M E T H O D S ******** */ + + /** + * Decodes four bytes from array source and writes the resulting bytes (up to three of them) to destination. The source and + * destination arrays can be manipulated anywhere along their length by specifying srcOffset and destOffset. This method does not + * check to make sure your arrays are large enough to accomodate srcOffset + 4 for the source array or destOffset + 3 for + * the destination array. This method returns the actual number of bytes that were converted from the Base64 encoding. + *

+ * This is the lowest level of the decoding methods with all possible parameters. + *

+ * + * + * @param source the array to convert + * @param srcOffset the index where conversion begins + * @param destination the array to hold the conversion + * @param destOffset the index where output will be put + * @param options alphabet type is pulled from this (standard, url-safe, ordered) + * @return the number of decoded bytes converted + * @throws NullPointerException if source or destination arrays are null + * @throws IllegalArgumentException if srcOffset or destOffset are invalid or there is not enough room in the array. + * @since 1.3 + */ + private static int decode4to3( + byte[] source, int srcOffset, + byte[] destination, int destOffset, int options) { + + // Lots of error checking and exception throwing + if (source == null) { + throw new NullPointerException("Source array was null."); + } // end if + if (destination == null) { + throw new NullPointerException("Destination array was null."); + } // end if + if (srcOffset < 0 || srcOffset + 3 >= source.length) { + throw new IllegalArgumentException(String.format( + "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset)); + } // end if + if (destOffset < 0 || destOffset + 2 >= destination.length) { + throw new IllegalArgumentException(String.format( + "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset)); + } // end if + + byte[] DECODABET = getDecodabet(options); + + // Example: Dk== + if (source[srcOffset + 2] == EQUALS_SIGN) { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12); + + destination[destOffset] = (byte) (outBuff >>> 16); + return 1; + } + + // Example: DkL= + else if (source[srcOffset + 3] == EQUALS_SIGN) { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6); + + destination[destOffset] = (byte) (outBuff >>> 16); + destination[destOffset + 1] = (byte) (outBuff >>> 8); + return 2; + } + + // Example: DkLE + else { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) + // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); + int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) + | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12) + | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) + | ((DECODABET[source[srcOffset + 3]] & 0xFF)); + + destination[destOffset] = (byte) (outBuff >> 16); + destination[destOffset + 1] = (byte) (outBuff >> 8); + destination[destOffset + 2] = (byte) (outBuff); + + return 3; + } + } // end decodeToBytes + + /** + * Low-level access to decoding ASCII characters in the form of a byte array. Ignores GUNZIP option, if it's set. This is not generally a + * recommended method, although it is used internally as part of the decoding process. Special case: if len = 0, an empty array is returned. Still, if you + * need more speed and reduced memory footprint (and aren't gzipping), consider this method. + * + * @param source The Base64 encoded data + * @return decoded data + * @since 2.3.1 + */ + public static byte[] decode(byte[] source) + throws java.io.IOException { + + byte[] decoded = null; + // try { + decoded = decode(source, 0, source.length, Base64.NO_OPTIONS); + // } catch( java.io.IOException ex ) { + // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); + // } + return decoded; + } + + /** + * Low-level access to decoding ASCII characters in the form of a byte array. Ignores GUNZIP option, if it's set. This is not generally a + * recommended method, although it is used internally as part of the decoding process. Special case: if len = 0, an empty array is returned. Still, if you + * need more speed and reduced memory footprint (and aren't gzipping), consider this method. + * + * @param source The Base64 encoded data + * @param off The offset of where to begin decoding + * @param len The length of characters to decode + * @param options Can specify options such as alphabet type to use + * @return decoded data + * @throws java.io.IOException If bogus characters exist in source data + * @since 1.3 + */ + public static byte[] decode(byte[] source, int off, int len, int options) + throws java.io.IOException { + + // Lots of error checking and exception throwing + if (source == null) { + throw new NullPointerException("Cannot decode null source array."); + } // end if + if (off < 0 || off + len > source.length) { + throw new IllegalArgumentException(String.format( + "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len)); + } // end if + + if (len == 0) { + return new byte[0]; + } else if (len < 4) { + throw new IllegalArgumentException( + "Base64-encoded string must have at least four characters, but length specified was " + len); + } // end if + + byte[] DECODABET = getDecodabet(options); + + int len34 = len * 3 / 4; // Estimate on array size + byte[] outBuff = new byte[len34]; // Upper limit on size of output + int outBuffPosn = 0; // Keep track of where we're writing + + byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space + int b4Posn = 0; // Keep track of four byte input buffer + int i = 0; // Source array counter + byte sbiDecode = 0; // Special value from DECODABET + + for (i = off; i < off + len; i++) { // Loop through source + + sbiDecode = DECODABET[source[i] & 0xFF]; + + // White space, Equals sign, or legit Base64 character + // Note the values such as -5 and -9 in the + // DECODABETs at the top of the file. + if (sbiDecode >= WHITE_SPACE_ENC) { + if (sbiDecode >= EQUALS_SIGN_ENC) { + b4[b4Posn++] = source[i]; // Save non-whitespace + if (b4Posn > 3) { // Time to decode? + outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options); + b4Posn = 0; + + // If that was the equals sign, break out of 'for' loop + if (source[i] == EQUALS_SIGN) { + break; + } // end if: equals sign + } // end if: quartet built + } // end if: equals sign or better + } // end if: white space, equals sign or better + else { + // There's a bad input character in the Base64 stream. + throw new java.io.IOException(String.format( + "Bad Base64 input character decimal %d in array position %d", (source[i]) & 0xFF, i)); + } // end else: + } // each input character + + byte[] out = new byte[outBuffPosn]; + System.arraycopy(outBuff, 0, out, 0, outBuffPosn); + return out; + } // end decode + + /** + * Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it. + * + * @param s the string to decode + * @return the decoded data + * @throws java.io.IOException If there is a problem + * @since 1.4 + */ + public static byte[] decode(String s) throws java.io.IOException { + + return decode(s, NO_OPTIONS); + } + + /** + * Decodes data from Base64 notation, automatically detecting gzip-compressed data and decompressing it. + * + * @param s the string to decode + * @param options encode options such as URL_SAFE + * @return the decoded data + * @throws java.io.IOException if there is an error + * @throws NullPointerException if s is null + * @since 1.4 + */ + public static byte[] decode(String s, int options) throws java.io.IOException { + + if (s == null) { + throw new NullPointerException("Input string was null."); + } // end if + + byte[] bytes; + try { + bytes = s.getBytes(PREFERRED_ENCODING); + } // end try + catch (java.io.UnsupportedEncodingException uee) { + bytes = s.getBytes(); + } // end catch + // + + // Decode + bytes = decode(bytes, 0, bytes.length, options); + + // Check to see if it's gzip-compressed + // GZIP Magic Two-Byte Number: 0x8b1f (35615) + boolean dontGunzip = (options & DONT_GUNZIP) != 0; + if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) { + + int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); + if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) { + java.io.ByteArrayInputStream bais = null; + java.util.zip.GZIPInputStream gzis = null; + java.io.ByteArrayOutputStream baos = null; + byte[] buffer = new byte[2048]; + int length = 0; + + try { + baos = new java.io.ByteArrayOutputStream(); + bais = new java.io.ByteArrayInputStream(bytes); + gzis = new java.util.zip.GZIPInputStream(bais); + + while ((length = gzis.read(buffer)) >= 0) { + baos.write(buffer, 0, length); + } // end while: reading input + + // No error? Get new bytes. + bytes = baos.toByteArray(); + + } // end try + catch (java.io.IOException e) { + logger.error(e.getMessage(), e); + // Just return originally-decoded bytes + } // end catch + finally { + try { + baos.close(); + } catch (Exception e) {} + try { + gzis.close(); + } catch (Exception e) {} + try { + bais.close(); + } catch (Exception e) {} + } // end finally + + } // end if: gzipped + } // end if: bytes.length >= 2 + + return bytes; + } // end decode + + /** + * Attempts to decode Base64 data and deserialize a Java Object within. Returns null if there was an error. + * + * @param encodedObject The Base64 data to decode + * @return The decoded and deserialized object + * @throws NullPointerException if encodedObject is null + * @throws java.io.IOException if there is a general error + * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by the JVM + * @since 1.5 + */ + public static Object decodeToObject(String encodedObject) + throws java.io.IOException, java.lang.ClassNotFoundException { + + return decodeToObject(encodedObject, NO_OPTIONS, null); + } + + /** + * Attempts to decode Base64 data and deserialize a Java Object within. Returns null if there was an error. If loader is not null, it will + * be the class loader used when deserializing. + * + * @param encodedObject The Base64 data to decode + * @param options Various parameters related to decoding + * @param loader Optional class loader to use in deserializing classes. + * @return The decoded and deserialized object + * @throws NullPointerException if encodedObject is null + * @throws java.io.IOException if there is a general error + * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by the JVM + * @since 2.3.4 + */ + public static Object decodeToObject( + String encodedObject, int options, final ClassLoader loader) + throws java.io.IOException, java.lang.ClassNotFoundException { + + // Decode and gunzip if necessary + byte[] objBytes = decode(encodedObject, options); + + java.io.ByteArrayInputStream bais = null; + java.io.ObjectInputStream ois = null; + Object obj = null; + + try { + bais = new java.io.ByteArrayInputStream(objBytes); + + // If no custom class loader is provided, use Java's builtin OIS. + if (loader == null) { + ois = new java.io.ObjectInputStream(bais); + } // end if: no loader provided + + // Else make a customized object input stream that uses + // the provided class loader. + else { + ois = new java.io.ObjectInputStream(bais) { + + @Override + public Class resolveClass(java.io.ObjectStreamClass streamClass) + throws java.io.IOException, ClassNotFoundException { + + Class c = Class.forName(streamClass.getName(), false, loader); + if (c == null) { + return super.resolveClass(streamClass); + } else { + return c; // Class loader knows of this class. + } // end else: not null + } // end resolveClass + }; // end ois + } // end else: no custom class loader + + obj = ois.readObject(); + } // end try + catch (java.io.IOException e) { + throw e; // Catch and throw in order to execute finally{} + } // end catch + catch (java.lang.ClassNotFoundException e) { + throw e; // Catch and throw in order to execute finally{} + } // end catch + finally { + try { + bais.close(); + } catch (Exception e) {} + try { + ois.close(); + } catch (Exception e) {} + } // end finally + + return obj; + } // end decodeObject + + /** + * Convenience method for encoding data to a file. + * + *

+ * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, + * but in retrospect that's a pretty poor way to handle it. + *

+ * + * @param dataToEncode byte array of data to encode in base64 form + * @param filename Filename for saving encoded data + * @throws java.io.IOException if there is an error + * @throws NullPointerException if dataToEncode is null + * @since 2.1 + */ + public static void encodeToFile(byte[] dataToEncode, String filename) + throws java.io.IOException { + + if (dataToEncode == null) { + throw new NullPointerException("Data to encode was null."); + } // end iff + + Base64.OutputStream bos = null; + try { + bos = new Base64.OutputStream( + new java.io.FileOutputStream(filename), Base64.ENCODE); + bos.write(dataToEncode); + } // end try + catch (java.io.IOException e) { + throw e; // Catch and throw to execute finally{} block + } // end catch: java.io.IOException + finally { + try { + bos.close(); + } catch (Exception e) {} + } // end finally + + } // end encodeToFile + + /** + * Convenience method for decoding data to a file. + * + *

+ * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, + * but in retrospect that's a pretty poor way to handle it. + *

+ * + * @param dataToDecode Base64-encoded data as a string + * @param filename Filename for saving decoded data + * @throws java.io.IOException if there is an error + * @since 2.1 + */ + public static void decodeToFile(String dataToDecode, String filename) + throws java.io.IOException { + + Base64.OutputStream bos = null; + try { + bos = new Base64.OutputStream( + new java.io.FileOutputStream(filename), Base64.DECODE); + bos.write(dataToDecode.getBytes(PREFERRED_ENCODING)); + } // end try + catch (java.io.IOException e) { + throw e; // Catch and throw to execute finally{} block + } // end catch: java.io.IOException + finally { + try { + bos.close(); + } catch (Exception e) {} + } // end finally + + } // end decodeToFile + + /** + * Convenience method for reading a base64-encoded file and decoding it. + * + *

+ * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, + * but in retrospect that's a pretty poor way to handle it. + *

+ * + * @param filename Filename for reading encoded data + * @return decoded byte array + * @throws java.io.IOException if there is an error + * @since 2.1 + */ + public static byte[] decodeFromFile(String filename) + throws java.io.IOException { + + byte[] decodedData = null; + Base64.InputStream bis = null; + try { + // Set up some useful variables + java.io.File file = new java.io.File(filename); + byte[] buffer = null; + int length = 0; + int numBytes = 0; + + // Check for size of file + if (file.length() > Integer.MAX_VALUE) { + throw new java.io.IOException("File is too big for this convenience method (" + file.length() + " bytes)."); + } // end if: file too big for int index + buffer = new byte[(int) file.length()]; + + // Open a stream + bis = new Base64.InputStream( + new java.io.BufferedInputStream( + new java.io.FileInputStream(file)), Base64.DECODE); + + // Read until done + while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { + length += numBytes; + } // end while + + // Save in a variable to return + decodedData = new byte[length]; + System.arraycopy(buffer, 0, decodedData, 0, length); + + } // end try + catch (java.io.IOException e) { + throw e; // Catch and release to execute finally{} + } // end catch: java.io.IOException + finally { + try { + bis.close(); + } catch (Exception e) {} + } // end finally + + return decodedData; + } // end decodeFromFile + + /** + * Convenience method for reading a binary file and base64-encoding it. + * + *

+ * As of v 2.3, if there is a error, the method will throw an java.io.IOException. This is new to v2.3! In earlier versions, it just returned false, + * but in retrospect that's a pretty poor way to handle it. + *

+ * + * @param filename Filename for reading binary data + * @return base64-encoded string + * @throws java.io.IOException if there is an error + * @since 2.1 + */ + public static String encodeFromFile(String filename) + throws java.io.IOException { + + String encodedData = null; + Base64.InputStream bis = null; + try { + // Set up some useful variables + java.io.File file = new java.io.File(filename); + byte[] buffer = new byte[Math.max((int) (file.length() * 1.4 + 1), 40)]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) + int length = 0; + int numBytes = 0; + + // Open a stream + bis = new Base64.InputStream( + new java.io.BufferedInputStream( + new java.io.FileInputStream(file)), Base64.ENCODE); + + // Read until done + while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { + length += numBytes; + } // end while + + // Save in a variable to return + encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING); + + } // end try + catch (java.io.IOException e) { + throw e; // Catch and release to execute finally{} + } // end catch: java.io.IOException + finally { + try { + bis.close(); + } catch (Exception e) {} + } // end finally + + return encodedData; + } // end encodeFromFile + + /** + * Reads infile and encodes it to outfile. + * + * @param infile Input file + * @param outfile Output file + * @throws java.io.IOException if there is an error + * @since 2.2 + */ + public static void encodeFileToFile(String infile, String outfile) + throws java.io.IOException { + + String encoded = Base64.encodeFromFile(infile); + java.io.OutputStream out = null; + try { + out = new java.io.BufferedOutputStream( + new java.io.FileOutputStream(outfile)); + out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output. + } // end try + catch (java.io.IOException e) { + throw e; // Catch and release to execute finally{} + } // end catch + finally { + try { + out.close(); + } catch (Exception ex) {} + } // end finally + } // end encodeFileToFile + + /** + * Reads infile and decodes it to outfile. + * + * @param infile Input file + * @param outfile Output file + * @throws java.io.IOException if there is an error + * @since 2.2 + */ + public static void decodeFileToFile(String infile, String outfile) + throws java.io.IOException { + + byte[] decoded = Base64.decodeFromFile(infile); + java.io.OutputStream out = null; + try { + out = new java.io.BufferedOutputStream( + new java.io.FileOutputStream(outfile)); + out.write(decoded); + } // end try + catch (java.io.IOException e) { + throw e; // Catch and release to execute finally{} + } // end catch + finally { + try { + out.close(); + } catch (Exception ex) {} + } // end finally + } // end decodeFileToFile + + /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ + + /** + * A {@link Base64.InputStream} will read data from another java.io.InputStream, given in the constructor, and encode/decode to/from Base64 + * notation on the fly. + * + * @see Base64 + * @since 1.3 + */ + public static class InputStream extends java.io.FilterInputStream { + + private boolean encode; // Encoding or decoding + private int position; // Current position in the buffer + private byte[] buffer; // Small buffer holding converted data + private int bufferLength; // Length of buffer (3 or 4) + private int numSigBytes; // Number of meaningful bytes in the buffer + private int lineLength; + private boolean breakLines; // Break lines at less than 80 characters + private int options; // Record options used to create the stream. + private byte[] decodabet; // Local copies to avoid extra method calls + + /** + * Constructs a {@link Base64.InputStream} in DECODE mode. + * + * @param in the java.io.InputStream from which to read data. + * @since 1.3 + */ + public InputStream(java.io.InputStream in) { + + this(in, DECODE); + } // end constructor + + /** + * Constructs a {@link Base64.InputStream} in either ENCODE or DECODE mode. + *

+ * Valid options: + * + *

+       *   ENCODE or DECODE: Encode or Decode as data is read.
+       *   DO_BREAK_LINES: break lines at 76 characters
+       *     (only meaningful when encoding)
+       * 
+ *

+ * Example: new Base64.InputStream( in, Base64.DECODE ) + * + * + * @param in the java.io.InputStream from which to read data. + * @param options Specified options + * @see Base64#ENCODE + * @see Base64#DECODE + * @see Base64#DO_BREAK_LINES + * @since 2.0 + */ + public InputStream(java.io.InputStream in, int options) { + + super(in); + this.options = options; // Record for later + this.breakLines = (options & DO_BREAK_LINES) > 0; + this.encode = (options & ENCODE) > 0; + this.bufferLength = encode ? 4 : 3; + this.buffer = new byte[bufferLength]; + this.position = -1; + this.lineLength = 0; + this.decodabet = getDecodabet(options); + } // end constructor + + /** + * Reads enough of the input stream to convert to/from Base64 and returns the next byte. + * + * @return next byte + * @since 1.3 + */ + @Override + public int read() throws java.io.IOException { + + // Do we need to get data? + if (position < 0) { + if (encode) { + byte[] b3 = new byte[3]; + int numBinaryBytes = 0; + for (int i = 0; i < 3; i++) { + int b = in.read(); + + // If end of stream, b is -1. + if (b >= 0) { + b3[i] = (byte) b; + numBinaryBytes++; + } else { + break; // out of for loop + } // end else: end of stream + + } // end for: each needed input byte + + if (numBinaryBytes > 0) { + encode3to4(b3, 0, numBinaryBytes, buffer, 0, options); + position = 0; + numSigBytes = 4; + } // end if: got data + else { + return -1; // Must be end of stream + } // end else + } // end if: encoding + + // Else decoding + else { + byte[] b4 = new byte[4]; + int i = 0; + for (i = 0; i < 4; i++) { + // Read four "meaningful" bytes: + int b = 0; + do { + b = in.read(); + } while (b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC); + + if (b < 0) { + break; // Reads a -1 if end of stream + } // end if: end of stream + + b4[i] = (byte) b; + } // end for: each needed input byte + + if (i == 4) { + numSigBytes = decode4to3(b4, 0, buffer, 0, options); + position = 0; + } // end if: got four characters + else if (i == 0) { + return -1; + } // end else if: also padded correctly + else { + // Must have broken out from above. + throw new java.io.IOException("Improperly padded Base64 input."); + } // end + + } // end else: decode + } // end else: get data + + // Got data? + if (position >= 0) { + // End of relevant data? + if ( /* !encode && */position >= numSigBytes) { + return -1; + } // end if: got data + + if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) { + lineLength = 0; + return '\n'; + } // end if + else { + lineLength++; // This isn't important when decoding + // but throwing an extra "if" seems + // just as wasteful. + + int b = buffer[position++]; + + if (position >= bufferLength) { + position = -1; + } // end if: end + + return b & 0xFF; // This is how you "cast" a byte that's + // intended to be unsigned. + } // end else + } // end if: position >= 0 + + // Else error + else { + throw new java.io.IOException("Error in Base64 code reading stream."); + } // end else + } // end read + + /** + * Calls {@link #read()} repeatedly until the end of stream is reached or len bytes are read. Returns number of bytes read into array or -1 + * if end of stream is encountered. + * + * @param dest array to hold values + * @param off offset for array + * @param len max number of bytes to read into array + * @return bytes read into array or -1 if end of stream is encountered. + * @since 1.3 + */ + @Override + public int read(byte[] dest, int off, int len) + throws java.io.IOException { + + int i; + int b; + for (i = 0; i < len; i++) { + b = read(); + + if (b >= 0) { + dest[off + i] = (byte) b; + } else if (i == 0) { + return -1; + } else { + break; // Out of 'for' loop + } // Out of 'for' loop + } // end for: each byte read + return i; + } // end read + + } // end inner class InputStream + + /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ + + /** + * A {@link Base64.OutputStream} will write data to another java.io.OutputStream, given in the constructor, and encode/decode to/from Base64 + * notation on the fly. + * + * @see Base64 + * @since 1.3 + */ + public static class OutputStream extends java.io.FilterOutputStream { + + private boolean encode; + private int position; + private byte[] buffer; + private int bufferLength; + private int lineLength; + private boolean breakLines; + private byte[] b4; // Scratch used in a few places + private boolean suspendEncoding; + private int options; // Record for later + private byte[] decodabet; // Local copies to avoid extra method calls + + /** + * Constructs a {@link Base64.OutputStream} in ENCODE mode. + * + * @param out the java.io.OutputStream to which data will be written. + * @since 1.3 + */ + public OutputStream(java.io.OutputStream out) { + + this(out, ENCODE); + } // end constructor + + /** + * Constructs a {@link Base64.OutputStream} in either ENCODE or DECODE mode. + *

+ * Valid options: + * + *

+       *   ENCODE or DECODE: Encode or Decode as data is read.
+       *   DO_BREAK_LINES: don't break lines at 76 characters
+       *     (only meaningful when encoding)
+       * 
+ *

+ * Example: new Base64.OutputStream( out, Base64.ENCODE ) + * + * @param out the java.io.OutputStream to which data will be written. + * @param options Specified options. + * @see Base64#ENCODE + * @see Base64#DECODE + * @see Base64#DO_BREAK_LINES + * @since 1.3 + */ + public OutputStream(java.io.OutputStream out, int options) { + + super(out); + this.breakLines = (options & DO_BREAK_LINES) != 0; + this.encode = (options & ENCODE) != 0; + this.bufferLength = encode ? 3 : 4; + this.buffer = new byte[bufferLength]; + this.position = 0; + this.lineLength = 0; + this.suspendEncoding = false; + this.b4 = new byte[4]; + this.options = options; + this.decodabet = getDecodabet(options); + } // end constructor + + /** + * Writes the byte to the output stream after converting to/from Base64 notation. When encoding, bytes are buffered three at a time before the output + * stream actually gets a write() call. When decoding, bytes are buffered four at a time. + * + * @param theByte the byte to write + * @since 1.3 + */ + @Override + public void write(int theByte) + throws java.io.IOException { + + // Encoding suspended? + if (suspendEncoding) { + this.out.write(theByte); + return; + } // end if: supsended + + // Encode? + if (encode) { + buffer[position++] = (byte) theByte; + if (position >= bufferLength) { // Enough to encode. + + this.out.write(encode3to4(b4, buffer, bufferLength, options)); + + lineLength += 4; + if (breakLines && lineLength >= MAX_LINE_LENGTH) { + this.out.write(NEW_LINE); + lineLength = 0; + } // end if: end of line + + position = 0; + } // end if: enough to output + } // end if: encoding + + // Else, Decoding + else { + // Meaningful Base64 character? + if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) { + buffer[position++] = (byte) theByte; + if (position >= bufferLength) { // Enough to output. + + int len = Base64.decode4to3(buffer, 0, b4, 0, options); + out.write(b4, 0, len); + position = 0; + } // end if: enough to output + } // end if: meaningful base64 character + else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) { + throw new java.io.IOException("Invalid character in Base64 data."); + } // end else: not white space either + } // end else: decoding + } // end write + + /** + * Calls {@link #write(int)} repeatedly until len bytes are written. + * + * @param theBytes array from which to read bytes + * @param off offset for array + * @param len max number of bytes to read into array + * @since 1.3 + */ + @Override + public void write(byte[] theBytes, int off, int len) + throws java.io.IOException { + + // Encoding suspended? + if (suspendEncoding) { + this.out.write(theBytes, off, len); + return; + } // end if: supsended + + for (int i = 0; i < len; i++) { + write(theBytes[off + i]); + } // end for: each byte written + + } // end write + + /** + * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer without closing the stream. + * + * @throws java.io.IOException if there's an error. + */ + public void flushBase64() throws java.io.IOException { + + if (position > 0) { + if (encode) { + out.write(encode3to4(b4, buffer, position, options)); + position = 0; + } // end if: encoding + else { + throw new java.io.IOException("Base64 input not properly padded."); + } // end else: decoding + } // end if: buffer partially full + + } // end flush + + /** + * Flushes and closes (I think, in the superclass) the stream. + * + * @since 1.3 + */ + @Override + public void close() throws java.io.IOException { + + // 1. Ensure that pending characters are written + flushBase64(); + + // 2. Actually close the stream + // Base class both flushes and closes. + super.close(); + + buffer = null; + out = null; + } // end close + + /** + * Suspends encoding of the stream. May be helpful if you need to embed a piece of base64-encoded data in a stream. + * + * @throws java.io.IOException if there's an error flushing + * @since 1.5.1 + */ + public void suspendEncoding() throws java.io.IOException { + + flushBase64(); + this.suspendEncoding = true; + } // end suspendEncoding + + /** + * Resumes encoding of the stream. May be helpful if you need to embed a piece of base64-encoded data in a stream. + * + * @since 1.5.1 + */ + public void resumeEncoding() { + + this.suspendEncoding = false; + } // end resumeEncoding + + } // end inner class OutputStream } // end class Base64 diff --git a/eagledns/src/main/java/se/unlogic/standardutils/crypto/EncryptionUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/crypto/EncryptionUtils.java index 85029504dee..e2a31a023cc 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/crypto/EncryptionUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/crypto/EncryptionUtils.java @@ -17,111 +17,111 @@ public class EncryptionUtils { - public static String hash(String string, String algorithm) throws UnsupportedEncodingException{ + public static String hash(String string, String algorithm) throws UnsupportedEncodingException{ - return hash(string, algorithm, Charset.defaultCharset().toString()); - } + return hash(string, algorithm, Charset.defaultCharset().toString()); + } - public static String hash(String string, String algorithm, String encoding) throws UnsupportedEncodingException{ + public static String hash(String string, String algorithm, String encoding) throws UnsupportedEncodingException{ - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); - digest.update(string.getBytes(encoding)); + digest.update(string.getBytes(encoding)); - byte[] encodedPassword = digest.digest(); + byte[] encodedPassword = digest.digest(); - return new BigInteger(1, encodedPassword).toString(16); + return new BigInteger(1, encodedPassword).toString(16); - //TODO fix if hash starts with zeroes! + //TODO fix if hash starts with zeroes! - } catch (NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - public static String hash(File file, String algorithm) throws IOException{ + public static String hash(File file, String algorithm) throws IOException{ - return hash(file, algorithm, null); - } + return hash(file, algorithm, null); + } - public static String hash(File file, String algorithm, ProgressMeter progressMeter) throws IOException{ + public static String hash(File file, String algorithm, ProgressMeter progressMeter) throws IOException{ - FileInputStream fileInputStream = null; + FileInputStream fileInputStream = null; - try { - MessageDigest digest = MessageDigest.getInstance(algorithm); - fileInputStream = new FileInputStream(file); + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + fileInputStream = new FileInputStream(file); - DigestInputStream digestInputStream = new DigestInputStream(fileInputStream, digest); + DigestInputStream digestInputStream = new DigestInputStream(fileInputStream, digest); - if(progressMeter != null){ + if(progressMeter != null){ - progressMeter.setStartTime(); - progressMeter.setFinish(file.length()); - } + progressMeter.setStartTime(); + progressMeter.setFinish(file.length()); + } - byte[] buffer = new byte[8192]; + byte[] buffer = new byte[8192]; - int bytesRead = 1; + int bytesRead = 1; - if(progressMeter != null){ + if(progressMeter != null){ - while ((bytesRead = digestInputStream.read(buffer)) != -1){ + while ((bytesRead = digestInputStream.read(buffer)) != -1){ - progressMeter.incrementCurrentPosition(bytesRead); - } + progressMeter.incrementCurrentPosition(bytesRead); + } - }else{ + }else{ - while ((bytesRead = digestInputStream.read(buffer)) != -1){} - } + while ((bytesRead = digestInputStream.read(buffer)) != -1){} + } - byte[] hash = digest.digest(); + byte[] hash = digest.digest(); - if(progressMeter != null){ + if(progressMeter != null){ - progressMeter.setEndTime(); - } + progressMeter.setEndTime(); + } - return new BigInteger(1, hash).toString(16); + return new BigInteger(1, hash).toString(16); - } catch (NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - }finally{ + }finally{ - StreamUtils.closeStream(fileInputStream); - } - } + StreamUtils.closeStream(fileInputStream); + } + } - public static String mysqlPasswordHash(String string) { + public static String mysqlPasswordHash(String string) { - try { - MessageDigest digest = MessageDigest.getInstance(HashAlgorithms.SHA1); + try { + MessageDigest digest = MessageDigest.getInstance(HashAlgorithms.SHA1); - digest.update(string.getBytes(StandardCharsets.UTF_8)); + digest.update(string.getBytes(StandardCharsets.UTF_8)); - byte[] encodedPassword = digest.digest(); + byte[] encodedPassword = digest.digest(); - digest.update(encodedPassword); + digest.update(encodedPassword); - encodedPassword = digest.digest(); + encodedPassword = digest.digest(); - String hash = new BigInteger(1, encodedPassword).toString(16).toUpperCase(); + String hash = new BigInteger(1, encodedPassword).toString(16).toUpperCase(); - while(hash.length() < 40){ + while(hash.length() < 40){ - hash = "0" + hash; - } + hash = "0" + hash; + } - return "*" + hash; + return "*" + hash; - } catch (NoSuchAlgorithmException e) { + } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/crypto/HashAlgorithms.java b/eagledns/src/main/java/se/unlogic/standardutils/crypto/HashAlgorithms.java index 0be9ef17a06..6df7d7fdaf9 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/crypto/HashAlgorithms.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/crypto/HashAlgorithms.java @@ -7,40 +7,40 @@ public class HashAlgorithms { - public static final String MD2 = "MD2"; - public static final String MD5 = "MD5"; - public static final String SHA1 = "SHA-1"; - public static final String SHA256 = "SHA-256"; - public static final String SHA384 = "SHA-384"; - public static final String SHA512 = "SHA-512"; - - private static final List ALGORITHMS; - - static{ - Field[] fields = HashAlgorithms.class.getFields(); - - ALGORITHMS = new ArrayList(fields.length); - - HashAlgorithms hashAlgorithms = new HashAlgorithms(); - - for(Field field : fields){ - - try { - ALGORITHMS.add((String) field.get(hashAlgorithms)); - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - } - } - } - - public static String[] getAlgorithms(){ - - return ALGORITHMS.toArray(new String[ALGORITHMS.size()]); - } + public static final String MD2 = "MD2"; + public static final String MD5 = "MD5"; + public static final String SHA1 = "SHA-1"; + public static final String SHA256 = "SHA-256"; + public static final String SHA384 = "SHA-384"; + public static final String SHA512 = "SHA-512"; + + private static final List ALGORITHMS; + + static{ + Field[] fields = HashAlgorithms.class.getFields(); + + ALGORITHMS = new ArrayList(fields.length); + + HashAlgorithms hashAlgorithms = new HashAlgorithms(); + + for(Field field : fields){ + + try { + ALGORITHMS.add((String) field.get(hashAlgorithms)); + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + } + + public static String[] getAlgorithms(){ + + return ALGORITHMS.toArray(new String[ALGORITHMS.size()]); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAO.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAO.java index 9f6e27e6686..0b0fd12d877 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAO.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAO.java @@ -52,2172 +52,2172 @@ public class AnnotatedDAO { - private static final OrderByComparator ORDER_BY_COMPARATOR = new OrderByComparator(); + private static final OrderByComparator ORDER_BY_COMPARATOR = new OrderByComparator(); - protected final AnnotatedResultSetPopulator populator; - protected final DataSource dataSource; - protected final Class beanClass; + protected final AnnotatedResultSetPopulator populator; + protected final DataSource dataSource; + protected final Class beanClass; - protected final List> queryParameterPopulators; - protected final List> beanStringPopulators; + protected final List> queryParameterPopulators; + protected final List> beanStringPopulators; - protected final ArrayList> simpleKeys = new ArrayList>(); - protected final ArrayList> simpleColumns = new ArrayList>(); - protected final HashMap> columnMap = new HashMap>(); + protected final ArrayList> simpleKeys = new ArrayList>(); + protected final ArrayList> simpleColumns = new ArrayList>(); + protected final HashMap> columnMap = new HashMap>(); - protected final ArrayList> columnKeyCollectors = new ArrayList>(); + protected final ArrayList> columnKeyCollectors = new ArrayList>(); - protected final HashMap> manyToOneRelations = new HashMap>(); - protected final HashMap> manyToOneRelationKeys = new HashMap>(); - protected final HashMap> oneToManyRelations = new HashMap>(); - protected final HashMap> manyToManyRelations = new HashMap>(); + protected final HashMap> manyToOneRelations = new HashMap>(); + protected final HashMap> manyToOneRelationKeys = new HashMap>(); + protected final HashMap> oneToManyRelations = new HashMap>(); + protected final HashMap> manyToManyRelations = new HashMap>(); - protected final TreeMap> columnOrderMap = new TreeMap>(ORDER_BY_COMPARATOR); + protected final TreeMap> columnOrderMap = new TreeMap>(ORDER_BY_COMPARATOR); - protected final ArrayList autoAddRelations = new ArrayList(); - protected final ArrayList autoGetRelations = new ArrayList(); - protected final ArrayList autoUpdateRelations = new ArrayList(); + protected final ArrayList autoAddRelations = new ArrayList(); + protected final ArrayList autoGetRelations = new ArrayList(); + protected final ArrayList autoUpdateRelations = new ArrayList(); - protected String tableName; + protected String tableName; - protected String insertSQL; - protected String updateSQL; - protected String deleteSQL; - protected String checkIfExistsSQL; - protected String deleteByFieldSQL; - protected String getSQL; - protected String defaultSortingCriteria; + protected String insertSQL; + protected String updateSQL; + protected String deleteSQL; + protected String checkIfExistsSQL; + protected String deleteByFieldSQL; + protected String getSQL; + protected String defaultSortingCriteria; - public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory) { + public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory) { - this(dataSource, beanClass, daoFactory, new AnnotatedResultSetPopulator(beanClass), null, null); - } + this(dataSource, beanClass, daoFactory, new AnnotatedResultSetPopulator(beanClass), null, null); + } - public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory, AnnotatedResultSetPopulator populator, QueryParameterPopulator... queryParameterPopulators) { + public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory, AnnotatedResultSetPopulator populator, QueryParameterPopulator... queryParameterPopulators) { - this(dataSource, beanClass, daoFactory, populator, Arrays.asList(queryParameterPopulators), null); - } + this(dataSource, beanClass, daoFactory, populator, Arrays.asList(queryParameterPopulators), null); + } - public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory, List> queryParameterPopulators, List> typePopulators) { + public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory, List> queryParameterPopulators, List> typePopulators) { - this(dataSource, beanClass, daoFactory, new AnnotatedResultSetPopulator(beanClass, typePopulators), queryParameterPopulators, typePopulators); - } + this(dataSource, beanClass, daoFactory, new AnnotatedResultSetPopulator(beanClass, typePopulators), queryParameterPopulators, typePopulators); + } - public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory, AnnotatedResultSetPopulator populator, - List> queryParameterPopulators, List> typePopulators) { + public AnnotatedDAO(DataSource dataSource, Class beanClass, AnnotatedDAOFactory daoFactory, AnnotatedResultSetPopulator populator, + List> queryParameterPopulators, List> typePopulators) { - super(); - this.populator = populator; - this.dataSource = dataSource; - this.beanClass = beanClass; + super(); + this.populator = populator; + this.dataSource = dataSource; + this.beanClass = beanClass; - if (queryParameterPopulators != null) { + if (queryParameterPopulators != null) { - this.queryParameterPopulators = new ArrayList>(queryParameterPopulators); + this.queryParameterPopulators = new ArrayList>(queryParameterPopulators); - } else { + } else { - this.queryParameterPopulators = null; - } + this.queryParameterPopulators = null; + } - if (typePopulators != null) { + if (typePopulators != null) { - this.beanStringPopulators = new ArrayList>(typePopulators); + this.beanStringPopulators = new ArrayList>(typePopulators); - } else { + } else { - this.beanStringPopulators = null; - } + this.beanStringPopulators = null; + } - Table table = beanClass.getAnnotation(Table.class); + Table table = beanClass.getAnnotation(Table.class); - if (table == null) { + if (table == null) { - throw new RuntimeException("No @Table annotation found in " + beanClass); - } else { - tableName = table.name(); - } + throw new RuntimeException("No @Table annotation found in " + beanClass); + } else { + tableName = table.name(); + } - this.tableName = table.name(); + this.tableName = table.name(); - List fields = ReflectionUtils.getFields(beanClass); + List fields = ReflectionUtils.getFields(beanClass); - int generatedKeyColumnIndex = 1; + int generatedKeyColumnIndex = 1; - for (Field field : fields) { + for (Field field : fields) { - DAOManaged daoManaged = field.getAnnotation(DAOManaged.class); - OrderBy orderBy = field.getAnnotation(OrderBy.class); + DAOManaged daoManaged = field.getAnnotation(DAOManaged.class); + OrderBy orderBy = field.getAnnotation(OrderBy.class); - if (daoManaged != null) { + if (daoManaged != null) { - ReflectionUtils.fixFieldAccess(field); + ReflectionUtils.fixFieldAccess(field); - if (field.isAnnotationPresent(OneToOne.class)) { + if (field.isAnnotationPresent(OneToOne.class)) { - this.checkAutoGeneration(daoManaged); + this.checkAutoGeneration(daoManaged); - // TODO Relation use this class pk, no extra field - // TODO check auto fields - throw new RuntimeException("OneToOne relations are not implemented yet!"); + // TODO Relation use this class pk, no extra field + // TODO check auto fields + throw new RuntimeException("OneToOne relations are not implemented yet!"); - } else if (field.isAnnotationPresent(OneToMany.class)) { + } else if (field.isAnnotationPresent(OneToMany.class)) { - OneToMany oneToMany = field.getAnnotation(OneToMany.class); + OneToMany oneToMany = field.getAnnotation(OneToMany.class); - this.checkOrderByAnnotation(field, orderBy); + this.checkOrderByAnnotation(field, orderBy); - if (field.getType() != List.class) { + if (field.getType() != List.class) { - throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass + " is of unsupported type " - + field.getType() + ". Fields annotated as @OneToMany have to be a genericly typed " + List.class, field, OneToMany.class, - beanClass); - } + throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass + " is of unsupported type " + + field.getType() + ". Fields annotated as @OneToMany have to be a genericly typed " + List.class, field, OneToMany.class, + beanClass); + } - if (ReflectionUtils.getGenericlyTypeCount(field) != 1) { + if (ReflectionUtils.getGenericlyTypeCount(field) != 1) { - throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass - + " is genericly typed. Fields annotated as @OneToMany have to be a genericly typed " + List.class, field, OneToMany.class, - beanClass); - } + throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass + + " is genericly typed. Fields annotated as @OneToMany have to be a genericly typed " + List.class, field, OneToMany.class, + beanClass); + } - // This is a bit ugly but still necessary until someone else - // comes up with something smarter... - Class remoteClass = (Class) ReflectionUtils.getGenericType(field); + // This is a bit ugly but still necessary until someone else + // comes up with something smarter... + Class remoteClass = (Class) ReflectionUtils.getGenericType(field); - SimplifiedRelation simplifiedRelation = field.getAnnotation(SimplifiedRelation.class); + SimplifiedRelation simplifiedRelation = field.getAnnotation(SimplifiedRelation.class); - if (simplifiedRelation != null) { + if (simplifiedRelation != null) { - this.oneToManyRelations.put(field, SimplifiedOneToManyRelation.getGenericInstance(beanClass, remoteClass, field, this, typePopulators, queryParameterPopulators)); + this.oneToManyRelations.put(field, SimplifiedOneToManyRelation.getGenericInstance(beanClass, remoteClass, field, this, typePopulators, queryParameterPopulators)); - } else { + } else { - // Use this class pks, no extra field - this.oneToManyRelations.put(field, DefaultOneToManyRelation.getGenericInstance(beanClass, remoteClass, field, daoFactory, daoManaged)); - } + // Use this class pks, no extra field + this.oneToManyRelations.put(field, DefaultOneToManyRelation.getGenericInstance(beanClass, remoteClass, field, daoFactory, daoManaged)); + } - if (oneToMany.autoAdd()) { - this.autoAddRelations.add(field); - } + if (oneToMany.autoAdd()) { + this.autoAddRelations.add(field); + } - if (oneToMany.autoUpdate()) { - this.autoUpdateRelations.add(field); - } + if (oneToMany.autoUpdate()) { + this.autoUpdateRelations.add(field); + } - if (oneToMany.autoGet()) { - this.autoGetRelations.add(field); - } + if (oneToMany.autoGet()) { + this.autoGetRelations.add(field); + } - } else if (field.isAnnotationPresent(ManyToOne.class)) { + } else if (field.isAnnotationPresent(ManyToOne.class)) { - this.checkAutoGeneration(daoManaged); + this.checkAutoGeneration(daoManaged); - ManyToOne manyToOne = field.getAnnotation(ManyToOne.class); + ManyToOne manyToOne = field.getAnnotation(ManyToOne.class); - List remoteClassFields = ReflectionUtils.getFields(field.getType()); + List remoteClassFields = ReflectionUtils.getFields(field.getType()); - Field matchingRemoteField = null; + Field matchingRemoteField = null; - if (remoteClassFields != null) { + if (remoteClassFields != null) { - for (Field remoteField : remoteClassFields) { + for (Field remoteField : remoteClassFields) { - if (remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(OneToMany.class) - && remoteField.getType() == List.class && ReflectionUtils.isGenericlyTyped(remoteField) - && ((Class) ReflectionUtils.getGenericType(remoteField) == this.beanClass)) { + if (remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(OneToMany.class) + && remoteField.getType() == List.class && ReflectionUtils.isGenericlyTyped(remoteField) + && ((Class) ReflectionUtils.getGenericType(remoteField) == this.beanClass)) { - matchingRemoteField = remoteField; + matchingRemoteField = remoteField; - break; - } - } - } + break; + } + } + } - if (matchingRemoteField == null) { + if (matchingRemoteField == null) { - throw new RuntimeException("No corresponding @OneToMany annotated field found in " + field.getType() - + " matching @ManyToOne relation of field " + field.getName() + " in " + beanClass + "!"); - } + throw new RuntimeException("No corresponding @OneToMany annotated field found in " + field.getType() + + " matching @ManyToOne relation of field " + field.getName() + " in " + beanClass + "!"); + } - Field remoteKeyField = null; + Field remoteKeyField = null; - if (!StringUtils.isEmpty(manyToOne.remoteKeyField())) { + if (!StringUtils.isEmpty(manyToOne.remoteKeyField())) { - remoteKeyField = ReflectionUtils.getField(field.getType(), manyToOne.remoteKeyField()); + remoteKeyField = ReflectionUtils.getField(field.getType(), manyToOne.remoteKeyField()); - //TODO Check if the remote key field is @DAOPopluate annotated - if (remoteKeyField == null) { + //TODO Check if the remote key field is @DAOPopluate annotated + if (remoteKeyField == null) { - throw new RuntimeException("Unable to find @Key annotated field " + manyToOne.remoteKeyField() + " in " + field.getType() + " specified for @ManyToOne annotated field " - + field.getName() + " in " + beanClass); - } + throw new RuntimeException("Unable to find @Key annotated field " + manyToOne.remoteKeyField() + " in " + field.getType() + " specified for @ManyToOne annotated field " + + field.getName() + " in " + beanClass); + } - } else { + } else { - for (Field remoteField : remoteClassFields) { + for (Field remoteField : remoteClassFields) { - if (remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(Key.class)) { + if (remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(Key.class)) { - if (remoteKeyField != null) { + if (remoteKeyField != null) { - throw new RuntimeException("Found multiple @Key annotated fields in " + field.getType() + ", therefore the remoteKeyField property needs to be specified for the @ManyToOne annotated field " - + field.getName() + " in " + beanClass); - } + throw new RuntimeException("Found multiple @Key annotated fields in " + field.getType() + ", therefore the remoteKeyField property needs to be specified for the @ManyToOne annotated field " + + field.getName() + " in " + beanClass); + } - remoteKeyField = remoteField; - } - } + remoteKeyField = remoteField; + } + } - if (remoteKeyField == null) { + if (remoteKeyField == null) { - throw new RuntimeException("Unable to find @Key annotated field in " + field.getType() + " while parsing @ManyToOne annotated field " - + field.getName() + " in " + beanClass); - } - } + throw new RuntimeException("Unable to find @Key annotated field in " + field.getType() + " while parsing @ManyToOne annotated field " + + field.getName() + " in " + beanClass); + } + } - DefaultManyToOneRelation relation = null; + DefaultManyToOneRelation relation = null; - if (field.isAnnotationPresent(Key.class)) { + if (field.isAnnotationPresent(Key.class)) { - relation = DefaultManyToOneRelation.getGenericInstance(beanClass, field.getType(), remoteKeyField.getType(), field, remoteKeyField, daoManaged, daoFactory); + relation = DefaultManyToOneRelation.getGenericInstance(beanClass, field.getType(), remoteKeyField.getType(), field, remoteKeyField, daoManaged, daoFactory); - manyToOneRelationKeys.put(field, relation); + manyToOneRelationKeys.put(field, relation); - } else { + } else { - relation = DefaultManyToOneRelation.getGenericInstance(beanClass, field.getType(), remoteKeyField.getType(), field, remoteKeyField, daoManaged, daoFactory); + relation = DefaultManyToOneRelation.getGenericInstance(beanClass, field.getType(), remoteKeyField.getType(), field, remoteKeyField, daoManaged, daoFactory); - this.manyToOneRelations.put(field, relation); - } + this.manyToOneRelations.put(field, relation); + } - this.columnMap.put(field, relation); + this.columnMap.put(field, relation); - if (orderBy != null) { - this.columnOrderMap.put(orderBy, relation); - } + if (orderBy != null) { + this.columnOrderMap.put(orderBy, relation); + } - if (manyToOne.autoAdd()) { - this.autoAddRelations.add(field); - } + if (manyToOne.autoAdd()) { + this.autoAddRelations.add(field); + } - if (manyToOne.autoUpdate()) { - this.autoUpdateRelations.add(field); - } + if (manyToOne.autoUpdate()) { + this.autoUpdateRelations.add(field); + } - if (manyToOne.autoGet()) { - this.autoGetRelations.add(field); - } + if (manyToOne.autoGet()) { + this.autoGetRelations.add(field); + } - } else if (field.isAnnotationPresent(ManyToMany.class)) { + } else if (field.isAnnotationPresent(ManyToMany.class)) { - this.checkAutoGeneration(daoManaged); + this.checkAutoGeneration(daoManaged); - this.checkOrderByAnnotation(field, orderBy); + this.checkOrderByAnnotation(field, orderBy); - if (field.getType() != List.class) { + if (field.getType() != List.class) { - throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass + " is of unsupported type " - + field.getType() + ". Fields annotated as @ManyToMany have to be a genericly typed " + List.class, field, ManyToMany.class, - beanClass); - } + throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass + " is of unsupported type " + + field.getType() + ". Fields annotated as @ManyToMany have to be a genericly typed " + List.class, field, ManyToMany.class, + beanClass); + } - if (ReflectionUtils.getGenericlyTypeCount(field) != 1) { + if (ReflectionUtils.getGenericlyTypeCount(field) != 1) { - throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass - + " is genericly typed. Fields annotated as @ManyToMany have to be a genericly typed " + List.class, field, ManyToMany.class, - beanClass); - } + throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in " + beanClass + + " is genericly typed. Fields annotated as @ManyToMany have to be a genericly typed " + List.class, field, ManyToMany.class, + beanClass); + } - // This is a bit ugly but still necessary until someone else - // comes up with something smarter... - Class remoteClass = (Class) ReflectionUtils.getGenericType(field); + // This is a bit ugly but still necessary until someone else + // comes up with something smarter... + Class remoteClass = (Class) ReflectionUtils.getGenericType(field); - this.manyToManyRelations.put(field, DefaultManyToManyRelation.getGenericInstance(beanClass, remoteClass, field, daoFactory, daoManaged)); + this.manyToManyRelations.put(field, DefaultManyToManyRelation.getGenericInstance(beanClass, remoteClass, field, daoFactory, daoManaged)); - ManyToMany manyToMany = field.getAnnotation(ManyToMany.class); + ManyToMany manyToMany = field.getAnnotation(ManyToMany.class); - if (manyToMany.autoAdd()) { - this.autoAddRelations.add(field); - } + if (manyToMany.autoAdd()) { + this.autoAddRelations.add(field); + } - if (manyToMany.autoUpdate()) { - this.autoUpdateRelations.add(field); - } + if (manyToMany.autoUpdate()) { + this.autoUpdateRelations.add(field); + } - if (manyToMany.autoGet()) { - this.autoGetRelations.add(field); - } + if (manyToMany.autoGet()) { + this.autoGetRelations.add(field); + } - } else { + } else { - QueryParameterPopulator queryPopulator = this.getQueryParameterPopulator(field.getType()); + QueryParameterPopulator queryPopulator = this.getQueryParameterPopulator(field.getType()); - Method method = null; + Method method = null; - if (queryPopulator == null) { + if (queryPopulator == null) { - method = PreparedStatementQueryMethods.getQueryMethod(field.getType()); + method = PreparedStatementQueryMethods.getQueryMethod(field.getType()); - if (method == null && field.getType().isEnum()) { + if (method == null && field.getType().isEnum()) { - queryPopulator = EnumPopulator.getInstanceFromField(field); - } + queryPopulator = EnumPopulator.getInstanceFromField(field); + } - if (method == null && queryPopulator == null) { + if (method == null && queryPopulator == null) { - throw new RuntimeException("No query method or query parameter populator found for @DAOManaged annotate field " + field.getName() + " in " + beanClass); - } - } + throw new RuntimeException("No query method or query parameter populator found for @DAOManaged annotate field " + field.getName() + " in " + beanClass); + } + } - String columnName = daoManaged.columnName(); + String columnName = daoManaged.columnName(); - if (StringUtils.isEmpty(columnName)) { + if (StringUtils.isEmpty(columnName)) { - columnName = field.getName(); - } + columnName = field.getName(); + } - SimpleColumn simpleColumn = null; + SimpleColumn simpleColumn = null; - Key primaryKey = field.getAnnotation(Key.class); + Key primaryKey = field.getAnnotation(Key.class); - if (primaryKey != null) { + if (primaryKey != null) { - simpleColumn = SimpleColumn.getGenericInstance(beanClass, field.getType(), field, method, queryPopulator, columnName, daoManaged - .autoGenerated()); + simpleColumn = SimpleColumn.getGenericInstance(beanClass, field.getType(), field, method, queryPopulator, columnName, daoManaged + .autoGenerated()); - this.simpleKeys.add(simpleColumn); + this.simpleKeys.add(simpleColumn); - } else { + } else { - simpleColumn = SimpleColumn.getGenericInstance(beanClass, field.getType(), field, method, queryPopulator, columnName, daoManaged - .autoGenerated()); + simpleColumn = SimpleColumn.getGenericInstance(beanClass, field.getType(), field, method, queryPopulator, columnName, daoManaged + .autoGenerated()); - this.simpleColumns.add(simpleColumn); - } + this.simpleColumns.add(simpleColumn); + } - this.columnMap.put(field, simpleColumn); + this.columnMap.put(field, simpleColumn); - if (daoManaged.autoGenerated()) { + if (daoManaged.autoGenerated()) { - if (daoManaged.autGenerationColumnIndex() != 0) { + if (daoManaged.autGenerationColumnIndex() != 0) { - this.columnKeyCollectors.add(new ColumnKeyCollector(field, populator, daoManaged.autGenerationColumnIndex())); + this.columnKeyCollectors.add(new ColumnKeyCollector(field, populator, daoManaged.autGenerationColumnIndex())); - } else { + } else { - this.columnKeyCollectors.add(new ColumnKeyCollector(field, populator, generatedKeyColumnIndex)); + this.columnKeyCollectors.add(new ColumnKeyCollector(field, populator, generatedKeyColumnIndex)); - generatedKeyColumnIndex++; - } - } + generatedKeyColumnIndex++; + } + } - if (orderBy != null) { - this.columnOrderMap.put(orderBy, simpleColumn); - } - } - } - } + if (orderBy != null) { + this.columnOrderMap.put(orderBy, simpleColumn); + } + } + } + } - if (this.simpleKeys.isEmpty() && this.manyToOneRelationKeys.isEmpty()) { + if (this.simpleKeys.isEmpty() && this.manyToOneRelationKeys.isEmpty()) { - throw new RuntimeException("No @Key annotated field found in " + beanClass + "!"); - } + throw new RuntimeException("No @Key annotated field found in " + beanClass + "!"); + } - // Genearate SQL statements - this.generateInsertSQL(); - this.generateUpdateSQL(); - this.generateDeleteSQL(); - this.generateCheckIfExistsSQL(); - this.generateDeleteByFieldSQL(); - this.generateGetSQL(); - this.generateDefaultSortingCriteria(); - } + // Genearate SQL statements + this.generateInsertSQL(); + this.generateUpdateSQL(); + this.generateDeleteSQL(); + this.generateCheckIfExistsSQL(); + this.generateDeleteByFieldSQL(); + this.generateGetSQL(); + this.generateDefaultSortingCriteria(); + } - public DataSource getDataSource() { - return dataSource; - } - - private void checkAutoGeneration(DAOManaged daoManaged) { + public DataSource getDataSource() { + return dataSource; + } - if (daoManaged.autoGenerated()) { + private void checkAutoGeneration(DAOManaged daoManaged) { - throw new RuntimeException("Fields with relations cannot be auto generated!"); - } - } + if (daoManaged.autoGenerated()) { - @SuppressWarnings("unchecked") - public QueryParameterPopulator getQueryParameterPopulator(Class type) { + throw new RuntimeException("Fields with relations cannot be auto generated!"); + } + } - if (queryParameterPopulators != null) { + @SuppressWarnings("unchecked") + public QueryParameterPopulator getQueryParameterPopulator(Class type) { - for (QueryParameterPopulator queryParameterPopulator : queryParameterPopulators) { + if (queryParameterPopulators != null) { - if (type.equals(queryParameterPopulator.getType())) { + for (QueryParameterPopulator queryParameterPopulator : queryParameterPopulators) { - return (QueryParameterPopulator) queryParameterPopulator; - } - } - } + if (type.equals(queryParameterPopulator.getType())) { - for (QueryParameterPopulator queryParameterPopulator : QueryParameterPopulatorRegistery.getQueryParameterPopulators()) { + return (QueryParameterPopulator) queryParameterPopulator; + } + } + } - if (type.equals(queryParameterPopulator.getType())) { + for (QueryParameterPopulator queryParameterPopulator : QueryParameterPopulatorRegistery.getQueryParameterPopulators()) { - return (QueryParameterPopulator) queryParameterPopulator; - } - } + if (type.equals(queryParameterPopulator.getType())) { - return null; - } + return (QueryParameterPopulator) queryParameterPopulator; + } + } - private void checkOrderByAnnotation(Field field, OrderBy orderBy) { + return null; + } - if (orderBy != null) { + private void checkOrderByAnnotation(Field field, OrderBy orderBy) { - throw new RuntimeException("Invalid @OrderBy annotation on field " + field.getName() + " in " + this.beanClass + ", the @OrderBy annotation is not allowed on @OneToMany and @ManyToMany annotated fields."); - } - } + if (orderBy != null) { - private void generateDefaultSortingCriteria() { + throw new RuntimeException("Invalid @OrderBy annotation on field " + field.getName() + " in " + this.beanClass + ", the @OrderBy annotation is not allowed on @OneToMany and @ManyToMany annotated fields."); + } + } - if (!this.columnOrderMap.isEmpty()) { + private void generateDefaultSortingCriteria() { - StringBuilder stringBuilder = new StringBuilder(" ORDER BY "); + if (!this.columnOrderMap.isEmpty()) { - boolean first = true; + StringBuilder stringBuilder = new StringBuilder(" ORDER BY "); - for (Entry> entry : this.columnOrderMap.entrySet()) { + boolean first = true; - if (first) { + for (Entry> entry : this.columnOrderMap.entrySet()) { - first = false; + if (first) { - } else { + first = false; - stringBuilder.append(", "); - } + } else { - stringBuilder.append(entry.getValue().getColumnName() + " " + entry.getKey().order().toString()); - } + stringBuilder.append(", "); + } - this.defaultSortingCriteria = stringBuilder.toString(); + stringBuilder.append(entry.getValue().getColumnName() + " " + entry.getKey().order().toString()); + } - } else { + this.defaultSortingCriteria = stringBuilder.toString(); - this.defaultSortingCriteria = ""; - } - } + } else { - protected void generateInsertSQL() { + this.defaultSortingCriteria = ""; + } + } - StringBuilder stringBuilder = new StringBuilder(); + protected void generateInsertSQL() { - stringBuilder.append("INSERT INTO " + this.tableName + "("); + StringBuilder stringBuilder = new StringBuilder(); - boolean first = true; + stringBuilder.append("INSERT INTO " + this.tableName + "("); - for (Column column : this.columnMap.values()) { + boolean first = true; - if (first) { + for (Column column : this.columnMap.values()) { - first = false; + if (first) { - } else { + first = false; - stringBuilder.append(", "); - } + } else { - stringBuilder.append(column.getColumnName()); - } + stringBuilder.append(", "); + } - stringBuilder.append(") VALUES ("); + stringBuilder.append(column.getColumnName()); + } - first = true; + stringBuilder.append(") VALUES ("); - for (@SuppressWarnings("unused") - Column column : this.columnMap.values()) { + first = true; - if (first) { + for (@SuppressWarnings("unused") + Column column : this.columnMap.values()) { - first = false; + if (first) { - } else { + first = false; - stringBuilder.append(", "); - } + } else { - stringBuilder.append("?"); - } + stringBuilder.append(", "); + } - stringBuilder.append(")"); + stringBuilder.append("?"); + } - this.insertSQL = stringBuilder.toString(); - } + stringBuilder.append(")"); - protected void generateUpdateSQL() { + this.insertSQL = stringBuilder.toString(); + } - StringBuilder stringBuilder = new StringBuilder(); + protected void generateUpdateSQL() { - stringBuilder.append("UPDATE " + this.tableName + " SET "); + StringBuilder stringBuilder = new StringBuilder(); - boolean first = true; + stringBuilder.append("UPDATE " + this.tableName + " SET "); - for (Column column : this.columnMap.values()) { + boolean first = true; - if (first) { + for (Column column : this.columnMap.values()) { - first = false; + if (first) { - } else { + first = false; - stringBuilder.append(", "); - } + } else { - stringBuilder.append(column.getColumnName() + " = ?"); - } + stringBuilder.append(", "); + } - stringBuilder.append(" WHERE "); + stringBuilder.append(column.getColumnName() + " = ?"); + } - this.appendPrimaryKeyWhereStatement(stringBuilder); + stringBuilder.append(" WHERE "); - this.updateSQL = stringBuilder.toString(); - } + this.appendPrimaryKeyWhereStatement(stringBuilder); - protected void generateCheckIfExistsSQL() { + this.updateSQL = stringBuilder.toString(); + } - StringBuilder stringBuilder = new StringBuilder("SELECT 1 FROM " + tableName + " WHERE "); + protected void generateCheckIfExistsSQL() { - this.appendPrimaryKeyWhereStatement(stringBuilder); + StringBuilder stringBuilder = new StringBuilder("SELECT 1 FROM " + tableName + " WHERE "); - this.checkIfExistsSQL = stringBuilder.toString(); - } + this.appendPrimaryKeyWhereStatement(stringBuilder); - private void appendPrimaryKeyWhereStatement(StringBuilder stringBuilder) { + this.checkIfExistsSQL = stringBuilder.toString(); + } - boolean first = true; + private void appendPrimaryKeyWhereStatement(StringBuilder stringBuilder) { - for (Column column : this.simpleKeys) { + boolean first = true; - if (first) { + for (Column column : this.simpleKeys) { - first = false; + if (first) { - } else { + first = false; - stringBuilder.append(" AND "); - } + } else { - stringBuilder.append(column.getColumnName() + " = ?"); - } + stringBuilder.append(" AND "); + } - for (Column column : this.manyToOneRelationKeys.values()) { + stringBuilder.append(column.getColumnName() + " = ?"); + } - if (first) { + for (Column column : this.manyToOneRelationKeys.values()) { - first = false; + if (first) { - } else { + first = false; - stringBuilder.append(" AND "); - } + } else { - stringBuilder.append(column.getColumnName() + " = ?"); - } - } + stringBuilder.append(" AND "); + } - protected void generateDeleteSQL() { + stringBuilder.append(column.getColumnName() + " = ?"); + } + } - StringBuilder stringBuilder = new StringBuilder(); + protected void generateDeleteSQL() { - stringBuilder.append("DELETE FROM "); - stringBuilder.append(tableName); - stringBuilder.append(" WHERE "); + StringBuilder stringBuilder = new StringBuilder(); - this.appendPrimaryKeyWhereStatement(stringBuilder); + stringBuilder.append("DELETE FROM "); + stringBuilder.append(tableName); + stringBuilder.append(" WHERE "); - this.deleteSQL = stringBuilder.toString(); - } + this.appendPrimaryKeyWhereStatement(stringBuilder); - protected void generateDeleteByFieldSQL() { + this.deleteSQL = stringBuilder.toString(); + } - this.deleteByFieldSQL = "DELETE FROM " + tableName; - } + protected void generateDeleteByFieldSQL() { - protected void generateGetSQL() { + this.deleteByFieldSQL = "DELETE FROM " + tableName; + } - this.getSQL = "SELECT * FROM " + tableName; - } + protected void generateGetSQL() { - public TransactionHandler createTransaction() throws SQLException { + this.getSQL = "SELECT * FROM " + tableName; + } - return new TransactionHandler(dataSource); - } + public TransactionHandler createTransaction() throws SQLException { - public void add(T bean) throws SQLException { + return new TransactionHandler(dataSource); + } - TransactionHandler transactionHandler = null; + public void add(T bean) throws SQLException { - try { + TransactionHandler transactionHandler = null; - transactionHandler = new TransactionHandler(dataSource); + try { - this.add(bean, transactionHandler.getConnection(), null); + transactionHandler = new TransactionHandler(dataSource); - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + this.add(bean, transactionHandler.getConnection(), null); - public void add(T bean, RelationQuery relationQuery) throws SQLException { + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - TransactionHandler transactionHandler = null; + public void add(T bean, RelationQuery relationQuery) throws SQLException { - try { + TransactionHandler transactionHandler = null; - transactionHandler = new TransactionHandler(dataSource); + try { - this.add(bean, transactionHandler.getConnection(), relationQuery); + transactionHandler = new TransactionHandler(dataSource); - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + this.add(bean, transactionHandler.getConnection(), relationQuery); - public void addAll(Collection beans, RelationQuery relationQuery) throws SQLException { + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - TransactionHandler transactionHandler = null; + public void addAll(Collection beans, RelationQuery relationQuery) throws SQLException { - try { + TransactionHandler transactionHandler = null; - transactionHandler = new TransactionHandler(dataSource); + try { - this.addAll(beans, transactionHandler.getConnection(), relationQuery); + transactionHandler = new TransactionHandler(dataSource); - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + this.addAll(beans, transactionHandler.getConnection(), relationQuery); - public void add(T bean, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - this.add(bean, transactionHandler.getConnection(), relationQuery); - } + public void add(T bean, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { - public void addAll(List beans, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { + this.add(bean, transactionHandler.getConnection(), relationQuery); + } - this.addAll(beans, transactionHandler.getConnection(), relationQuery); - } + public void addAll(List beans, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { - public void addAll(Collection beans, Connection connection, RelationQuery relationQuery) throws SQLException { + this.addAll(beans, transactionHandler.getConnection(), relationQuery); + } - for (T bean : beans) { + public void addAll(Collection beans, Connection connection, RelationQuery relationQuery) throws SQLException { - this.add(bean, connection, relationQuery); - } - } + for (T bean : beans) { - public void add(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + this.add(bean, connection, relationQuery); + } + } - this.preAddRelations(bean, connection, relationQuery); + public void add(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - UpdateQuery query = null; + this.preAddRelations(bean, connection, relationQuery); - try { + UpdateQuery query = null; - query = new UpdateQuery(connection, false, this.insertSQL); + try { - IntegerCounter integerCounter = new IntegerCounter(); + query = new UpdateQuery(connection, false, this.insertSQL); - setQueryValues(bean, query, integerCounter, this.columnMap.values()); + IntegerCounter integerCounter = new IntegerCounter(); - this.executeUpdateQuery(query, bean); + setQueryValues(bean, query, integerCounter, this.columnMap.values()); - this.addRelations(bean, connection, relationQuery); + this.executeUpdateQuery(query, bean); - } finally { + this.addRelations(bean, connection, relationQuery); - PreparedStatementQuery.autoCloseQuery(query); - } - } + } finally { - private void executeUpdateQuery(UpdateQuery query, T bean) throws SQLException { + PreparedStatementQuery.autoCloseQuery(query); + } + } - if (!this.columnKeyCollectors.isEmpty()) { + private void executeUpdateQuery(UpdateQuery query, T bean) throws SQLException { - query.executeUpdate(new ColumnKeyCollectorWrapper(this.columnKeyCollectors, bean)); + if (!this.columnKeyCollectors.isEmpty()) { - } else { + query.executeUpdate(new ColumnKeyCollectorWrapper(this.columnKeyCollectors, bean)); - query.executeUpdate(); - } - } + } else { - private void preAddRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + query.executeUpdate(); + } + } - if (RelationQuery.hasRelations(relationQuery)) { + private void preAddRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - for (Field relation : relationQuery.getRelations()) { + if (RelationQuery.hasRelations(relationQuery)) { - preAddRelation(bean, connection, relationQuery, relation); - } - } + for (Field relation : relationQuery.getRelations()) { - if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { + preAddRelation(bean, connection, relationQuery, relation); + } + } - for (Field relation : autoAddRelations) { + if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { - if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { + for (Field relation : autoAddRelations) { - preAddRelation(bean, connection, relationQuery, relation); - } - } - } - } + if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { - private void preAddRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { + preAddRelation(bean, connection, relationQuery, relation); + } + } + } + } - ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); + private void preAddRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { - if (manyToOneRelation != null) { + ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); - manyToOneRelation.add(bean, connection, relationQuery); - return; - } + if (manyToOneRelation != null) { - manyToOneRelation = this.manyToOneRelationKeys.get(relation); + manyToOneRelation.add(bean, connection, relationQuery); + return; + } - if (manyToOneRelation != null) { + manyToOneRelation = this.manyToOneRelationKeys.get(relation); - manyToOneRelation.add(bean, connection, relationQuery); - } - } + if (manyToOneRelation != null) { - private void addRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + manyToOneRelation.add(bean, connection, relationQuery); + } + } - if (RelationQuery.hasRelations(relationQuery)) { + private void addRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - for (Field relation : relationQuery.getRelations()) { + if (RelationQuery.hasRelations(relationQuery)) { - addRelation(bean, connection, relationQuery, relation); - } - } + for (Field relation : relationQuery.getRelations()) { - if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { - for (Field relation : autoAddRelations) { + addRelation(bean, connection, relationQuery, relation); + } + } - if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { + if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { + for (Field relation : autoAddRelations) { - addRelation(bean, connection, relationQuery, relation); - } - } - } + if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { - } + addRelation(bean, connection, relationQuery, relation); + } + } + } - private void addRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { + } - OneToManyRelation oneToManyRelation = this.oneToManyRelations.get(relation); + private void addRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { - if (oneToManyRelation != null) { + OneToManyRelation oneToManyRelation = this.oneToManyRelations.get(relation); - oneToManyRelation.add(bean, connection, relationQuery); - return; - } + if (oneToManyRelation != null) { - ManyToManyRelation manyToManyRelation = this.manyToManyRelations.get(relation); + oneToManyRelation.add(bean, connection, relationQuery); + return; + } - if (manyToManyRelation != null) { + ManyToManyRelation manyToManyRelation = this.manyToManyRelations.get(relation); - manyToManyRelation.add(bean, connection, relationQuery); - } - } + if (manyToManyRelation != null) { - private void preUpdateRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + manyToManyRelation.add(bean, connection, relationQuery); + } + } - if (RelationQuery.hasRelations(relationQuery)) { + private void preUpdateRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - for (Field relation : relationQuery.getRelations()) { + if (RelationQuery.hasRelations(relationQuery)) { - preUpdateRelation(bean, connection, relationQuery, relation); - } - } + for (Field relation : relationQuery.getRelations()) { - if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { + preUpdateRelation(bean, connection, relationQuery, relation); + } + } - for (Field relation : autoUpdateRelations) { + if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { - if (relationQuery == null || (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation)))) { + for (Field relation : autoUpdateRelations) { - preUpdateRelation(bean, connection, relationQuery, relation); - } - } - } - } + if (relationQuery == null || (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation)))) { - private void preUpdateRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { + preUpdateRelation(bean, connection, relationQuery, relation); + } + } + } + } - ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); + private void preUpdateRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { - if (manyToOneRelation != null) { + ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); - manyToOneRelation.update(bean, connection, relationQuery); - return; - } + if (manyToOneRelation != null) { - manyToOneRelation = this.manyToOneRelationKeys.get(relation); + manyToOneRelation.update(bean, connection, relationQuery); + return; + } - if (manyToOneRelation != null) { + manyToOneRelation = this.manyToOneRelationKeys.get(relation); - manyToOneRelation.update(bean, connection, relationQuery); - } - } + if (manyToOneRelation != null) { - private void updateRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + manyToOneRelation.update(bean, connection, relationQuery); + } + } - if (RelationQuery.hasRelations(relationQuery)) { + private void updateRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - for (Field relation : relationQuery.getRelations()) { + if (RelationQuery.hasRelations(relationQuery)) { - updateRelation(bean, connection, relationQuery, relation); - } - } + for (Field relation : relationQuery.getRelations()) { - if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { + updateRelation(bean, connection, relationQuery, relation); + } + } - for (Field relation : autoUpdateRelations) { + if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { - if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { + for (Field relation : autoUpdateRelations) { - updateRelation(bean, connection, relationQuery, relation); - } - } - } - } + if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { - private void updateRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { + updateRelation(bean, connection, relationQuery, relation); + } + } + } + } - OneToManyRelation oneToManyRelation = this.oneToManyRelations.get(relation); + private void updateRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { - if (oneToManyRelation != null) { + OneToManyRelation oneToManyRelation = this.oneToManyRelations.get(relation); - oneToManyRelation.update(bean, connection, relationQuery); - return; - } + if (oneToManyRelation != null) { - ManyToManyRelation manyToManyRelation = this.manyToManyRelations.get(relation); + oneToManyRelation.update(bean, connection, relationQuery); + return; + } - if (manyToManyRelation != null) { + ManyToManyRelation manyToManyRelation = this.manyToManyRelations.get(relation); - manyToManyRelation.update(bean, connection, relationQuery); - } - } + if (manyToManyRelation != null) { - private void setQueryValues(T bean, PreparedStatementQuery query, IntegerCounter integerCounter, Collection> columns) throws SQLException { + manyToManyRelation.update(bean, connection, relationQuery); + } + } - for (Column column : columns) { + private void setQueryValues(T bean, PreparedStatementQuery query, IntegerCounter integerCounter, Collection> columns) throws SQLException { - if (column.getQueryParameterPopulator() != null) { + for (Column column : columns) { - column.getQueryParameterPopulator().populate(query, integerCounter.increment(), column.getBeanValue(bean)); + if (column.getQueryParameterPopulator() != null) { - } else { + column.getQueryParameterPopulator().populate(query, integerCounter.increment(), column.getBeanValue(bean)); - try { - column.getQueryMethod().invoke(query, integerCounter.increment(), column.getBeanValue(bean)); + } else { - } catch (IllegalArgumentException e) { + try { + column.getQueryMethod().invoke(query, integerCounter.increment(), column.getBeanValue(bean)); - throw new RuntimeException(e); + } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { + throw new RuntimeException(e); - throw new RuntimeException(e); + } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { + throw new RuntimeException(e); - throw new RuntimeException(e); - } - } - } - } + } catch (InvocationTargetException e) { - private void setQueryValues(List beans, PreparedStatementQuery query, IntegerCounter integerCounter, Collection> columns, Field excludedField) throws SQLException { + throw new RuntimeException(e); + } + } + } + } - for (Column column : columns) { + private void setQueryValues(List beans, PreparedStatementQuery query, IntegerCounter integerCounter, Collection> columns, Field excludedField) throws SQLException { - if(column.getBeanField().equals(excludedField)) { - continue; - } + for (Column column : columns) { - for (T bean : beans) { + if(column.getBeanField().equals(excludedField)) { + continue; + } - if (column.getQueryParameterPopulator() != null) { + for (T bean : beans) { - column.getQueryParameterPopulator().populate(query, integerCounter.increment(), column.getBeanValue(bean)); + if (column.getQueryParameterPopulator() != null) { - } else { + column.getQueryParameterPopulator().populate(query, integerCounter.increment(), column.getBeanValue(bean)); - try { - column.getQueryMethod().invoke(query, integerCounter.increment(), column.getBeanValue(bean)); + } else { - } catch (IllegalArgumentException e) { + try { + column.getQueryMethod().invoke(query, integerCounter.increment(), column.getBeanValue(bean)); - throw new RuntimeException(e); + } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { + throw new RuntimeException(e); - throw new RuntimeException(e); + } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { + throw new RuntimeException(e); - throw new RuntimeException(e); - } - } - } - } - } + } catch (InvocationTargetException e) { - public void addOrUpdateAll(Collection beans, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { - this.addOrUpdateAll(beans, transactionHandler.getConnection(), relationQuery); - } - - public void addOrUpdateAll(Collection beans, Connection connection, RelationQuery relationQuery) throws SQLException { + throw new RuntimeException(e); + } + } + } + } + } - for (T bean : beans) { - this.addOrUpdate(bean, connection, relationQuery); - } - } + public void addOrUpdateAll(Collection beans, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { + this.addOrUpdateAll(beans, transactionHandler.getConnection(), relationQuery); + } - public void addOrUpdate(T bean, RelationQuery relationQuery) throws SQLException { + public void addOrUpdateAll(Collection beans, Connection connection, RelationQuery relationQuery) throws SQLException { - TransactionHandler transactionHandler = null; + for (T bean : beans) { + this.addOrUpdate(bean, connection, relationQuery); + } + } - try { + public void addOrUpdate(T bean, RelationQuery relationQuery) throws SQLException { - transactionHandler = new TransactionHandler(dataSource); + TransactionHandler transactionHandler = null; - this.addOrUpdate(bean, transactionHandler.getConnection(), relationQuery); + try { - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + transactionHandler = new TransactionHandler(dataSource); - public void addOrUpdate(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + this.addOrUpdate(bean, transactionHandler.getConnection(), relationQuery); - if (!isNewBean(bean, connection)) { + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - this.update(bean, connection, relationQuery); + public void addOrUpdate(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - } else { + if (!isNewBean(bean, connection)) { - this.add(bean, connection, relationQuery); - } - } + this.update(bean, connection, relationQuery); - public boolean isNewBean(T bean, Connection connection) throws SQLException { + } else { - if(!hasKeysSet(bean)){ + this.add(bean, connection, relationQuery); + } + } - return true; - } + public boolean isNewBean(T bean, Connection connection) throws SQLException { - //Unable to determine if beans is new or not so far, do db query to check - return !beanExists(bean, connection); - } + if(!hasKeysSet(bean)){ - public boolean hasKeysSet(T bean) throws SQLException { + return true; + } - for (Column column : this.simpleKeys) { + //Unable to determine if beans is new or not so far, do db query to check + return !beanExists(bean, connection); + } - if (column.getBeanValue(bean) == null) { + public boolean hasKeysSet(T bean) throws SQLException { - //Key not set, presume new bean - return false; - } - } + for (Column column : this.simpleKeys) { - for (Column column : this.manyToOneRelationKeys.values()) { + if (column.getBeanValue(bean) == null) { - if (column.getBeanValue(bean) == null) { + //Key not set, presume new bean + return false; + } + } - //Key not set, presume new bean - return false; - } - } + for (Column column : this.manyToOneRelationKeys.values()) { - return true; - } + if (column.getBeanValue(bean) == null) { - public boolean beanExists(T bean) throws SQLException { + //Key not set, presume new bean + return false; + } + } - Connection connection = null; + return true; + } - try { + public boolean beanExists(T bean) throws SQLException { - connection = this.dataSource.getConnection(); + Connection connection = null; - return beanExists(bean, connection); + try { - } finally { - DBUtils.closeConnection(connection); - } - } + connection = this.dataSource.getConnection(); - public boolean beanExists(T bean, TransactionHandler transactionHandler) throws SQLException { + return beanExists(bean, connection); - return beanExists(bean, transactionHandler.getConnection()); - } + } finally { + DBUtils.closeConnection(connection); + } + } - public boolean beanExists(T bean, Connection connection) throws SQLException { + public boolean beanExists(T bean, TransactionHandler transactionHandler) throws SQLException { - BooleanQuery query = null; + return beanExists(bean, transactionHandler.getConnection()); + } - try { + public boolean beanExists(T bean, Connection connection) throws SQLException { - query = new BooleanQuery(connection, false, this.checkIfExistsSQL); + BooleanQuery query = null; - IntegerCounter integerCounter = new IntegerCounter(); + try { - // Keys from SimpleColumns for where statement - this.setQueryValues(bean, query, integerCounter, this.simpleKeys); + query = new BooleanQuery(connection, false, this.checkIfExistsSQL); - // Keys from many to one relations for where statement - this.setQueryValues(bean, query, integerCounter, this.manyToOneRelationKeys.values()); + IntegerCounter integerCounter = new IntegerCounter(); - return query.executeQuery(); + // Keys from SimpleColumns for where statement + this.setQueryValues(bean, query, integerCounter, this.simpleKeys); - } finally { + // Keys from many to one relations for where statement + this.setQueryValues(bean, query, integerCounter, this.manyToOneRelationKeys.values()); - BooleanQuery.autoCloseQuery(query); - } - } + return query.executeQuery(); - public void update(T bean) throws SQLException { + } finally { - TransactionHandler transactionHandler = null; + BooleanQuery.autoCloseQuery(query); + } + } - try { + public void update(T bean) throws SQLException { - transactionHandler = new TransactionHandler(dataSource); + TransactionHandler transactionHandler = null; - this.update(bean, transactionHandler.getConnection(), null); + try { - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + transactionHandler = new TransactionHandler(dataSource); - public void update(T bean, RelationQuery relationQuery) throws SQLException { + this.update(bean, transactionHandler.getConnection(), null); - TransactionHandler transactionHandler = null; + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - try { + public void update(T bean, RelationQuery relationQuery) throws SQLException { - transactionHandler = new TransactionHandler(dataSource); + TransactionHandler transactionHandler = null; - this.update(bean, transactionHandler.getConnection(), relationQuery); + try { - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + transactionHandler = new TransactionHandler(dataSource); - public void update(T bean, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { + this.update(bean, transactionHandler.getConnection(), relationQuery); - this.update(bean, transactionHandler.getConnection(), relationQuery); - } + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - public Integer update(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + public void update(T bean, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { - UpdateQuery query = null; + this.update(bean, transactionHandler.getConnection(), relationQuery); + } - try { + public Integer update(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - this.preUpdateRelations(bean, connection, relationQuery); + UpdateQuery query = null; - query = new UpdateQuery(connection, false, this.updateSQL); + try { - IntegerCounter integerCounter = new IntegerCounter(); + this.preUpdateRelations(bean, connection, relationQuery); - // All fields - this.setQueryValues(bean, query, integerCounter, this.columnMap.values()); + query = new UpdateQuery(connection, false, this.updateSQL); - // Keys from SimpleColumns for where statement - this.setQueryValues(bean, query, integerCounter, this.simpleKeys); + IntegerCounter integerCounter = new IntegerCounter(); - // Keys from many to one relations for where statement - this.setQueryValues(bean, query, integerCounter, this.manyToOneRelationKeys.values()); + // All fields + this.setQueryValues(bean, query, integerCounter, this.columnMap.values()); - query.executeUpdate(); + // Keys from SimpleColumns for where statement + this.setQueryValues(bean, query, integerCounter, this.simpleKeys); - } finally { + // Keys from many to one relations for where statement + this.setQueryValues(bean, query, integerCounter, this.manyToOneRelationKeys.values()); - UpdateQuery.autoCloseQuery(query); - } + query.executeUpdate(); - this.updateRelations(bean, connection, relationQuery); + } finally { - return query.getAffectedRows(); - } + UpdateQuery.autoCloseQuery(query); + } - public void update(List beans, RelationQuery relationQuery) throws SQLException { + this.updateRelations(bean, connection, relationQuery); - TransactionHandler transactionHandler = null; + return query.getAffectedRows(); + } - try { + public void update(List beans, RelationQuery relationQuery) throws SQLException { - transactionHandler = new TransactionHandler(dataSource); + TransactionHandler transactionHandler = null; - this.update(beans, transactionHandler.getConnection(), relationQuery); + try { - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + transactionHandler = new TransactionHandler(dataSource); - public void update(List beans, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { + this.update(beans, transactionHandler.getConnection(), relationQuery); - this.update(beans, transactionHandler.getConnection(), relationQuery); - } - - public void update(List beans, Connection connection, RelationQuery relationQuery) throws SQLException { - - for(T bean : beans){ - - update(bean, connection, relationQuery); - } - } - - public void update(LowLevelQuery lowLevelQuery) throws SQLException { + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - Connection connection = null; + public void update(List beans, TransactionHandler transactionHandler, RelationQuery relationQuery) throws SQLException { - try { + this.update(beans, transactionHandler.getConnection(), relationQuery); + } - connection = this.dataSource.getConnection(); + public void update(List beans, Connection connection, RelationQuery relationQuery) throws SQLException { - this.update(lowLevelQuery, connection); + for(T bean : beans){ - } finally { - DBUtils.closeConnection(connection); - } - } + update(bean, connection, relationQuery); + } + } - public void update(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public void update(LowLevelQuery lowLevelQuery) throws SQLException { - this.update(lowLevelQuery, transactionHandler.getConnection()); - } + Connection connection = null; - public void update(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { + try { - UpdateQuery query = null; + connection = this.dataSource.getConnection(); - try { + this.update(lowLevelQuery, connection); - query = new UpdateQuery(connection, false, lowLevelQuery.getSql()); + } finally { + DBUtils.closeConnection(connection); + } + } - this.setCustomQueryParameters(query, lowLevelQuery.getParameters()); + public void update(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { - if (lowLevelQuery.getGeneratedKeyCollectors() != null) { + this.update(lowLevelQuery, transactionHandler.getConnection()); + } - query.executeUpdate(lowLevelQuery.getGeneratedKeyCollectors()); + public void update(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { - } else { + UpdateQuery query = null; - query.executeUpdate(); - } + try { - } finally { + query = new UpdateQuery(connection, false, lowLevelQuery.getSql()); - PreparedStatementQuery.autoCloseQuery(query); - } - } + this.setCustomQueryParameters(query, lowLevelQuery.getParameters()); - public T get(LowLevelQuery lowLevelQuery) throws SQLException { + if (lowLevelQuery.getGeneratedKeyCollectors() != null) { - Connection connection = null; + query.executeUpdate(lowLevelQuery.getGeneratedKeyCollectors()); - try { + } else { - connection = this.dataSource.getConnection(); + query.executeUpdate(); + } - return this.get(lowLevelQuery, connection); + } finally { - } finally { - DBUtils.closeConnection(connection); - } - } + PreparedStatementQuery.autoCloseQuery(query); + } + } - public T get(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public T get(LowLevelQuery lowLevelQuery) throws SQLException { - return this.get(lowLevelQuery, transactionHandler.getConnection()); - } + Connection connection = null; - public T get(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { + try { - BeanResultSetPopulator populator = this.getPopulator(connection, lowLevelQuery); + connection = this.dataSource.getConnection(); - ObjectQuery query = null; + return this.get(lowLevelQuery, connection); - try { + } finally { + DBUtils.closeConnection(connection); + } + } - query = new ObjectQuery(connection, false, lowLevelQuery.getSql(), populator); + public T get(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { - this.setCustomQueryParameters(query, lowLevelQuery.getParameters()); + return this.get(lowLevelQuery, transactionHandler.getConnection()); + } - T bean = query.executeQuery(); + public T get(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { - if (bean != null && (RelationQuery.hasRelations(lowLevelQuery) || !autoGetRelations.isEmpty())) { + BeanResultSetPopulator populator = this.getPopulator(connection, lowLevelQuery); - this.populateRelations(bean, connection, lowLevelQuery); - } + ObjectQuery query = null; - return bean; + try { - } finally { + query = new ObjectQuery(connection, false, lowLevelQuery.getSql(), populator); - PreparedStatementQuery.autoCloseQuery(query); - } - } + this.setCustomQueryParameters(query, lowLevelQuery.getParameters()); + T bean = query.executeQuery(); + if (bean != null && (RelationQuery.hasRelations(lowLevelQuery) || !autoGetRelations.isEmpty())) { + this.populateRelations(bean, connection, lowLevelQuery); + } + return bean; + } finally { + PreparedStatementQuery.autoCloseQuery(query); + } + } - public boolean getBoolean(LowLevelQuery lowLevelQuery) throws SQLException { - Connection connection = null; - try { - connection = this.dataSource.getConnection(); - return this.getBoolean(lowLevelQuery, connection); - } finally { - DBUtils.closeConnection(connection); - } - } - public boolean getBoolean(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public boolean getBoolean(LowLevelQuery lowLevelQuery) throws SQLException { - return this.getBoolean(lowLevelQuery, transactionHandler.getConnection()); - } + Connection connection = null; - public boolean getBoolean(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { + try { - BooleanQuery query = null; + connection = this.dataSource.getConnection(); - try { + return this.getBoolean(lowLevelQuery, connection); - query = new BooleanQuery(connection, false, lowLevelQuery.getSql()); + } finally { + DBUtils.closeConnection(connection); + } + } - this.setCustomQueryParameters(query, lowLevelQuery.getParameters()); + public boolean getBoolean(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { - return query.executeQuery(); + return this.getBoolean(lowLevelQuery, transactionHandler.getConnection()); + } - } finally { + public boolean getBoolean(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { - PreparedStatementQuery.autoCloseQuery(query); - } - } + BooleanQuery query = null; + try { + query = new BooleanQuery(connection, false, lowLevelQuery.getSql()); + this.setCustomQueryParameters(query, lowLevelQuery.getParameters()); - public T get(HighLevelQuery highLevelQuery) throws SQLException { + return query.executeQuery(); - Connection connection = null; + } finally { - try { + PreparedStatementQuery.autoCloseQuery(query); + } + } - connection = this.dataSource.getConnection(); - return this.get(highLevelQuery, connection); - } finally { - DBUtils.closeConnection(connection); - } - } - public T get(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public T get(HighLevelQuery highLevelQuery) throws SQLException { - return this.get(highLevelQuery, transactionHandler.getConnection()); - } + Connection connection = null; - public T get(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { + try { - BeanResultSetPopulator populator = this.getPopulator(connection, highLevelQuery); + connection = this.dataSource.getConnection(); - ObjectQuery query = null; + return this.get(highLevelQuery, connection); - try { - query = new ObjectQuery(connection, false, this.getSQL + this.getCriterias(highLevelQuery, true), populator); + } finally { + DBUtils.closeConnection(connection); + } + } - if (highLevelQuery.getParameters() != null) { + public T get(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { - setQueryParameters(query, highLevelQuery, 1); - } + return this.get(highLevelQuery, transactionHandler.getConnection()); + } - T bean = query.executeQuery(); + public T get(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { - if (bean != null && (RelationQuery.hasRelations(highLevelQuery) || !autoGetRelations.isEmpty())) { + BeanResultSetPopulator populator = this.getPopulator(connection, highLevelQuery); - this.populateRelations(bean, connection, highLevelQuery); - } + ObjectQuery query = null; - return bean; + try { + query = new ObjectQuery(connection, false, this.getSQL + this.getCriterias(highLevelQuery, true), populator); - } finally { + if (highLevelQuery.getParameters() != null) { - PreparedStatementQuery.autoCloseQuery(query); - } - } + setQueryParameters(query, highLevelQuery, 1); + } - public boolean getBoolean(HighLevelQuery highLevelQuery) throws SQLException { + T bean = query.executeQuery(); - Connection connection = null; + if (bean != null && (RelationQuery.hasRelations(highLevelQuery) || !autoGetRelations.isEmpty())) { - try { + this.populateRelations(bean, connection, highLevelQuery); + } - connection = this.dataSource.getConnection(); + return bean; - return this.getBoolean(highLevelQuery, connection); + } finally { - } finally { - DBUtils.closeConnection(connection); - } - } + PreparedStatementQuery.autoCloseQuery(query); + } + } - public boolean getBoolean(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public boolean getBoolean(HighLevelQuery highLevelQuery) throws SQLException { - return this.getBoolean(highLevelQuery, transactionHandler.getConnection()); - } + Connection connection = null; - public boolean getBoolean(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { + try { - BooleanQuery query = null; + connection = this.dataSource.getConnection(); - try { - query = new BooleanQuery(connection, false, this.getSQL + this.getCriterias(highLevelQuery, true)); + return this.getBoolean(highLevelQuery, connection); - if (highLevelQuery.getParameters() != null) { + } finally { + DBUtils.closeConnection(connection); + } + } - setQueryParameters(query, highLevelQuery, 1); - } + public boolean getBoolean(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { - return query.executeQuery(); + return this.getBoolean(highLevelQuery, transactionHandler.getConnection()); + } - } finally { + public boolean getBoolean(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { - PreparedStatementQuery.autoCloseQuery(query); - } - } + BooleanQuery query = null; - private String getCriterias(HighLevelQuery highLevelQuery, boolean orderBy) { + try { + query = new BooleanQuery(connection, false, this.getSQL + this.getCriterias(highLevelQuery, true)); - if (highLevelQuery == null) { + if (highLevelQuery.getParameters() != null) { - if (orderBy) { + setQueryParameters(query, highLevelQuery, 1); + } - return this.defaultSortingCriteria; + return query.executeQuery(); - } else { + } finally { - return ""; - } - } + PreparedStatementQuery.autoCloseQuery(query); + } + } - StringBuilder stringBuilder = new StringBuilder(); + private String getCriterias(HighLevelQuery highLevelQuery, boolean orderBy) { - if (highLevelQuery.getParameters() != null) { + if (highLevelQuery == null) { - boolean first = true; + if (orderBy) { - for (QueryParameter queryParameter : highLevelQuery.getParameters()) { + return this.defaultSortingCriteria; - if (first) { + } else { - stringBuilder.append(" WHERE "); + return ""; + } + } - first = false; + StringBuilder stringBuilder = new StringBuilder(); - } else { + if (highLevelQuery.getParameters() != null) { - stringBuilder.append(" AND "); - } + boolean first = true; - stringBuilder.append(queryParameter.getColumn().getColumnName() + " " + queryParameter.getOperator()); + for (QueryParameter queryParameter : highLevelQuery.getParameters()) { - if (queryParameter.hasValues()) { + if (first) { - if (queryParameter.hasMultipleValues()) { + stringBuilder.append(" WHERE "); - //stringBuilder.append(queryParameter.getOperator() + " " + queryParameter.getColumn().getColumnName()); + first = false; - stringBuilder.append(" (?"); + } else { - if (queryParameter.getValues().size() > 1) { + stringBuilder.append(" AND "); + } - StringUtils.repeatString(",?", queryParameter.getValues().size() - 1, stringBuilder); - } + stringBuilder.append(queryParameter.getColumn().getColumnName() + " " + queryParameter.getOperator()); - stringBuilder.append(")"); + if (queryParameter.hasValues()) { - } else { + if (queryParameter.hasMultipleValues()) { - stringBuilder.append(" ?"); - } - } - } - } + //stringBuilder.append(queryParameter.getOperator() + " " + queryParameter.getColumn().getColumnName()); - if (orderBy && highLevelQuery.getOrderByCriterias() != null) { + stringBuilder.append(" (?"); - boolean first = true; + if (queryParameter.getValues().size() > 1) { - for (OrderByCriteria criteria : highLevelQuery.getOrderByCriterias()) { + StringUtils.repeatString(",?", queryParameter.getValues().size() - 1, stringBuilder); + } - if (first) { + stringBuilder.append(")"); - stringBuilder.append(" ORDER BY " + criteria.getColumn().getColumnName() + " " + criteria.getOrder().toString()); + } else { - first = false; + stringBuilder.append(" ?"); + } + } + } + } - } else { + if (orderBy && highLevelQuery.getOrderByCriterias() != null) { - stringBuilder.append(", " + criteria.getColumn().getColumnName() + " " + criteria.getOrder().toString()); - } - } + boolean first = true; - } else { + for (OrderByCriteria criteria : highLevelQuery.getOrderByCriterias()) { - stringBuilder.append(this.defaultSortingCriteria); - } + if (first) { - return stringBuilder.toString(); - } + stringBuilder.append(" ORDER BY " + criteria.getColumn().getColumnName() + " " + criteria.getOrder().toString()); - @SuppressWarnings("unchecked") - private Column getColumn(Field field, Class paramClass) { + first = false; - Column column = this.columnMap.get(field); + } else { - if (column == null) { + stringBuilder.append(", " + criteria.getColumn().getColumnName() + " " + criteria.getOrder().toString()); + } + } - throw new RuntimeException("Field " + field + " not found in " + this.beanClass + "!"); + } else { - } else if (!column.getParamType().isAssignableFrom(paramClass)) { + stringBuilder.append(this.defaultSortingCriteria); + } - throw new RuntimeException(" " + paramClass + " is not compatible with type " + column.getParamType() + " of field " + field + " in " - + this.beanClass + "!"); - } + return stringBuilder.toString(); + } - return (Column) column; - } + @SuppressWarnings("unchecked") + private Column getColumn(Field field, Class paramClass) { - protected BeanResultSetPopulator getPopulator(Connection connection, LowLevelQuery query) { + Column column = this.columnMap.get(field); - BeanResultSetPopulator populator = getPopulator(connection, (RelationQuery)query); + if (column == null) { - if(query.hasChainedBeanResultSetPopulators()){ + throw new RuntimeException("Field " + field + " not found in " + this.beanClass + "!"); - return new BeanChainPopulator(query.getChainedResultSetPopulators(), populator); - } + } else if (!column.getParamType().isAssignableFrom(paramClass)) { - return populator; - } + throw new RuntimeException(" " + paramClass + " is not compatible with type " + column.getParamType() + " of field " + field + " in " + + this.beanClass + "!"); + } - protected BeanResultSetPopulator getPopulator(Connection connection, RelationQuery relationQuery) { + return (Column) column; + } - ArrayList> manyToOneRelations = null; + protected BeanResultSetPopulator getPopulator(Connection connection, LowLevelQuery query) { - if (RelationQuery.hasRelations(relationQuery)) { + BeanResultSetPopulator populator = getPopulator(connection, (RelationQuery)query); - for (Field relation : relationQuery.getRelations()) { + if(query.hasChainedBeanResultSetPopulators()){ - ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); + return new BeanChainPopulator(query.getChainedResultSetPopulators(), populator); + } - if (manyToOneRelation == null) { + return populator; + } - manyToOneRelation = this.manyToOneRelationKeys.get(relation); - } + protected BeanResultSetPopulator getPopulator(Connection connection, RelationQuery relationQuery) { - if (manyToOneRelation != null) { + ArrayList> manyToOneRelations = null; - if (manyToOneRelations == null) { + if (RelationQuery.hasRelations(relationQuery)) { - manyToOneRelations = new ArrayList>(); - } + for (Field relation : relationQuery.getRelations()) { - manyToOneRelations.add(manyToOneRelation); - } - } - } + ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); - if((!autoGetRelations.isEmpty() && (relationQuery == null || !relationQuery.isDisableAutoRelations()))){ + if (manyToOneRelation == null) { - for (Field relation : autoGetRelations) { + manyToOneRelation = this.manyToOneRelationKeys.get(relation); + } - ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); + if (manyToOneRelation != null) { - if (manyToOneRelation == null) { + if (manyToOneRelations == null) { - manyToOneRelation = this.manyToOneRelationKeys.get(relation); - } + manyToOneRelations = new ArrayList>(); + } - if (manyToOneRelation != null) { + manyToOneRelations.add(manyToOneRelation); + } + } + } - if (manyToOneRelations == null) { + if((!autoGetRelations.isEmpty() && (relationQuery == null || !relationQuery.isDisableAutoRelations()))){ - manyToOneRelations = new ArrayList>(); - } + for (Field relation : autoGetRelations) { - manyToOneRelations.add(manyToOneRelation); - } - } - } + ManyToOneRelation manyToOneRelation = this.manyToOneRelations.get(relation); - if (manyToOneRelations != null) { + if (manyToOneRelation == null) { - return new BeanRelationPopulator(this.populator, manyToOneRelations, connection, relationQuery); - } + manyToOneRelation = this.manyToOneRelationKeys.get(relation); + } - return this.populator; - } + if (manyToOneRelation != null) { - protected void populateRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { + if (manyToOneRelations == null) { - if (RelationQuery.hasRelations(relationQuery)) { + manyToOneRelations = new ArrayList>(); + } - for (Field relation : relationQuery.getRelations()) { + manyToOneRelations.add(manyToOneRelation); + } + } + } - populateRelation(bean, connection, relationQuery, relation); - } - } + if (manyToOneRelations != null) { - if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { + return new BeanRelationPopulator(this.populator, manyToOneRelations, connection, relationQuery); + } - for (Field relation : autoGetRelations) { + return this.populator; + } - if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { + protected void populateRelations(T bean, Connection connection, RelationQuery relationQuery) throws SQLException { - populateRelation(bean, connection, relationQuery, relation); - } - } - } - } + if (RelationQuery.hasRelations(relationQuery)) { - protected void populateRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { + for (Field relation : relationQuery.getRelations()) { - OneToManyRelation oneToManyRelation = this.oneToManyRelations.get(relation); + populateRelation(bean, connection, relationQuery, relation); + } + } - if (oneToManyRelation != null) { + if (relationQuery == null || !relationQuery.isDisableAutoRelations()) { - oneToManyRelation.getRemoteValue(bean, connection, relationQuery); - return; - } + for (Field relation : autoGetRelations) { - ManyToManyRelation manyToManyRelation = this.manyToManyRelations.get(relation); + if (relationQuery == null || (!relationQuery.containsRelation(relation) && !relationQuery.containsExcludedRelation(relation))) { - if (manyToManyRelation != null) { + populateRelation(bean, connection, relationQuery, relation); + } + } + } + } - manyToManyRelation.getRemoteValue(bean, connection, relationQuery); - } - } + protected void populateRelation(T bean, Connection connection, RelationQuery relationQuery, Field relation) throws SQLException { - public List getAll(LowLevelQuery lowLevelQuery) throws SQLException { + OneToManyRelation oneToManyRelation = this.oneToManyRelations.get(relation); - Connection connection = null; + if (oneToManyRelation != null) { - try { + oneToManyRelation.getRemoteValue(bean, connection, relationQuery); + return; + } - connection = this.dataSource.getConnection(); + ManyToManyRelation manyToManyRelation = this.manyToManyRelations.get(relation); - return this.getAll(lowLevelQuery, connection); + if (manyToManyRelation != null) { - } finally { - DBUtils.closeConnection(connection); - } - } + manyToManyRelation.getRemoteValue(bean, connection, relationQuery); + } + } - public List getAll(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public List getAll(LowLevelQuery lowLevelQuery) throws SQLException { - return this.getAll(lowLevelQuery, transactionHandler.getConnection()); - } + Connection connection = null; - public List getAll(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { + try { - BeanResultSetPopulator populator = this.getPopulator(connection, lowLevelQuery); + connection = this.dataSource.getConnection(); - ArrayListQuery query = null; + return this.getAll(lowLevelQuery, connection); - try { + } finally { + DBUtils.closeConnection(connection); + } + } - query = new ArrayListQuery(connection, false, lowLevelQuery.getSql(), populator); + public List getAll(LowLevelQuery lowLevelQuery, TransactionHandler transactionHandler) throws SQLException { - setCustomQueryParameters(query, lowLevelQuery.getParameters()); + return this.getAll(lowLevelQuery, transactionHandler.getConnection()); + } - ArrayList beans = query.executeQuery(); + public List getAll(LowLevelQuery lowLevelQuery, Connection connection) throws SQLException { - if (beans != null && (RelationQuery.hasRelations(lowLevelQuery) || !autoGetRelations.isEmpty())) { + BeanResultSetPopulator populator = this.getPopulator(connection, lowLevelQuery); - for (T bean : beans) { + ArrayListQuery query = null; - this.populateRelations(bean, connection, lowLevelQuery); - } - } + try { - return beans; + query = new ArrayListQuery(connection, false, lowLevelQuery.getSql(), populator); - } finally { + setCustomQueryParameters(query, lowLevelQuery.getParameters()); - PreparedStatementQuery.autoCloseQuery(query); - } - } + ArrayList beans = query.executeQuery(); - private void setCustomQueryParameters(PreparedStatementQuery query, List parameters) { + if (beans != null && (RelationQuery.hasRelations(lowLevelQuery) || !autoGetRelations.isEmpty())) { - if (parameters != null) { + for (T bean : beans) { - int i = 1; + this.populateRelations(bean, connection, lowLevelQuery); + } + } - for (Object object : parameters) { + return beans; - Method queryMethod; + } finally { - if (object == null) { + PreparedStatementQuery.autoCloseQuery(query); + } + } - queryMethod = PreparedStatementQueryMethods.getObjectQueryMethod(); + private void setCustomQueryParameters(PreparedStatementQuery query, List parameters) { - } else if(object.getClass().isEnum()){ + if (parameters != null) { - object = object.toString(); + int i = 1; - queryMethod = PreparedStatementQueryMethods.getQueryMethod(String.class); + for (Object object : parameters) { - }else { + Method queryMethod; - queryMethod = PreparedStatementQueryMethods.getQueryMethod(object.getClass()); - } + if (object == null) { - if (queryMethod == null) { - throw new RuntimeException("Unable to find suitable prepared statement query method for parameter " + object.getClass()); - } + queryMethod = PreparedStatementQueryMethods.getObjectQueryMethod(); - try { - queryMethod.invoke(query, i++, object); + } else if(object.getClass().isEnum()){ - } catch (IllegalArgumentException e) { + object = object.toString(); - throw new RuntimeException(e); + queryMethod = PreparedStatementQueryMethods.getQueryMethod(String.class); - } catch (IllegalAccessException e) { + }else { - throw new RuntimeException(e); + queryMethod = PreparedStatementQueryMethods.getQueryMethod(object.getClass()); + } - } catch (InvocationTargetException e) { + if (queryMethod == null) { + throw new RuntimeException("Unable to find suitable prepared statement query method for parameter " + object.getClass()); + } - throw new RuntimeException(e); - } - } - } - } + try { + queryMethod.invoke(query, i++, object); - protected List getAll(String sql, CustomQueryParameter queryParameter, Connection connection, - RelationQuery relationQuery) throws SQLException { + } catch (IllegalArgumentException e) { - BeanResultSetPopulator populator = this.getPopulator(connection, relationQuery); + throw new RuntimeException(e); - ArrayListQuery query = null; + } catch (IllegalAccessException e) { - try { + throw new RuntimeException(e); - query = new ArrayListQuery(connection, false, sql, populator); + } catch (InvocationTargetException e) { - if (queryParameter.getQueryParameterPopulator() != null) { + throw new RuntimeException(e); + } + } + } + } - queryParameter.getQueryParameterPopulator().populate(query, 1, queryParameter.getParamValue()); + protected List getAll(String sql, CustomQueryParameter queryParameter, Connection connection, + RelationQuery relationQuery) throws SQLException { - } else { + BeanResultSetPopulator populator = this.getPopulator(connection, relationQuery); - try { - queryParameter.getQueryMethod().invoke(query, 1, queryParameter.getParamValue()); + ArrayListQuery query = null; - } catch (IllegalArgumentException e) { + try { - throw new RuntimeException(e); + query = new ArrayListQuery(connection, false, sql, populator); - } catch (IllegalAccessException e) { + if (queryParameter.getQueryParameterPopulator() != null) { - throw new RuntimeException(e); + queryParameter.getQueryParameterPopulator().populate(query, 1, queryParameter.getParamValue()); - } catch (InvocationTargetException e) { + } else { - throw new RuntimeException(e); - } - } + try { + queryParameter.getQueryMethod().invoke(query, 1, queryParameter.getParamValue()); - ArrayList beans = query.executeQuery(); + } catch (IllegalArgumentException e) { - if (beans != null && (RelationQuery.hasRelations(relationQuery) || !autoGetRelations.isEmpty())) { + throw new RuntimeException(e); - for (T bean : beans) { + } catch (IllegalAccessException e) { - this.populateRelations(bean, connection, relationQuery); - } - } + throw new RuntimeException(e); - return beans; + } catch (InvocationTargetException e) { - } finally { + throw new RuntimeException(e); + } + } - PreparedStatementQuery.autoCloseQuery(query); - } - } + ArrayList beans = query.executeQuery(); - public List getAll(HighLevelQuery highLevelQuery) throws SQLException { + if (beans != null && (RelationQuery.hasRelations(relationQuery) || !autoGetRelations.isEmpty())) { - Connection connection = null; + for (T bean : beans) { - try { + this.populateRelations(bean, connection, relationQuery); + } + } - connection = this.dataSource.getConnection(); + return beans; - return this.getAll(highLevelQuery, connection); + } finally { - } finally { - DBUtils.closeConnection(connection); - } - } + PreparedStatementQuery.autoCloseQuery(query); + } + } - public List getAll(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public List getAll(HighLevelQuery highLevelQuery) throws SQLException { - return this.getAll(highLevelQuery, transactionHandler.getConnection()); - } + Connection connection = null; - public List getAll(HighLevelQuery highLevelQuery, Connection connection) - throws SQLException { + try { - BeanResultSetPopulator populator = this.getPopulator(connection, highLevelQuery); + connection = this.dataSource.getConnection(); - ArrayListQuery query = null; + return this.getAll(highLevelQuery, connection); - try { - query = new ArrayListQuery(connection, false, this.getSQL + this.getCriterias(highLevelQuery, true), populator); + } finally { + DBUtils.closeConnection(connection); + } + } - setQueryParameters(query, highLevelQuery, 1); + public List getAll(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { - ArrayList beans = query.executeQuery(); + return this.getAll(highLevelQuery, transactionHandler.getConnection()); + } - if (beans != null && (RelationQuery.hasRelations(highLevelQuery) || !autoGetRelations.isEmpty())) { + public List getAll(HighLevelQuery highLevelQuery, Connection connection) + throws SQLException { - for (T bean : beans) { + BeanResultSetPopulator populator = this.getPopulator(connection, highLevelQuery); - this.populateRelations(bean, connection, highLevelQuery); - } - } + ArrayListQuery query = null; - return beans; + try { + query = new ArrayListQuery(connection, false, this.getSQL + this.getCriterias(highLevelQuery, true), populator); - } finally { + setQueryParameters(query, highLevelQuery, 1); - PreparedStatementQuery.autoCloseQuery(query); - } - } + ArrayList beans = query.executeQuery(); - public List getAll() throws SQLException { + if (beans != null && (RelationQuery.hasRelations(highLevelQuery) || !autoGetRelations.isEmpty())) { - return this.getAll((HighLevelQuery) null); - } + for (T bean : beans) { - public void delete(T bean) throws SQLException { + this.populateRelations(bean, connection, highLevelQuery); + } + } - TransactionHandler transactionHandler = null; + return beans; - try { + } finally { - transactionHandler = new TransactionHandler(dataSource); + PreparedStatementQuery.autoCloseQuery(query); + } + } - this.delete(bean, transactionHandler); + public List getAll() throws SQLException { - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + return this.getAll((HighLevelQuery) null); + } - public void delete(T bean, TransactionHandler transactionHandler) throws SQLException { + public void delete(T bean) throws SQLException { - this.delete(bean, transactionHandler.getConnection()); - } + TransactionHandler transactionHandler = null; - public void delete(T bean, Connection connection) throws SQLException { + try { - UpdateQuery query = null; + transactionHandler = new TransactionHandler(dataSource); - try { + this.delete(bean, transactionHandler); - query = new UpdateQuery(connection, false, this.deleteSQL); + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - IntegerCounter integerCounter = new IntegerCounter(); + public void delete(T bean, TransactionHandler transactionHandler) throws SQLException { - // Keys from SimpleColumns for where statement - this.setQueryValues(bean, query, integerCounter, this.simpleKeys); + this.delete(bean, transactionHandler.getConnection()); + } - // Keys from many to one relations for where statement - this.setQueryValues(bean, query, integerCounter, this.manyToOneRelationKeys.values()); + public void delete(T bean, Connection connection) throws SQLException { - query.executeUpdate(); + UpdateQuery query = null; - } finally { - PreparedStatementQuery.autoCloseQuery(query); - } - } + try { - public void delete(List beans) throws SQLException { + query = new UpdateQuery(connection, false, this.deleteSQL); - TransactionHandler transactionHandler = null; + IntegerCounter integerCounter = new IntegerCounter(); - try { + // Keys from SimpleColumns for where statement + this.setQueryValues(bean, query, integerCounter, this.simpleKeys); - transactionHandler = new TransactionHandler(dataSource); + // Keys from many to one relations for where statement + this.setQueryValues(bean, query, integerCounter, this.manyToOneRelationKeys.values()); - this.delete(beans, transactionHandler); + query.executeUpdate(); - transactionHandler.commit(); - } finally { - TransactionHandler.autoClose(transactionHandler); - } - } + } finally { + PreparedStatementQuery.autoCloseQuery(query); + } + } - public void delete(List beans, TransactionHandler transactionHandler) throws SQLException { + public void delete(List beans) throws SQLException { - this.delete(beans, transactionHandler.getConnection()); - } + TransactionHandler transactionHandler = null; - public void delete(List beans, Connection connection) throws SQLException { - - for(T bean : beans){ - - delete(bean, connection); - } - } - - public Integer delete(HighLevelQuery highLevelQuery) throws SQLException { + try { - Connection connection = null; + transactionHandler = new TransactionHandler(dataSource); - try { + this.delete(beans, transactionHandler); - connection = this.dataSource.getConnection(); + transactionHandler.commit(); + } finally { + TransactionHandler.autoClose(transactionHandler); + } + } - return this.delete(highLevelQuery, connection); + public void delete(List beans, TransactionHandler transactionHandler) throws SQLException { - } finally { - DBUtils.closeConnection(connection); - } - } + this.delete(beans, transactionHandler.getConnection()); + } - public Integer delete(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { + public void delete(List beans, Connection connection) throws SQLException { - return this.delete(highLevelQuery, transactionHandler.getConnection()); - } + for(T bean : beans){ - public Integer delete(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { + delete(bean, connection); + } + } - UpdateQuery query = null; + public Integer delete(HighLevelQuery highLevelQuery) throws SQLException { - try { - query = new UpdateQuery(connection, false, this.deleteByFieldSQL + this.getCriterias(highLevelQuery, false)); + Connection connection = null; - setQueryParameters(query, highLevelQuery, 1); + try { - query.executeUpdate(); + connection = this.dataSource.getConnection(); - return query.getAffectedRows(); + return this.delete(highLevelQuery, connection); - } finally { + } finally { + DBUtils.closeConnection(connection); + } + } - PreparedStatementQuery.autoCloseQuery(query); - } - } + public Integer delete(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { - public boolean deleteWhereNotIn(List beans, TransactionHandler transactionHandler, Field excludedField, QueryParameter... queryParameters) throws SQLException { - return this.deleteWhereNotIn(beans, transactionHandler.getConnection(), excludedField, queryParameters); - } - - public boolean deleteWhereNotIn(List beans, Connection connection, Field excludedField, QueryParameter... queryParameters) - throws SQLException { + return this.delete(highLevelQuery, transactionHandler.getConnection()); + } - // Generate SQL - StringBuilder stringBuilder = new StringBuilder(); + public Integer delete(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { - stringBuilder.append("DELETE FROM "); - stringBuilder.append(tableName); - stringBuilder.append(" WHERE"); + UpdateQuery query = null; - //Filter away any beans that don't have their keys set - ArrayList filteredBeans = new ArrayList(beans); + try { + query = new UpdateQuery(connection, false, this.deleteByFieldSQL + this.getCriterias(highLevelQuery, false)); - Iterator iterator = filteredBeans.iterator(); + setQueryParameters(query, highLevelQuery, 1); - while(iterator.hasNext()){ + query.executeUpdate(); - if(!hasKeysSet(iterator.next())){ + return query.getAffectedRows(); - iterator.remove(); - } - } + } finally { - if(filteredBeans.isEmpty()){ + PreparedStatementQuery.autoCloseQuery(query); + } + } - //No beans left, abort - return false; - } + public boolean deleteWhereNotIn(List beans, TransactionHandler transactionHandler, Field excludedField, QueryParameter... queryParameters) throws SQLException { + return this.deleteWhereNotIn(beans, transactionHandler.getConnection(), excludedField, queryParameters); + } - int beanCount = filteredBeans.size(); + public boolean deleteWhereNotIn(List beans, Connection connection, Field excludedField, QueryParameter... queryParameters) + throws SQLException { - BooleanSignal signal = new BooleanSignal(); + // Generate SQL + StringBuilder stringBuilder = new StringBuilder(); - this.generateColumWhereNotInSQL(this.simpleKeys, excludedField, stringBuilder, beanCount, signal); - this.generateColumWhereNotInSQL(this.manyToOneRelationKeys.values(), excludedField, stringBuilder, beanCount, signal); + stringBuilder.append("DELETE FROM "); + stringBuilder.append(tableName); + stringBuilder.append(" WHERE"); - if (queryParameters != null) { + //Filter away any beans that don't have their keys set + ArrayList filteredBeans = new ArrayList(beans); - for (QueryParameter queryParameter : queryParameters) { + Iterator iterator = filteredBeans.iterator(); - stringBuilder.append(" AND " + queryParameter.getColumn().getColumnName() + " " + queryParameter.getOperator() + " ?"); - } - } + while(iterator.hasNext()){ - UpdateQuery query = null; + if(!hasKeysSet(iterator.next())){ - try { + iterator.remove(); + } + } - query = new UpdateQuery(connection, false, stringBuilder.toString()); + if(filteredBeans.isEmpty()){ - IntegerCounter integerCounter = new IntegerCounter(); + //No beans left, abort + return false; + } - // Keys values from SimpleColumns for where not in statement - this.setQueryValues(filteredBeans, query, integerCounter, this.simpleKeys, excludedField); + int beanCount = filteredBeans.size(); - // Keys values from many to one relations for where not in statement - this.setQueryValues(filteredBeans, query, integerCounter, this.manyToOneRelationKeys.values(), excludedField); + BooleanSignal signal = new BooleanSignal(); - if (queryParameters != null) { + this.generateColumWhereNotInSQL(this.simpleKeys, excludedField, stringBuilder, beanCount, signal); + this.generateColumWhereNotInSQL(this.manyToOneRelationKeys.values(), excludedField, stringBuilder, beanCount, signal); - // Set query param values - this.setQueryParameters(query, new HighLevelQuery(queryParameters), integerCounter.increment()); - } + if (queryParameters != null) { - query.executeUpdate(); + for (QueryParameter queryParameter : queryParameters) { - } finally { - PreparedStatementQuery.autoCloseQuery(query); - } + stringBuilder.append(" AND " + queryParameter.getColumn().getColumnName() + " " + queryParameter.getOperator() + " ?"); + } + } - return true; - } + UpdateQuery query = null; - public Integer getCount(HighLevelQuery highLevelQuery) throws SQLException { + try { - Connection connection = null; + query = new UpdateQuery(connection, false, stringBuilder.toString()); - try { + IntegerCounter integerCounter = new IntegerCounter(); - connection = this.dataSource.getConnection(); + // Keys values from SimpleColumns for where not in statement + this.setQueryValues(filteredBeans, query, integerCounter, this.simpleKeys, excludedField); - return getCount(highLevelQuery, connection); + // Keys values from many to one relations for where not in statement + this.setQueryValues(filteredBeans, query, integerCounter, this.manyToOneRelationKeys.values(), excludedField); - } finally { - DBUtils.closeConnection(connection); - } - } + if (queryParameters != null) { - public Integer getCount(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { + // Set query param values + this.setQueryParameters(query, new HighLevelQuery(queryParameters), integerCounter.increment()); + } - return getCount(highLevelQuery, transactionHandler.getConnection()); - } + query.executeUpdate(); - public Integer getCount(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { + } finally { + PreparedStatementQuery.autoCloseQuery(query); + } - ObjectQuery query = null; + return true; + } - try{ - query = new ObjectQuery(connection, false, "SELECT COUNT(*) FROM " + tableName + this.getCriterias(highLevelQuery, false), IntegerPopulator.getPopulator()); + public Integer getCount(HighLevelQuery highLevelQuery) throws SQLException { - if (highLevelQuery != null && highLevelQuery.getParameters() != null) { + Connection connection = null; - setQueryParameters(query, highLevelQuery, 1); - } + try { - return query.executeQuery(); + connection = this.dataSource.getConnection(); - }finally{ - PreparedStatementQuery.autoCloseQuery(query); - } - } + return getCount(highLevelQuery, connection); - private void generateColumWhereNotInSQL(Collection> keyColumns, Field excludedField, StringBuilder stringBuilder, int beanCount, BooleanSignal signal) { + } finally { + DBUtils.closeConnection(connection); + } + } - for (Column column : keyColumns) { + public Integer getCount(HighLevelQuery highLevelQuery, TransactionHandler transactionHandler) throws SQLException { - if(column.getBeanField().equals(excludedField)) { - continue; - } + return getCount(highLevelQuery, transactionHandler.getConnection()); + } - if (signal.isSignal()) { + public Integer getCount(HighLevelQuery highLevelQuery, Connection connection) throws SQLException { - stringBuilder.append(" AND"); + ObjectQuery query = null; - } else { + try{ + query = new ObjectQuery(connection, false, "SELECT COUNT(*) FROM " + tableName + this.getCriterias(highLevelQuery, false), IntegerPopulator.getPopulator()); - signal.setSignal(true); - } + if (highLevelQuery != null && highLevelQuery.getParameters() != null) { - stringBuilder.append(" "); - stringBuilder.append(column.getColumnName()); - stringBuilder.append(" NOT IN ("); + setQueryParameters(query, highLevelQuery, 1); + } - this.addQuestionMarks(beanCount, stringBuilder); + return query.executeQuery(); - stringBuilder.append(")"); - } + }finally{ + PreparedStatementQuery.autoCloseQuery(query); + } + } - } + private void generateColumWhereNotInSQL(Collection> keyColumns, Field excludedField, StringBuilder stringBuilder, int beanCount, BooleanSignal signal) { - private void addQuestionMarks(int size, StringBuilder stringBuilder) { + for (Column column : keyColumns) { - stringBuilder.append("?"); + if(column.getBeanField().equals(excludedField)) { + continue; + } - if (size > 1) { + if (signal.isSignal()) { - for (int i = 2; i <= size; i++) { + stringBuilder.append(" AND"); - stringBuilder.append(",?"); - } - } - } + } else { - public QueryParameterFactory getParamFactory(Field field, Class paramClass) { + signal.setSignal(true); + } - return new QueryParameterFactory(this.getColumn(field, paramClass)); - } + stringBuilder.append(" "); + stringBuilder.append(column.getColumnName()); + stringBuilder.append(" NOT IN ("); - public QueryParameterFactory getParamFactory(String fieldName, Class paramClass) { + this.addQuestionMarks(beanCount, stringBuilder); - Field field = ReflectionUtils.getField(beanClass, fieldName); + stringBuilder.append(")"); + } - if (field == null) { - throw new RuntimeException("Field " + fieldName + " not found in " + this.beanClass + "!"); - } + } - return new QueryParameterFactory(this.getColumn(field, paramClass)); - } + private void addQuestionMarks(int size, StringBuilder stringBuilder) { - public OrderByCriteria getOrderByCriteria(Field field, Order order) { + stringBuilder.append("?"); - Column column = this.columnMap.get(field); + if (size > 1) { - if (column == null) { - throw new RuntimeException("No @DAOManaged annotated field with name " + field.getName() + " not found in " + this.beanClass + "!"); - } + for (int i = 2; i <= size; i++) { - return new OrderByCriteria(order, column); - } + stringBuilder.append(",?"); + } + } + } - public OrderByCriteria getOrderByCriteria(String fieldName, Order order) { + public QueryParameterFactory getParamFactory(Field field, Class paramClass) { - Field field = ReflectionUtils.getField(beanClass, fieldName); + return new QueryParameterFactory(this.getColumn(field, paramClass)); + } - if (field == null) { - throw new RuntimeException("Field " + fieldName + " not found in " + this.beanClass + "!"); - } + public QueryParameterFactory getParamFactory(String fieldName, Class paramClass) { - return this.getOrderByCriteria(field, order); - } + Field field = ReflectionUtils.getField(beanClass, fieldName); - public String getTableName() { + if (field == null) { + throw new RuntimeException("Field " + fieldName + " not found in " + this.beanClass + "!"); + } - return tableName; - } + return new QueryParameterFactory(this.getColumn(field, paramClass)); + } - Column getColumn(Field field) { + public OrderByCriteria getOrderByCriteria(Field field, Order order) { - return this.columnMap.get(field); - } + Column column = this.columnMap.get(field); - public void setQueryParameters(PreparedStatementQuery query, HighLevelQuery highLevelQuery, final int startIndex) throws SQLException { + if (column == null) { + throw new RuntimeException("No @DAOManaged annotated field with name " + field.getName() + " not found in " + this.beanClass + "!"); + } - if (highLevelQuery != null && highLevelQuery.getParameters() != null) { + return new OrderByCriteria(order, column); + } - int index = startIndex; + public OrderByCriteria getOrderByCriteria(String fieldName, Order order) { - for (QueryParameter queryParameter : highLevelQuery.getParameters()) { + Field field = ReflectionUtils.getField(beanClass, fieldName); - if (queryParameter.hasValues()) { + if (field == null) { + throw new RuntimeException("Field " + fieldName + " not found in " + this.beanClass + "!"); + } - if (queryParameter.hasMultipleValues()) { + return this.getOrderByCriteria(field, order); + } - for (Object value : queryParameter.getValues()) { + public String getTableName() { - setQueryParameter(queryParameter, value, query, index++); - } + return tableName; + } - } else { + Column getColumn(Field field) { - setQueryParameter(queryParameter, queryParameter.getValue(), query, index++); - } - } - } - } - } + return this.columnMap.get(field); + } - private void setQueryParameter(QueryParameter queryParameter, Object value, PreparedStatementQuery query, int index) throws SQLException { + public void setQueryParameters(PreparedStatementQuery query, HighLevelQuery highLevelQuery, final int startIndex) throws SQLException { - Column column = queryParameter.getColumn(); + if (highLevelQuery != null && highLevelQuery.getParameters() != null) { - if (column.getQueryParameterPopulator() != null) { + int index = startIndex; - column.getQueryParameterPopulator().populate(query, index, column.getParamValue(value)); + for (QueryParameter queryParameter : highLevelQuery.getParameters()) { - } else { + if (queryParameter.hasValues()) { - try { - column.getQueryMethod().invoke(query, index, column.getParamValue(value)); + if (queryParameter.hasMultipleValues()) { - } catch (IllegalArgumentException e) { + for (Object value : queryParameter.getValues()) { - throw new RuntimeException(e); + setQueryParameter(queryParameter, value, query, index++); + } - } catch (IllegalAccessException e) { + } else { - throw new RuntimeException(e); + setQueryParameter(queryParameter, queryParameter.getValue(), query, index++); + } + } + } + } + } - } catch (InvocationTargetException e) { + private void setQueryParameter(QueryParameter queryParameter, Object value, PreparedStatementQuery query, int index) throws SQLException { - throw new RuntimeException(e); - } - } - } + Column column = queryParameter.getColumn(); - - public Class getBeanClass() { - - return beanClass; - } + if (column.getQueryParameterPopulator() != null) { + + column.getQueryParameterPopulator().populate(query, index, column.getParamValue(value)); + + } else { + + try { + column.getQueryMethod().invoke(query, index, column.getParamValue(value)); + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + + } catch (InvocationTargetException e) { + + throw new RuntimeException(e); + } + } + } + + + public Class getBeanClass() { + + return beanClass; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAOFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAOFactory.java index c1d63eacee4..dd0110a7f60 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAOFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/AnnotatedDAOFactory.java @@ -12,5 +12,5 @@ public interface AnnotatedDAOFactory { - AnnotatedDAO getDAO(Class beanClass); + AnnotatedDAO getDAO(Class beanClass); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanChainPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanChainPopulator.java index 0054f95cce3..15db5059e2d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanChainPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanChainPopulator.java @@ -7,25 +7,25 @@ public class BeanChainPopulator implements BeanResultSetPopulator { - protected BeanResultSetPopulator populator; - protected List> chainedResultSetPopulators; - - public BeanChainPopulator(List> chainedResultSetPopulators, BeanResultSetPopulator populator) { - - super(); - this.populator = populator; - this.chainedResultSetPopulators = chainedResultSetPopulators; - } - - public T populate(ResultSet rs) throws SQLException { - - T bean = populator.populate(rs); - - for(ChainedResultSetPopulator chainedPopulator : chainedResultSetPopulators){ - - chainedPopulator.populate(bean, rs); - } - - return bean; - } + protected BeanResultSetPopulator populator; + protected List> chainedResultSetPopulators; + + public BeanChainPopulator(List> chainedResultSetPopulators, BeanResultSetPopulator populator) { + + super(); + this.populator = populator; + this.chainedResultSetPopulators = chainedResultSetPopulators; + } + + public T populate(ResultSet rs) throws SQLException { + + T bean = populator.populate(rs); + + for(ChainedResultSetPopulator chainedPopulator : chainedResultSetPopulators){ + + chainedPopulator.populate(bean, rs); + } + + return bean; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanRelationPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanRelationPopulator.java index aaaacfd737b..6e0857e2ea5 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanRelationPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanRelationPopulator.java @@ -15,33 +15,33 @@ public class BeanRelationPopulator implements BeanResultSetPopulator{ - private BeanResultSetPopulator populator; - private List> manyToOneRelations; - private Connection connection; - private RelationQuery relationQuery; + private BeanResultSetPopulator populator; + private List> manyToOneRelations; + private Connection connection; + private RelationQuery relationQuery; - public BeanRelationPopulator(BeanResultSetPopulator populator, List> manyToOneRelations, Connection connection, RelationQuery relationQuery) { - super(); - this.populator = populator; - this.manyToOneRelations = manyToOneRelations; - this.connection = connection; - this.relationQuery = relationQuery; - } + public BeanRelationPopulator(BeanResultSetPopulator populator, List> manyToOneRelations, Connection connection, RelationQuery relationQuery) { + super(); + this.populator = populator; + this.manyToOneRelations = manyToOneRelations; + this.connection = connection; + this.relationQuery = relationQuery; + } - public T populate(ResultSet rs) throws SQLException { + public T populate(ResultSet rs) throws SQLException { - T bean = populator.populate(rs); + T bean = populator.populate(rs); - if(bean != null){ + if(bean != null){ - for(ManyToOneRelation relation : manyToOneRelations){ + for(ManyToOneRelation relation : manyToOneRelations){ - relation.getRemoteValue(bean, rs, connection, relationQuery); - } - } + relation.getRemoteValue(bean, rs, connection, relationQuery); + } + } - return bean; - } + return bean; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanResultSetPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanResultSetPopulator.java index 9eefb86e60c..3a3b48fe4be 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanResultSetPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/BeanResultSetPopulator.java @@ -11,5 +11,5 @@ import java.sql.SQLException; public interface BeanResultSetPopulator { - ReturnType populate(ResultSet rs) throws SQLException; + ReturnType populate(ResultSet rs) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/ChainedResultSetPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/ChainedResultSetPopulator.java index dd2b9fc642f..96a3047afe0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/ChainedResultSetPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/ChainedResultSetPopulator.java @@ -6,5 +6,5 @@ public interface ChainedResultSetPopulator { - void populate(T bean, ResultSet resultSet) throws SQLException; + void populate(T bean, ResultSet resultSet) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/Column.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/Column.java index a0dc1268bc2..e4a69fe7a81 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/Column.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/Column.java @@ -14,20 +14,20 @@ public interface Column { - Field getBeanField(); + Field getBeanField(); - Class getParamType(); + Class getParamType(); - Object getParamValue(Object param); + Object getParamValue(Object param); - Object getBeanValue(BeanType bean); + Object getBeanValue(BeanType bean); - Method getQueryMethod(); + Method getQueryMethod(); - String getColumnName(); + String getColumnName(); - boolean isAutoGenerated(); + boolean isAutoGenerated(); - QueryParameterPopulator getQueryParameterPopulator(); + QueryParameterPopulator getQueryParameterPopulator(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollector.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollector.java index e151eac3a8d..ae08acff521 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollector.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollector.java @@ -17,54 +17,54 @@ public class ColumnKeyCollector { - private final ResultSetField resultSetField; - private final int columnIndex; + private final ResultSetField resultSetField; + private final int columnIndex; - public ColumnKeyCollector(Field field, AnnotatedResultSetPopulator populator, int columnIndex) { + public ColumnKeyCollector(Field field, AnnotatedResultSetPopulator populator, int columnIndex) { - this.resultSetField = populator.getResultSetField(field); - this.columnIndex = columnIndex; - } + this.resultSetField = populator.getResultSetField(field); + this.columnIndex = columnIndex; + } - public void collect(T bean, ResultSet rs) throws SQLException { + public void collect(T bean, ResultSet rs) throws SQLException { - try { - if(resultSetField.getResultSetColumnIndexMethod() != null){ + try { + if(resultSetField.getResultSetColumnIndexMethod() != null){ - Object value = resultSetField.getResultSetColumnIndexMethod().invoke(rs, columnIndex); + Object value = resultSetField.getResultSetColumnIndexMethod().invoke(rs, columnIndex); - if(value == null && !resultSetField.getBeanField().getType().isPrimitive()){ + if(value == null && !resultSetField.getBeanField().getType().isPrimitive()){ - resultSetField.getBeanField().set(bean, null); + resultSetField.getBeanField().set(bean, null); - }else{ + }else{ - resultSetField.getBeanField().set(bean, value); - } + resultSetField.getBeanField().set(bean, value); + } - }else{ + }else{ - String value = rs.getString(columnIndex); + String value = rs.getString(columnIndex); - if(value != null || resultSetField.getBeanStringPopulator().getType().isPrimitive()){ + if(value != null || resultSetField.getBeanStringPopulator().getType().isPrimitive()){ - resultSetField.getBeanField().set(bean, resultSetField.getBeanStringPopulator().getValue(value)); - }else{ - resultSetField.getBeanField().set(bean, null); - } - } + resultSetField.getBeanField().set(bean, resultSetField.getBeanStringPopulator().getValue(value)); + }else{ + resultSetField.getBeanField().set(bean, null); + } + } - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (InvocationTargetException e) { + } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollectorWrapper.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollectorWrapper.java index 87395eab669..e2c54c797dc 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollectorWrapper.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/ColumnKeyCollectorWrapper.java @@ -16,20 +16,20 @@ public class ColumnKeyCollectorWrapper implements GeneratedKeyCollector { - private ArrayList> columnKeyCollectors; - private T bean; + private ArrayList> columnKeyCollectors; + private T bean; - public ColumnKeyCollectorWrapper(ArrayList> columnKeyCollectors, T bean) { + public ColumnKeyCollectorWrapper(ArrayList> columnKeyCollectors, T bean) { - this.columnKeyCollectors = columnKeyCollectors; - this.bean = bean; - } + this.columnKeyCollectors = columnKeyCollectors; + this.bean = bean; + } - public void collect(ResultSet rs) throws SQLException { + public void collect(ResultSet rs) throws SQLException { - for(ColumnKeyCollector keyCollector : columnKeyCollectors){ + for(ColumnKeyCollector keyCollector : columnKeyCollectors){ - keyCollector.collect(bean, rs); - } - } + keyCollector.collect(bean, rs); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/CustomQueryParameter.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/CustomQueryParameter.java index ee5d98d7d48..58c94c2f327 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/CustomQueryParameter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/CustomQueryParameter.java @@ -13,30 +13,30 @@ public class CustomQueryParameter{ - private QueryParameterPopulator queryParameterPopulator; - private Method queryMethod; - private Object paramValue; + private QueryParameterPopulator queryParameterPopulator; + private Method queryMethod; + private Object paramValue; - public CustomQueryParameter(Column column , T bean) { + public CustomQueryParameter(Column column , T bean) { - super(); - this.queryParameterPopulator = column.getQueryParameterPopulator(); - this.queryMethod = column.getQueryMethod(); - this.paramValue = column.getBeanValue(bean); - } + super(); + this.queryParameterPopulator = column.getQueryParameterPopulator(); + this.queryMethod = column.getQueryMethod(); + this.paramValue = column.getBeanValue(bean); + } - public QueryParameterPopulator getQueryParameterPopulator() { + public QueryParameterPopulator getQueryParameterPopulator() { - return queryParameterPopulator; - } + return queryParameterPopulator; + } - public Method getQueryMethod() { + public Method getQueryMethod() { - return queryMethod; - } + return queryMethod; + } - public Object getParamValue() { + public Object getParamValue() { - return paramValue; - } + return paramValue; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToManyRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToManyRelation.java index 6e1daad63a5..fb7de20d703 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToManyRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToManyRelation.java @@ -24,346 +24,346 @@ public class DefaultManyToManyRelation implements ManyToManyRelation { - private final Field field; - private final Field localKeyField; - private final Field remoteKeyField; - - private final String linkTable; - private final String localLinkTableColumnName; - private final String remoteKeyColumnName; - private final String remoteLinkTableColumnName; - - private String linkTableLinkSQL; - private String linkTableDeleteSQL; - private String linkTableInsertSQL; - - private Column localColumn; - private Column remoteColumn; - - private final AnnotatedDAOFactory daoFactory; - private AnnotatedDAO annotatedDAO; - private final Class beanClass; - private final Class remoteClass; - - private boolean initialized; - - public DefaultManyToManyRelation(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged) { - super(); - this.beanClass = beanClass; - this.remoteClass = remoteClass; - this.field = field; - this.daoFactory = daoFactory; - - - //Validate linkTable name - ManyToMany localAnnotation = field.getAnnotation(ManyToMany.class); - - this.linkTable = localAnnotation.linkTable(); - - //Get remote field - Field matchingRemoteField = null; - - Field[] fields = remoteClass.getDeclaredFields(); - - for(Field remoteField : fields){ - - if(ReflectionUtils.getGenericlyTypeCount(remoteField) == 1 && ReflectionUtils.getGenericType(remoteField).equals(beanClass) && remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(ManyToMany.class) && remoteField.getAnnotation(ManyToMany.class).linkTable().equals(linkTable)){ - - matchingRemoteField = remoteField; - - break; - } - - } - - if(matchingRemoteField == null){ - - throw new RuntimeException("Unable to to find corresponding @ManyToMany field in " + remoteClass + " while parsing field " + field.getName() + " in " + beanClass); - } - - //Get remote annotation - ManyToMany remoteAnnotation = matchingRemoteField.getAnnotation(ManyToMany.class); - - //Get local key field - this.localKeyField = getKeyField(localAnnotation, beanClass, field); - - //Get local localColumn name - this.localLinkTableColumnName = getColumnName(daoManaged, localKeyField); - - //Get remote key field - remoteKeyField = getKeyField(remoteAnnotation, remoteClass, matchingRemoteField); - - //Get remote localColumn name - this.remoteLinkTableColumnName = getColumnName(remoteKeyField.getAnnotation(DAOManaged.class), remoteKeyField); - - String remoteColumnName = remoteKeyField.getAnnotation(DAOManaged.class).columnName(); - - //Get remote table localColumn name - if(!StringUtils.isEmpty(remoteColumnName)){ - - this.remoteKeyColumnName = remoteColumnName; - - }else{ - - this.remoteKeyColumnName = remoteKeyField.getName(); - } - - this.linkTableDeleteSQL = "DELETE FROM " + linkTable + " WHERE " + localLinkTableColumnName + " = ?"; - this.linkTableInsertSQL = "INSERT INTO " + linkTable + " (" + localLinkTableColumnName + "," + remoteLinkTableColumnName + ") VALUES (?,?)"; - - } - - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToManyRelation#setValue(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - public void getRemoteValue(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - - try { - if(!initialized){ - init(); - } - - CustomQueryParameter queryParameter = new CustomQueryParameter(localColumn, bean); - - if(queryParameter.getParamValue() != null){ - - field.set(bean, annotatedDAO.getAll(linkTableLinkSQL, queryParameter, connection, relationQuery)); - } - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - } - } - - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToManyRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - @SuppressWarnings("unchecked") - public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - - //TODO cascading add like OneToMany relations - - try { - if(!initialized){ - init(); - } - - //Check if there are any relations to set - List remoteBeans = (List) field.get(bean); - - if(remoteBeans == null){ - - return; - } - - for(RemoteType remoteBean : remoteBeans){ - - //Set new relations - UpdateQuery insertQuery; - - insertQuery = new UpdateQuery(connection, false, linkTableInsertSQL); - - setQueryParameter(insertQuery, this.localColumn, bean, 1); - setQueryParameter(insertQuery, this.remoteColumn, remoteBean, 2); - - insertQuery.executeUpdate(); - } - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - } - } - - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToManyRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - @SuppressWarnings("unchecked") - public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - - //TODO cascading add like OneToMany relations - - try { - if(!initialized){ - init(); - } - - //Clear old relations - UpdateQuery deleteQuery; - - deleteQuery = new UpdateQuery(connection, false, linkTableDeleteSQL); - - setQueryParameter(deleteQuery, this.localColumn, bean, 1); - - deleteQuery.executeUpdate(); - - //Check if there are any new relations to set - List remoteBeans = (List) field.get(bean); - - if(remoteBeans == null){ - - return; - } - - for(RemoteType remoteBean : remoteBeans){ - - //Set new relations - UpdateQuery insertQuery; - - insertQuery = new UpdateQuery(connection, false, linkTableInsertSQL); - - setQueryParameter(insertQuery, this.localColumn, bean, 1); - setQueryParameter(insertQuery, this.remoteColumn, remoteBean, 2); - - insertQuery.executeUpdate(); - } - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - } - } - - private void init() { - - if(annotatedDAO == null){ - annotatedDAO = this.daoFactory.getDAO(remoteClass); - } - - if(this.linkTableLinkSQL == null){ - this.linkTableLinkSQL = "SELECT " + annotatedDAO.getTableName() + ".* FROM " + annotatedDAO.getTableName() + " INNER JOIN " + linkTable + " ON (" + annotatedDAO.getTableName() + "." + remoteKeyColumnName + "=" + linkTable + "." + remoteLinkTableColumnName + ") WHERE " + linkTable + "." + localLinkTableColumnName + " = ?"; - } - - if(this.localColumn == null){ - this.localColumn = this.daoFactory.getDAO(beanClass).getColumn(this.localKeyField); - } - - if(this.remoteColumn == null){ - this.remoteColumn = this.annotatedDAO.getColumn(remoteKeyField); - } - - this.initialized = true; - } - - private static void setQueryParameter(UpdateQuery query, Column column, Type bean, int index) throws SQLException{ - - if(column.getQueryParameterPopulator() != null){ - - column.getQueryParameterPopulator().populate(query, index, column.getBeanValue(bean)); - - }else{ - - try { - column.getQueryMethod().invoke(query, index, column.getBeanValue(bean)); - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - - } catch (InvocationTargetException e) { - - throw new RuntimeException(e); - } - } - } - - public static Field getKeyField(ManyToMany manyToManyAnnotation, Class clazz, Field annotatedField){ - - if(!StringUtils.isEmpty(manyToManyAnnotation.keyField())){ - - try { - Field keyField = clazz.getDeclaredField(manyToManyAnnotation.keyField()); - - DAOManaged keyDAOPopulate = keyField.getAnnotation(DAOManaged.class); - - if(keyDAOPopulate == null){ - - throw new RuntimeException("Specified keyField " + manyToManyAnnotation.keyField() + " for @ManyToMany annotation for field " + annotatedField.getName() + " in " + clazz + " is missing the @DAOManaged annotation"); - } - - return keyField; - - - } catch (SecurityException e) { - - throw new RuntimeException("Unable to find specified keyField " + manyToManyAnnotation.keyField() + " for @ManyToMany annotation for field " + annotatedField.getName() + " in " + clazz); - - } catch (NoSuchFieldException e) { - - throw new RuntimeException("Unable to find specified keyField " + manyToManyAnnotation.keyField() + " for @ManyToMany annotation for field " + annotatedField.getName() + " in " + clazz); - } - - }else{ - - ArrayList keyFields = getKeyFields(clazz); - - if(keyFields.size() == 0){ - - throw new RuntimeException("Unable to find any @Key annotated fields in " + clazz); - - }else if(keyFields.size() > 1){ - - throw new RuntimeException("keyField needs to be specified for @ManyToMany annotated field " + annotatedField.getName() + " in " + clazz + " since the class contains multiple @Key annotated fields"); - } - - return keyFields.get(0); - } - } - - public static ArrayList getKeyFields(Class clazz){ - - ArrayList keyFields = new ArrayList(); - - Field[] fields = clazz.getDeclaredFields(); - - for(Field field : fields){ - - if(field.isAnnotationPresent(Key.class) && field.isAnnotationPresent(DAOManaged.class)){ - - keyFields.add(field); - } - } - - return keyFields; - } - - private static String getColumnName(DAOManaged manyToManyDAOPopulate, Field keyField){ - - String keyColumnName; - - if(!StringUtils.isEmpty(manyToManyDAOPopulate.columnName())){ - - return manyToManyDAOPopulate.columnName(); - - }else if(!StringUtils.isEmpty(keyColumnName = keyField.getAnnotation(DAOManaged.class).columnName())){ - - return keyColumnName; - - }else{ - - return keyField.getName(); - } - } - - public static ManyToManyRelation getGenericInstance(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged){ - - return new DefaultManyToManyRelation(beanClass,remoteClass,field,daoFactory,daoManaged); - } + private final Field field; + private final Field localKeyField; + private final Field remoteKeyField; + + private final String linkTable; + private final String localLinkTableColumnName; + private final String remoteKeyColumnName; + private final String remoteLinkTableColumnName; + + private String linkTableLinkSQL; + private String linkTableDeleteSQL; + private String linkTableInsertSQL; + + private Column localColumn; + private Column remoteColumn; + + private final AnnotatedDAOFactory daoFactory; + private AnnotatedDAO annotatedDAO; + private final Class beanClass; + private final Class remoteClass; + + private boolean initialized; + + public DefaultManyToManyRelation(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged) { + super(); + this.beanClass = beanClass; + this.remoteClass = remoteClass; + this.field = field; + this.daoFactory = daoFactory; + + + //Validate linkTable name + ManyToMany localAnnotation = field.getAnnotation(ManyToMany.class); + + this.linkTable = localAnnotation.linkTable(); + + //Get remote field + Field matchingRemoteField = null; + + Field[] fields = remoteClass.getDeclaredFields(); + + for(Field remoteField : fields){ + + if(ReflectionUtils.getGenericlyTypeCount(remoteField) == 1 && ReflectionUtils.getGenericType(remoteField).equals(beanClass) && remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(ManyToMany.class) && remoteField.getAnnotation(ManyToMany.class).linkTable().equals(linkTable)){ + + matchingRemoteField = remoteField; + + break; + } + + } + + if(matchingRemoteField == null){ + + throw new RuntimeException("Unable to to find corresponding @ManyToMany field in " + remoteClass + " while parsing field " + field.getName() + " in " + beanClass); + } + + //Get remote annotation + ManyToMany remoteAnnotation = matchingRemoteField.getAnnotation(ManyToMany.class); + + //Get local key field + this.localKeyField = getKeyField(localAnnotation, beanClass, field); + + //Get local localColumn name + this.localLinkTableColumnName = getColumnName(daoManaged, localKeyField); + + //Get remote key field + remoteKeyField = getKeyField(remoteAnnotation, remoteClass, matchingRemoteField); + + //Get remote localColumn name + this.remoteLinkTableColumnName = getColumnName(remoteKeyField.getAnnotation(DAOManaged.class), remoteKeyField); + + String remoteColumnName = remoteKeyField.getAnnotation(DAOManaged.class).columnName(); + + //Get remote table localColumn name + if(!StringUtils.isEmpty(remoteColumnName)){ + + this.remoteKeyColumnName = remoteColumnName; + + }else{ + + this.remoteKeyColumnName = remoteKeyField.getName(); + } + + this.linkTableDeleteSQL = "DELETE FROM " + linkTable + " WHERE " + localLinkTableColumnName + " = ?"; + this.linkTableInsertSQL = "INSERT INTO " + linkTable + " (" + localLinkTableColumnName + "," + remoteLinkTableColumnName + ") VALUES (?,?)"; + + } + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToManyRelation#setValue(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + public void getRemoteValue(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + + try { + if(!initialized){ + init(); + } + + CustomQueryParameter queryParameter = new CustomQueryParameter(localColumn, bean); + + if(queryParameter.getParamValue() != null){ + + field.set(bean, annotatedDAO.getAll(linkTableLinkSQL, queryParameter, connection, relationQuery)); + } + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToManyRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + @SuppressWarnings("unchecked") + public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + + //TODO cascading add like OneToMany relations + + try { + if(!initialized){ + init(); + } + + //Check if there are any relations to set + List remoteBeans = (List) field.get(bean); + + if(remoteBeans == null){ + + return; + } + + for(RemoteType remoteBean : remoteBeans){ + + //Set new relations + UpdateQuery insertQuery; + + insertQuery = new UpdateQuery(connection, false, linkTableInsertSQL); + + setQueryParameter(insertQuery, this.localColumn, bean, 1); + setQueryParameter(insertQuery, this.remoteColumn, remoteBean, 2); + + insertQuery.executeUpdate(); + } + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToManyRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + @SuppressWarnings("unchecked") + public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + + //TODO cascading add like OneToMany relations + + try { + if(!initialized){ + init(); + } + + //Clear old relations + UpdateQuery deleteQuery; + + deleteQuery = new UpdateQuery(connection, false, linkTableDeleteSQL); + + setQueryParameter(deleteQuery, this.localColumn, bean, 1); + + deleteQuery.executeUpdate(); + + //Check if there are any new relations to set + List remoteBeans = (List) field.get(bean); + + if(remoteBeans == null){ + + return; + } + + for(RemoteType remoteBean : remoteBeans){ + + //Set new relations + UpdateQuery insertQuery; + + insertQuery = new UpdateQuery(connection, false, linkTableInsertSQL); + + setQueryParameter(insertQuery, this.localColumn, bean, 1); + setQueryParameter(insertQuery, this.remoteColumn, remoteBean, 2); + + insertQuery.executeUpdate(); + } + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + + private void init() { + + if(annotatedDAO == null){ + annotatedDAO = this.daoFactory.getDAO(remoteClass); + } + + if(this.linkTableLinkSQL == null){ + this.linkTableLinkSQL = "SELECT " + annotatedDAO.getTableName() + ".* FROM " + annotatedDAO.getTableName() + " INNER JOIN " + linkTable + " ON (" + annotatedDAO.getTableName() + "." + remoteKeyColumnName + "=" + linkTable + "." + remoteLinkTableColumnName + ") WHERE " + linkTable + "." + localLinkTableColumnName + " = ?"; + } + + if(this.localColumn == null){ + this.localColumn = this.daoFactory.getDAO(beanClass).getColumn(this.localKeyField); + } + + if(this.remoteColumn == null){ + this.remoteColumn = this.annotatedDAO.getColumn(remoteKeyField); + } + + this.initialized = true; + } + + private static void setQueryParameter(UpdateQuery query, Column column, Type bean, int index) throws SQLException{ + + if(column.getQueryParameterPopulator() != null){ + + column.getQueryParameterPopulator().populate(query, index, column.getBeanValue(bean)); + + }else{ + + try { + column.getQueryMethod().invoke(query, index, column.getBeanValue(bean)); + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + + } catch (InvocationTargetException e) { + + throw new RuntimeException(e); + } + } + } + + public static Field getKeyField(ManyToMany manyToManyAnnotation, Class clazz, Field annotatedField){ + + if(!StringUtils.isEmpty(manyToManyAnnotation.keyField())){ + + try { + Field keyField = clazz.getDeclaredField(manyToManyAnnotation.keyField()); + + DAOManaged keyDAOPopulate = keyField.getAnnotation(DAOManaged.class); + + if(keyDAOPopulate == null){ + + throw new RuntimeException("Specified keyField " + manyToManyAnnotation.keyField() + " for @ManyToMany annotation for field " + annotatedField.getName() + " in " + clazz + " is missing the @DAOManaged annotation"); + } + + return keyField; + + + } catch (SecurityException e) { + + throw new RuntimeException("Unable to find specified keyField " + manyToManyAnnotation.keyField() + " for @ManyToMany annotation for field " + annotatedField.getName() + " in " + clazz); + + } catch (NoSuchFieldException e) { + + throw new RuntimeException("Unable to find specified keyField " + manyToManyAnnotation.keyField() + " for @ManyToMany annotation for field " + annotatedField.getName() + " in " + clazz); + } + + }else{ + + ArrayList keyFields = getKeyFields(clazz); + + if(keyFields.size() == 0){ + + throw new RuntimeException("Unable to find any @Key annotated fields in " + clazz); + + }else if(keyFields.size() > 1){ + + throw new RuntimeException("keyField needs to be specified for @ManyToMany annotated field " + annotatedField.getName() + " in " + clazz + " since the class contains multiple @Key annotated fields"); + } + + return keyFields.get(0); + } + } + + public static ArrayList getKeyFields(Class clazz){ + + ArrayList keyFields = new ArrayList(); + + Field[] fields = clazz.getDeclaredFields(); + + for(Field field : fields){ + + if(field.isAnnotationPresent(Key.class) && field.isAnnotationPresent(DAOManaged.class)){ + + keyFields.add(field); + } + } + + return keyFields; + } + + private static String getColumnName(DAOManaged manyToManyDAOPopulate, Field keyField){ + + String keyColumnName; + + if(!StringUtils.isEmpty(manyToManyDAOPopulate.columnName())){ + + return manyToManyDAOPopulate.columnName(); + + }else if(!StringUtils.isEmpty(keyColumnName = keyField.getAnnotation(DAOManaged.class).columnName())){ + + return keyColumnName; + + }else{ + + return keyField.getName(); + } + } + + public static ManyToManyRelation getGenericInstance(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged){ + + return new DefaultManyToManyRelation(beanClass,remoteClass,field,daoFactory,daoManaged); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToOneRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToOneRelation.java index 743e6a7f33c..b192bc94fa1 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToOneRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultManyToOneRelation.java @@ -24,287 +24,287 @@ public class DefaultManyToOneRelation implements ManyToOneRelation{ - private final String columnName; - private final Field field; - private QueryParameterPopulator queryParameterPopulator; - private Method queryMethod; - private final BeanResultSetPopulator remoteKeyPopulator; - private final Field remoteKeyField; + private final String columnName; + private final Field field; + private QueryParameterPopulator queryParameterPopulator; + private Method queryMethod; + private final BeanResultSetPopulator remoteKeyPopulator; + private final Field remoteKeyField; - private final AnnotatedDAOFactory daoFactory; - private AnnotatedDAO annotatedDAO; - private QueryParameterFactory queryParameterFactory; - private final Class remoteClass; - private final Class remoteRemoteKeyClass; + private final AnnotatedDAOFactory daoFactory; + private AnnotatedDAO annotatedDAO; + private QueryParameterFactory queryParameterFactory; + private final Class remoteClass; + private final Class remoteRemoteKeyClass; - private boolean initialized; + private boolean initialized; - public DefaultManyToOneRelation(Class beanClass, Class remoteClass, Class remoteKeyClass, Field field, Field remoteKeyField, DAOManaged daoManaged, AnnotatedDAOFactory daoFactory) { + public DefaultManyToOneRelation(Class beanClass, Class remoteClass, Class remoteKeyClass, Field field, Field remoteKeyField, DAOManaged daoManaged, AnnotatedDAOFactory daoFactory) { - this.remoteClass = remoteClass; - this.remoteRemoteKeyClass = remoteKeyClass; - this.field = field; - this.remoteKeyField = remoteKeyField; - this.daoFactory = daoFactory; + this.remoteClass = remoteClass; + this.remoteRemoteKeyClass = remoteKeyClass; + this.field = field; + this.remoteKeyField = remoteKeyField; + this.daoFactory = daoFactory; - if(!StringUtils.isEmpty(daoManaged.columnName())){ - this.columnName = daoManaged.columnName(); - }else{ - this.columnName = field.getName(); - } + if(!StringUtils.isEmpty(daoManaged.columnName())){ + this.columnName = daoManaged.columnName(); + }else{ + this.columnName = field.getName(); + } - ReflectionUtils.fixFieldAccess(remoteKeyField); + ReflectionUtils.fixFieldAccess(remoteKeyField); - //TODO use column instead! somehow... - Method resultSetMethod = ResultSetMethods.getColumnNameMethod(remoteKeyClass); + //TODO use column instead! somehow... + Method resultSetMethod = ResultSetMethods.getColumnNameMethod(remoteKeyClass); - if(resultSetMethod != null){ - - remoteKeyPopulator = new MethodBasedResultSetPopulator(resultSetMethod, columnName); - - }else{ - - BeanStringPopulator typePopulator = BeanStringPopulatorRegistery.getBeanStringPopulator(remoteKeyClass); - - if(typePopulator != null){ - - remoteKeyPopulator = new TypeBasedResultSetPopulator(typePopulator, columnName); - }else{ + if(resultSetMethod != null){ - throw new UnsupportedFieldTypeException("Unable to find resultset method or type populator for field " + remoteKeyField.getName() + " in " + remoteClass + " when creating many to one relation for field " + field.getName() + " in " + beanClass, field, ManyToOne.class, beanClass); - } - } - } + remoteKeyPopulator = new MethodBasedResultSetPopulator(resultSetMethod, columnName); - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getColumnName() - */ - public String getColumnName(){ + }else{ - return columnName; - } + BeanStringPopulator typePopulator = BeanStringPopulatorRegistery.getBeanStringPopulator(remoteKeyClass); - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getQueryParameterPopulator() - */ - public QueryParameterPopulator getQueryParameterPopulator(){ + if(typePopulator != null){ - if(queryParameterPopulator == null && queryMethod == null){ + remoteKeyPopulator = new TypeBasedResultSetPopulator(typePopulator, columnName); + }else{ - if(!initialized){ + throw new UnsupportedFieldTypeException("Unable to find resultset method or type populator for field " + remoteKeyField.getName() + " in " + remoteClass + " when creating many to one relation for field " + field.getName() + " in " + beanClass, field, ManyToOne.class, beanClass); + } + } + } - this.init(); - } + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getColumnName() + */ + public String getColumnName(){ - this.queryParameterPopulator = annotatedDAO.getQueryParameterPopulator(remoteRemoteKeyClass); - } + return columnName; + } - return queryParameterPopulator; - } + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getQueryParameterPopulator() + */ + public QueryParameterPopulator getQueryParameterPopulator(){ - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getQueryMethod() - */ - public Method getQueryMethod(){ + if(queryParameterPopulator == null && queryMethod == null){ - if(this.queryMethod == null){ - this.queryMethod = PreparedStatementQueryMethods.getObjectQueryMethod(); - } + if(!initialized){ - return queryMethod; - } + this.init(); + } - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getBeanValue(LocalType) - */ - @SuppressWarnings("unchecked") - public RemoteKeyType getBeanValue(LocalType bean){ + this.queryParameterPopulator = annotatedDAO.getQueryParameterPopulator(remoteRemoteKeyClass); + } - try { - RemoteType subBean = (RemoteType) field.get(bean); + return queryParameterPopulator; + } - if(subBean == null){ - return null; - } + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getQueryMethod() + */ + public Method getQueryMethod(){ - return (RemoteKeyType)remoteKeyField.get(subBean); + if(this.queryMethod == null){ + this.queryMethod = PreparedStatementQueryMethods.getObjectQueryMethod(); + } - } catch (IllegalArgumentException e) { + return queryMethod; + } - throw new RuntimeException(e); + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getBeanValue(LocalType) + */ + @SuppressWarnings("unchecked") + public RemoteKeyType getBeanValue(LocalType bean){ - } catch (IllegalAccessException e) { + try { + RemoteType subBean = (RemoteType) field.get(bean); - throw new RuntimeException(e); - } - } + if(subBean == null){ + return null; + } - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getParamValue(java.lang.Object) - */ - @SuppressWarnings("unchecked") - public RemoteKeyType getParamValue(Object bean) { + return (RemoteKeyType)remoteKeyField.get(subBean); - try { - if(bean == null){ - return null; - } + } catch (IllegalArgumentException e) { - return (RemoteKeyType) remoteKeyField.get(bean); + throw new RuntimeException(e); - } catch (IllegalArgumentException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); + } + } - } catch (IllegalAccessException e) { + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getParamValue(java.lang.Object) + */ + @SuppressWarnings("unchecked") + public RemoteKeyType getParamValue(Object bean) { - throw new RuntimeException(e); - } - } + try { + if(bean == null){ + return null; + } - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#setValue(LocalType, java.sql.ResultSet, java.sql.Connection, java.lang.reflect.Field[]) - */ - public void getRemoteValue(LocalType bean, ResultSet resultSet, Connection connection, RelationQuery relationQuery) throws SQLException{ + return (RemoteKeyType) remoteKeyField.get(bean); - try { + } catch (IllegalArgumentException e) { - if(!initialized){ - this.init(); - } + throw new RuntimeException(e); - RemoteKeyType keyValue = remoteKeyPopulator.populate(resultSet); + } catch (IllegalAccessException e) { - if(keyValue != null){ + throw new RuntimeException(e); + } + } - HighLevelQuery query = new HighLevelQuery(); + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#setValue(LocalType, java.sql.ResultSet, java.sql.Connection, java.lang.reflect.Field[]) + */ + public void getRemoteValue(LocalType bean, ResultSet resultSet, Connection connection, RelationQuery relationQuery) throws SQLException{ - query.addParameter(queryParameterFactory.getParameter(keyValue)); - - if(relationQuery != null){ - query.disableAutoRelations(relationQuery.isDisableAutoRelations()); - } - - query.addRelations(relationQuery); + try { - RemoteType remoteBeanInstance = annotatedDAO.get(query ,connection); + if(!initialized){ + this.init(); + } - this.getField().set(bean, remoteBeanInstance); - } + RemoteKeyType keyValue = remoteKeyPopulator.populate(resultSet); - } catch (IllegalArgumentException e) { + if(keyValue != null){ - throw new RuntimeException(e); + HighLevelQuery query = new HighLevelQuery(); - } catch (IllegalAccessException e) { + query.addParameter(queryParameterFactory.getParameter(keyValue)); - throw new RuntimeException(e); - } - } + if(relationQuery != null){ + query.disableAutoRelations(relationQuery.isDisableAutoRelations()); + } + query.addRelations(relationQuery); + RemoteType remoteBeanInstance = annotatedDAO.get(query ,connection); - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field) - */ - @SuppressWarnings("unchecked") - public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + this.getField().set(bean, remoteBeanInstance); + } - if(!initialized){ - this.init(); - } + } catch (IllegalArgumentException e) { - try { - RemoteType remoteBean = (RemoteType) field.get(bean); + throw new RuntimeException(e); - if(remoteBean != null){ + } catch (IllegalAccessException e) { - this.annotatedDAO.add(remoteBean, connection, relationQuery); - } + throw new RuntimeException(e); + } + } - } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } catch (IllegalAccessException e) { + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field) + */ + @SuppressWarnings("unchecked") + public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - throw new RuntimeException(e); - } + if(!initialized){ + this.init(); + } - } + try { + RemoteType remoteBean = (RemoteType) field.get(bean); - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field) - */ - @SuppressWarnings("unchecked") - public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + if(remoteBean != null){ - if(!initialized){ - this.init(); - } + this.annotatedDAO.add(remoteBean, connection, relationQuery); + } - try { - RemoteType remoteBean = (RemoteType) field.get(bean); + } catch (IllegalArgumentException e) { - if(remoteBean != null){ + throw new RuntimeException(e); - this.annotatedDAO.addOrUpdate(remoteBean, connection, relationQuery); - } + } catch (IllegalAccessException e) { - } catch (IllegalArgumentException e) { + throw new RuntimeException(e); + } - throw new RuntimeException(e); + } - } catch (IllegalAccessException e) { + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field) + */ + @SuppressWarnings("unchecked") + public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - throw new RuntimeException(e); - } + if(!initialized){ + this.init(); + } - } + try { + RemoteType remoteBean = (RemoteType) field.get(bean); - private void init() { + if(remoteBean != null){ - this.annotatedDAO = this.daoFactory.getDAO(remoteClass); - this.queryParameterFactory = annotatedDAO.getParamFactory(remoteKeyField, remoteRemoteKeyClass); + this.annotatedDAO.addOrUpdate(remoteBean, connection, relationQuery); + } - this.initialized = true; - } + } catch (IllegalArgumentException e) { - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getField() - */ - public Field getField() { + throw new RuntimeException(e); - return field; - } + } catch (IllegalAccessException e) { - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getBeanField() - */ - public Field getBeanField() { + throw new RuntimeException(e); + } - return this.field; - } + } - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#getParamType() - */ - public Class getParamType() { + private void init() { - return remoteClass; - } + this.annotatedDAO = this.daoFactory.getDAO(remoteClass); + this.queryParameterFactory = annotatedDAO.getParamFactory(remoteKeyField, remoteRemoteKeyClass); + this.initialized = true; + } - /* (non-Javadoc) - * @see se.unlogic.utils.dao.ManyToOneRelation#isAutoGenerated() - */ - public boolean isAutoGenerated() { + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getField() + */ + public Field getField() { - return false; - } + return field; + } - public static DefaultManyToOneRelation getGenericInstance(Class beanClass, Class remoteClass, Class remoteKeyClass, Field field, Field remoteField, DAOManaged daoManaged, AnnotatedDAOFactory daoFactory){ + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getBeanField() + */ + public Field getBeanField() { - return new DefaultManyToOneRelation(beanClass, remoteClass, remoteKeyClass, field, remoteField, daoManaged, daoFactory); - } + return this.field; + } + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#getParamType() + */ + public Class getParamType() { + + return remoteClass; + } + + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.ManyToOneRelation#isAutoGenerated() + */ + public boolean isAutoGenerated() { + + return false; + } + + public static DefaultManyToOneRelation getGenericInstance(Class beanClass, Class remoteClass, Class remoteKeyClass, Field field, Field remoteField, DAOManaged daoManaged, AnnotatedDAOFactory daoFactory){ + + return new DefaultManyToOneRelation(beanClass, remoteClass, remoteKeyClass, field, remoteField, daoManaged, daoFactory); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultOneToManyRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultOneToManyRelation.java index 34dbe82c7ec..679fce62976 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultOneToManyRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/DefaultOneToManyRelation.java @@ -19,181 +19,181 @@ public class DefaultOneToManyRelation implements OneToManyRelation { - private final Field field; - private Field remoteField; - private final AnnotatedDAOFactory daoFactory; - private AnnotatedDAO annotatedDAO; - private QueryParameterFactory queryParameterFactory; - private final Class beanClass; - private final Class remoteClass; - private boolean initialized; - - public DefaultOneToManyRelation(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged) { - super(); - this.beanClass = beanClass; - this.remoteClass = remoteClass; - this.field = field; - this.daoFactory = daoFactory; - - List fields = ReflectionUtils.getFields(remoteClass); - - for(Field remoteField : fields){ - - if(remoteField.getType().equals(beanClass) && remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(ManyToOne.class)){ - - this.remoteField = remoteField; - - ReflectionUtils.fixFieldAccess(this.remoteField); - - break; - } - } - - if(this.remoteField == null){ - - throw new RuntimeException("Unable to to find corresponding @ManyToOne field in class " + remoteClass + " for @OneToMany annotated field " + field.getName() + " in " + beanClass); - } - } - - /* (non-Javadoc) - * @see se.unlogic.utils.dao.OneToManyRelation#setValue(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - public void getRemoteValue(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - - if(!initialized){ - init(); - } - - try { - HighLevelQuery query = new HighLevelQuery(); - - query.addRelations(relationQuery); - - if(relationQuery != null){ - query.disableAutoRelations(relationQuery.isDisableAutoRelations()); - } - - query.addParameter(queryParameterFactory.getParameter(bean)); - - field.set(bean, annotatedDAO.getAll(query, connection)); - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - } - } - - /* (non-Javadoc) - * @see se.unlogic.utils.dao.OneToManyRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - @SuppressWarnings("unchecked") - public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - - if(!initialized){ - init(); - } - - try { - List remoteBeans = (List) field.get(bean); - - if(remoteBeans != null){ - - this.fixReferences(remoteBeans, bean); - - annotatedDAO.addAll(remoteBeans, connection, relationQuery); - } - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - } - } - - private void fixReferences(List remoteBeans, LocalType bean) throws IllegalArgumentException, IllegalAccessException { - - for(RemoteType remoteBean : remoteBeans){ - - remoteField.set(remoteBean, bean); - } - } - - /* (non-Javadoc) - * @see se.unlogic.utils.dao.OneToManyRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - @SuppressWarnings("unchecked") - public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ - - if(!initialized){ - init(); - } - - try { - List remoteBeans = (List) field.get(bean); - - if(remoteBeans == null || remoteBeans.isEmpty()){ - - HighLevelQuery query = new HighLevelQuery(); - - query.addRelations(relationQuery); - - if(relationQuery != null){ - query.disableAutoRelations(relationQuery.isDisableAutoRelations()); - } - - query.addParameter(queryParameterFactory.getParameter(bean)); - - annotatedDAO.delete(query, connection); - - }else{ - - this.fixReferences(remoteBeans, bean); - - //TODO exclude current parameter - - QueryParameter queryParameter = queryParameterFactory.getParameter(bean); - - if(!annotatedDAO.deleteWhereNotIn(remoteBeans, connection, this.remoteField, queryParameter)){ - - HighLevelQuery query = new HighLevelQuery(); - - query.addParameter(queryParameter); - - annotatedDAO.delete(query, connection); - } - - annotatedDAO.addOrUpdateAll(remoteBeans, connection, relationQuery); - } - - } catch (IllegalArgumentException e) { - - throw new RuntimeException(e); - - } catch (IllegalAccessException e) { - - throw new RuntimeException(e); - } - } - - private void init() { - - if(annotatedDAO == null){ - annotatedDAO = this.daoFactory.getDAO(remoteClass); - queryParameterFactory = annotatedDAO.getParamFactory(remoteField, beanClass); - } - - this.initialized = true; - } - - public static OneToManyRelation getGenericInstance(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged){ - - return new DefaultOneToManyRelation(beanClass,remoteClass,field,daoFactory,daoManaged); - } + private final Field field; + private Field remoteField; + private final AnnotatedDAOFactory daoFactory; + private AnnotatedDAO annotatedDAO; + private QueryParameterFactory queryParameterFactory; + private final Class beanClass; + private final Class remoteClass; + private boolean initialized; + + public DefaultOneToManyRelation(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged) { + super(); + this.beanClass = beanClass; + this.remoteClass = remoteClass; + this.field = field; + this.daoFactory = daoFactory; + + List fields = ReflectionUtils.getFields(remoteClass); + + for(Field remoteField : fields){ + + if(remoteField.getType().equals(beanClass) && remoteField.isAnnotationPresent(DAOManaged.class) && remoteField.isAnnotationPresent(ManyToOne.class)){ + + this.remoteField = remoteField; + + ReflectionUtils.fixFieldAccess(this.remoteField); + + break; + } + } + + if(this.remoteField == null){ + + throw new RuntimeException("Unable to to find corresponding @ManyToOne field in class " + remoteClass + " for @OneToMany annotated field " + field.getName() + " in " + beanClass); + } + } + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.OneToManyRelation#setValue(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + public void getRemoteValue(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + + if(!initialized){ + init(); + } + + try { + HighLevelQuery query = new HighLevelQuery(); + + query.addRelations(relationQuery); + + if(relationQuery != null){ + query.disableAutoRelations(relationQuery.isDisableAutoRelations()); + } + + query.addParameter(queryParameterFactory.getParameter(bean)); + + field.set(bean, annotatedDAO.getAll(query, connection)); + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.OneToManyRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + @SuppressWarnings("unchecked") + public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + + if(!initialized){ + init(); + } + + try { + List remoteBeans = (List) field.get(bean); + + if(remoteBeans != null){ + + this.fixReferences(remoteBeans, bean); + + annotatedDAO.addAll(remoteBeans, connection, relationQuery); + } + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + + private void fixReferences(List remoteBeans, LocalType bean) throws IllegalArgumentException, IllegalAccessException { + + for(RemoteType remoteBean : remoteBeans){ + + remoteField.set(remoteBean, bean); + } + } + + /* (non-Javadoc) + * @see se.unlogic.utils.dao.OneToManyRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + @SuppressWarnings("unchecked") + public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException{ + + if(!initialized){ + init(); + } + + try { + List remoteBeans = (List) field.get(bean); + + if(remoteBeans == null || remoteBeans.isEmpty()){ + + HighLevelQuery query = new HighLevelQuery(); + + query.addRelations(relationQuery); + + if(relationQuery != null){ + query.disableAutoRelations(relationQuery.isDisableAutoRelations()); + } + + query.addParameter(queryParameterFactory.getParameter(bean)); + + annotatedDAO.delete(query, connection); + + }else{ + + this.fixReferences(remoteBeans, bean); + + //TODO exclude current parameter + + QueryParameter queryParameter = queryParameterFactory.getParameter(bean); + + if(!annotatedDAO.deleteWhereNotIn(remoteBeans, connection, this.remoteField, queryParameter)){ + + HighLevelQuery query = new HighLevelQuery(); + + query.addParameter(queryParameter); + + annotatedDAO.delete(query, connection); + } + + annotatedDAO.addOrUpdateAll(remoteBeans, connection, relationQuery); + } + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + + private void init() { + + if(annotatedDAO == null){ + annotatedDAO = this.daoFactory.getDAO(remoteClass); + queryParameterFactory = annotatedDAO.getParamFactory(remoteField, beanClass); + } + + this.initialized = true; + } + + public static OneToManyRelation getGenericInstance(Class beanClass, Class remoteClass, Field field, AnnotatedDAOFactory daoFactory, DAOManaged daoManaged){ + + return new DefaultOneToManyRelation(beanClass,remoteClass,field,daoFactory,daoManaged); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAO.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAO.java index 8ad22b617b1..aaf935bb891 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAO.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAO.java @@ -15,33 +15,33 @@ @Deprecated public interface GenericDAO { - void add(BeanType bean) throws SQLException; + void add(BeanType bean) throws SQLException; - void add(BeanType bean, TransactionHandler transactionHandler) throws SQLException; + void add(BeanType bean, TransactionHandler transactionHandler) throws SQLException; - void add(BeanType bean, Connection connection) throws SQLException; + void add(BeanType bean, Connection connection) throws SQLException; - void update(BeanType bean) throws SQLException; + void update(BeanType bean) throws SQLException; - void update(BeanType bean, TransactionHandler transactionHandler) throws SQLException; + void update(BeanType bean, TransactionHandler transactionHandler) throws SQLException; - void update(BeanType bean, Connection connection) throws SQLException; + void update(BeanType bean, Connection connection) throws SQLException; - BeanType get(KeyType id, Field... relations) throws SQLException; + BeanType get(KeyType id, Field... relations) throws SQLException; - BeanType get(KeyType id, TransactionHandler transactionHandler, Field... relations) throws SQLException; + BeanType get(KeyType id, TransactionHandler transactionHandler, Field... relations) throws SQLException; - BeanType get(KeyType id, Connection connection, Field... relations) throws SQLException; + BeanType get(KeyType id, Connection connection, Field... relations) throws SQLException; - List getAll(Field... relations) throws SQLException; + List getAll(Field... relations) throws SQLException; - List getAll(TransactionHandler transactionHandler, Field... relations) throws SQLException; + List getAll(TransactionHandler transactionHandler, Field... relations) throws SQLException; - List getAll(Connection connection, Field... relations) throws SQLException; + List getAll(Connection connection, Field... relations) throws SQLException; - void delete(BeanType bean) throws SQLException; + void delete(BeanType bean) throws SQLException; - void delete(BeanType bean, TransactionHandler transactionHandler) throws SQLException; + void delete(BeanType bean, TransactionHandler transactionHandler) throws SQLException; - void delete(BeanType bean, Connection connection) throws SQLException; + void delete(BeanType bean, Connection connection) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAOFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAOFactory.java index 3341f32f522..4c89f58b3d3 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAOFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/GenericDAOFactory.java @@ -10,5 +10,5 @@ @Deprecated public interface GenericDAOFactory { - GenericDAO getDAO(Class beanClass); + GenericDAO getDAO(Class beanClass); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/HighLevelQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/HighLevelQuery.java index f736ed4c055..5d72888aaef 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/HighLevelQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/HighLevelQuery.java @@ -24,94 +24,94 @@ */ public class HighLevelQuery extends RelationQuery{ - private List> parameters; - private List> orderByCriterias; + private List> parameters; + private List> orderByCriterias; - public HighLevelQuery() {} + public HighLevelQuery() {} - public HighLevelQuery(List> parameters, List> orderByCriterias) { + public HighLevelQuery(List> parameters, List> orderByCriterias) { - super(); - this.parameters = parameters; - this.orderByCriterias = orderByCriterias; - } + super(); + this.parameters = parameters; + this.orderByCriterias = orderByCriterias; + } - public HighLevelQuery(Field... relations) { + public HighLevelQuery(Field... relations) { - this.addRelations(relations); - } + this.addRelations(relations); + } - public HighLevelQuery(QueryParameter parameter, Field... relations) { + public HighLevelQuery(QueryParameter parameter, Field... relations) { - this.addParameter(parameter); - this.addRelations(relations); - } + this.addParameter(parameter); + this.addRelations(relations); + } - public HighLevelQuery(QueryParameter... queryParameters) { + public HighLevelQuery(QueryParameter... queryParameters) { - this.addParameter(queryParameters); - } + this.addParameter(queryParameters); + } - public void setParameters(List> parameters) { + public void setParameters(List> parameters) { - this.parameters = parameters; - } + this.parameters = parameters; + } - public synchronized void addParameter(QueryParameter parameter){ + public synchronized void addParameter(QueryParameter parameter){ - if(this.parameters == null){ + if(this.parameters == null){ - this.parameters = new ArrayList>(); - } + this.parameters = new ArrayList>(); + } - this.parameters.add(parameter); - } + this.parameters.add(parameter); + } - public synchronized void addParameter(QueryParameter... parameters){ + public synchronized void addParameter(QueryParameter... parameters){ - if(this.parameters == null){ + if(this.parameters == null){ - this.parameters = new ArrayList>(); - } + this.parameters = new ArrayList>(); + } - this.parameters.addAll(Arrays.asList(parameters)); - } + this.parameters.addAll(Arrays.asList(parameters)); + } - public List> getOrderByCriterias() { + public List> getOrderByCriterias() { - return orderByCriterias; - } + return orderByCriterias; + } - public void setOrderByCriterias(List> orderByCriterias) { + public void setOrderByCriterias(List> orderByCriterias) { - this.orderByCriterias = orderByCriterias; - } + this.orderByCriterias = orderByCriterias; + } - public List> getParameters() { + public List> getParameters() { - return parameters; - } + return parameters; + } - public synchronized void addOrderByCriteria(OrderByCriteria criteria){ + public synchronized void addOrderByCriteria(OrderByCriteria criteria){ - if(this.orderByCriterias == null){ + if(this.orderByCriterias == null){ - this.orderByCriterias = new ArrayList>(); - } + this.orderByCriterias = new ArrayList>(); + } - this.orderByCriterias.add(criteria); - } + this.orderByCriterias.add(criteria); + } - public synchronized void addOrderByCriteria(OrderByCriteria... criterias){ + public synchronized void addOrderByCriteria(OrderByCriteria... criterias){ - if(this.orderByCriterias == null){ + if(this.orderByCriterias == null){ - this.orderByCriterias = new ArrayList>(); - } + this.orderByCriterias = new ArrayList>(); + } - this.orderByCriterias.addAll(Arrays.asList(criterias)); - } + this.orderByCriterias.addAll(Arrays.asList(criterias)); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/LowLevelQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/LowLevelQuery.java index 0e021c5d26f..43800a7d199 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/LowLevelQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/LowLevelQuery.java @@ -33,130 +33,130 @@ */ public class LowLevelQuery extends RelationQuery { - private String sql; - private List parameters; - private List generatedKeyCollectors; - private List> chainedResultSetPopulators; + private String sql; + private List parameters; + private List generatedKeyCollectors; + private List> chainedResultSetPopulators; - public String getSql() { + public String getSql() { - return sql; - } + return sql; + } - public void setSql(String sql) { + public void setSql(String sql) { - this.sql = sql; - } + this.sql = sql; + } - public List getParameters() { + public List getParameters() { - return parameters; - } + return parameters; + } - public void setParameters(List parameters) { + public void setParameters(List parameters) { - this.parameters = parameters; - } + this.parameters = parameters; + } - public void addParameter(Object parameter) { + public void addParameter(Object parameter) { - checkParameterList(); + checkParameterList(); - this.parameters.add(parameter); - } + this.parameters.add(parameter); + } - public void addParameters(Object... parameters) { + public void addParameters(Object... parameters) { - checkParameterList(); + checkParameterList(); - this.parameters.addAll(Arrays.asList(parameters)); - } + this.parameters.addAll(Arrays.asList(parameters)); + } - public void addParameters(List parameters) { + public void addParameters(List parameters) { - checkParameterList(); + checkParameterList(); - this.parameters.addAll(parameters); - } + this.parameters.addAll(parameters); + } - private void checkParameterList() { + private void checkParameterList() { - if (this.parameters == null) { + if (this.parameters == null) { - this.parameters = new ArrayList(); - } - } + this.parameters = new ArrayList(); + } + } - public void addGeneratedKeyCollector(GeneratedKeyCollector keyCollector) { + public void addGeneratedKeyCollector(GeneratedKeyCollector keyCollector) { - checkGeneratedKeyCollectorList(); + checkGeneratedKeyCollectorList(); - this.generatedKeyCollectors.add(keyCollector); - } + this.generatedKeyCollectors.add(keyCollector); + } - public void addGeneratedKeyCollector(List keyCollectors) { + public void addGeneratedKeyCollector(List keyCollectors) { - checkGeneratedKeyCollectorList(); + checkGeneratedKeyCollectorList(); - this.generatedKeyCollectors.addAll(keyCollectors); - } + this.generatedKeyCollectors.addAll(keyCollectors); + } - public void addGeneratedKeyCollector(GeneratedKeyCollector... keyCollectors) { + public void addGeneratedKeyCollector(GeneratedKeyCollector... keyCollectors) { - checkGeneratedKeyCollectorList(); + checkGeneratedKeyCollectorList(); - this.generatedKeyCollectors.addAll(Arrays.asList(keyCollectors)); - } + this.generatedKeyCollectors.addAll(Arrays.asList(keyCollectors)); + } - private void checkGeneratedKeyCollectorList() { + private void checkGeneratedKeyCollectorList() { - if (this.generatedKeyCollectors == null) { + if (this.generatedKeyCollectors == null) { - this.generatedKeyCollectors = new ArrayList(); - } - } + this.generatedKeyCollectors = new ArrayList(); + } + } - public List getGeneratedKeyCollectors() { + public List getGeneratedKeyCollectors() { - return generatedKeyCollectors; - } + return generatedKeyCollectors; + } - public void addChainedResultSetPopulator(ChainedResultSetPopulator chainedPopulator) { + public void addChainedResultSetPopulator(ChainedResultSetPopulator chainedPopulator) { - checkChainedResultSetPopulatorList(); + checkChainedResultSetPopulatorList(); - this.chainedResultSetPopulators.add(chainedPopulator); - } + this.chainedResultSetPopulators.add(chainedPopulator); + } - public void addChainedResultSetPopulator(List> chainedPopulators) { + public void addChainedResultSetPopulator(List> chainedPopulators) { - checkChainedResultSetPopulatorList(); + checkChainedResultSetPopulatorList(); - this.chainedResultSetPopulators.addAll(chainedPopulators); - } + this.chainedResultSetPopulators.addAll(chainedPopulators); + } - public void addChainedResultSetPopulator(ChainedResultSetPopulator... chainedPopulators) { + public void addChainedResultSetPopulator(ChainedResultSetPopulator... chainedPopulators) { - checkChainedResultSetPopulatorList(); + checkChainedResultSetPopulatorList(); - this.chainedResultSetPopulators.addAll(Arrays.asList(chainedPopulators)); - } + this.chainedResultSetPopulators.addAll(Arrays.asList(chainedPopulators)); + } - private void checkChainedResultSetPopulatorList() { + private void checkChainedResultSetPopulatorList() { - if (this.chainedResultSetPopulators == null) { + if (this.chainedResultSetPopulators == null) { - this.chainedResultSetPopulators = new ArrayList>(); - } - } + this.chainedResultSetPopulators = new ArrayList>(); + } + } - public List> getChainedResultSetPopulators() { + public List> getChainedResultSetPopulators() { - return chainedResultSetPopulators; - } - - public boolean hasChainedBeanResultSetPopulators(){ - - return this.chainedResultSetPopulators != null && !this.chainedResultSetPopulators.isEmpty(); - } + return chainedResultSetPopulators; + } + + public boolean hasChainedBeanResultSetPopulators(){ + + return this.chainedResultSetPopulators != null && !this.chainedResultSetPopulators.isEmpty(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToManyRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToManyRelation.java index c1e61350df1..24594a91c77 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToManyRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToManyRelation.java @@ -12,10 +12,10 @@ public interface ManyToManyRelation { - void getRemoteValue(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void getRemoteValue(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; - void add(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void add(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; - void update(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void update(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToOneRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToOneRelation.java index 8caecd95938..09a1dcf7c63 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToOneRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/ManyToOneRelation.java @@ -14,15 +14,15 @@ public interface ManyToOneRelation extends Column{ - RemoteKeyType getBeanValue(LocalType bean); + RemoteKeyType getBeanValue(LocalType bean); - RemoteKeyType getParamValue(Object bean); + RemoteKeyType getParamValue(Object bean); - void getRemoteValue(LocalType bean, ResultSet resultSet, Connection connection, RelationQuery relations) throws SQLException; + void getRemoteValue(LocalType bean, ResultSet resultSet, Connection connection, RelationQuery relations) throws SQLException; - void add(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void add(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; - void update(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void update(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; - Field getField(); + Field getField(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/MethodBasedResultSetPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/MethodBasedResultSetPopulator.java index 9da7dc94c6b..5a453bb1f4b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/MethodBasedResultSetPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/MethodBasedResultSetPopulator.java @@ -15,32 +15,32 @@ public class MethodBasedResultSetPopulator implements BeanResultSetPopulator { - private Method method; - private String columnName; + private Method method; + private String columnName; - public MethodBasedResultSetPopulator(Method method, String columnName) { + public MethodBasedResultSetPopulator(Method method, String columnName) { - this.method = method; - this.columnName = columnName; - } + this.method = method; + this.columnName = columnName; + } - @SuppressWarnings("unchecked") - public Type populate(ResultSet rs) throws SQLException { + @SuppressWarnings("unchecked") + public Type populate(ResultSet rs) throws SQLException { - try { - return (Type) method.invoke(rs, columnName); + try { + return (Type) method.invoke(rs, columnName); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (InvocationTargetException e) { + } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/OneToManyRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/OneToManyRelation.java index 48b1388b0aa..dcf1da31598 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/OneToManyRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/OneToManyRelation.java @@ -12,10 +12,10 @@ public interface OneToManyRelation { - void getRemoteValue(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void getRemoteValue(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; - void add(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void add(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; - void update(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; + void update(LocalType bean, Connection connection, RelationQuery relations) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByComparator.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByComparator.java index 5f4d0404936..d40eb489164 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByComparator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByComparator.java @@ -13,19 +13,19 @@ public class OrderByComparator implements Comparator { - public int compare(OrderBy o1, OrderBy o2) { - - if (o1.priority() < o2.priority()) { - - return 1; - - } else if (o1.priority() == o2.priority()) { - - return 0; - - } else { - - return -1; - } - } + public int compare(OrderBy o1, OrderBy o2) { + + if (o1.priority() < o2.priority()) { + + return 1; + + } else if (o1.priority() == o2.priority()) { + + return 0; + + } else { + + return -1; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByCriteria.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByCriteria.java index 6b3ba007224..af574f6637a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByCriteria.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/OrderByCriteria.java @@ -11,24 +11,24 @@ public class OrderByCriteria { - private Order order; - private Column column; + private Order order; + private Column column; - public OrderByCriteria(Order order, Column column) { + public OrderByCriteria(Order order, Column column) { - super(); - this.order = order; - this.column = column; - } + super(); + this.order = order; + this.column = column; + } - public Order getOrder() { + public Order getOrder() { - return order; - } + return order; + } - public Column getColumn() { + public Column getColumn() { - return column; - } + return column; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/PreparedStatementQueryMethods.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/PreparedStatementQueryMethods.java index 82580ddfa89..0ff02d6df79 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/PreparedStatementQueryMethods.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/PreparedStatementQueryMethods.java @@ -26,48 +26,48 @@ */ public class PreparedStatementQueryMethods { - protected static final HashMap,Method> QUERY_METHOD_MAP = new HashMap, Method>(); - protected static final Method SET_OBJECT_METHOD; - static{ - try { - //Special methods mappings - QUERY_METHOD_MAP.put(Integer.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); - QUERY_METHOD_MAP.put(Long.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); - QUERY_METHOD_MAP.put(Double.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); - QUERY_METHOD_MAP.put(Float.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); - QUERY_METHOD_MAP.put(Boolean.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); - QUERY_METHOD_MAP.put(Byte.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); + protected static final HashMap,Method> QUERY_METHOD_MAP = new HashMap, Method>(); + protected static final Method SET_OBJECT_METHOD; + static{ + try { + //Special methods mappings + QUERY_METHOD_MAP.put(Integer.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); + QUERY_METHOD_MAP.put(Long.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); + QUERY_METHOD_MAP.put(Double.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); + QUERY_METHOD_MAP.put(Float.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); + QUERY_METHOD_MAP.put(Boolean.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); + QUERY_METHOD_MAP.put(Byte.class, PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class)); - Method[] methods = PreparedStatementQuery.class.getMethods(); + Method[] methods = PreparedStatementQuery.class.getMethods(); - for(Method method : methods){ + for(Method method : methods){ - if(method.getName().startsWith("set") && !method.getName().equals("setObject") && method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == int.class){ + if(method.getName().startsWith("set") && !method.getName().equals("setObject") && method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == int.class){ - //System.out.println("Adding method " + method); - QUERY_METHOD_MAP.put(method.getParameterTypes()[1], method); - } - } + //System.out.println("Adding method " + method); + QUERY_METHOD_MAP.put(method.getParameterTypes()[1], method); + } + } - SET_OBJECT_METHOD = PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class); + SET_OBJECT_METHOD = PreparedStatementQuery.class.getMethod("setObject", int.class,Object.class); - } catch (SecurityException e) { + } catch (SecurityException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - public static Method getQueryMethod(Class clazz) { + public static Method getQueryMethod(Class clazz) { - return QUERY_METHOD_MAP.get(clazz); - } + return QUERY_METHOD_MAP.get(clazz); + } - public static Method getObjectQueryMethod(){ + public static Method getObjectQueryMethod(){ - return SET_OBJECT_METHOD; - } + return SET_OBJECT_METHOD; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryOperators.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryOperators.java index 0c3f35510c4..a04b825a4ef 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryOperators.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryOperators.java @@ -9,21 +9,21 @@ public enum QueryOperators { - EQUALS("="), - NOT_EQUALS("!="), - BIGGER_THAN(">"), - SMALLER_THAN("<"), - BIGGER_THAN_OR_EUALS("<="), - SMALLER_THAN_OR_EUALS(">="), - LIKE("LIKE"); + EQUALS("="), + NOT_EQUALS("!="), + BIGGER_THAN(">"), + SMALLER_THAN("<"), + BIGGER_THAN_OR_EUALS("<="), + SMALLER_THAN_OR_EUALS(">="), + LIKE("LIKE"); - private String value; + private String value; - QueryOperators (String value){ - this.value = value; - } + QueryOperators (String value){ + this.value = value; + } - public String getOperator(){ - return value; - } + public String getOperator(){ + return value; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameter.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameter.java index 22303a5740d..3a26fc21f85 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameter.java @@ -12,65 +12,65 @@ public class QueryParameter { - private final ColumnType value; - private final Collection values; - private Column column; - private String operator = QueryOperators.EQUALS.getOperator(); - - QueryParameter(Column column, ColumnType value) { - super(); - this.column = column; - this.value = value; - this.values = null; - } - - QueryParameter(Column column, ColumnType value, String operator) { - super(); - this.column = column; - this.value = value; - this.operator = operator; - this.values = null; - } - - QueryParameter(Column column, String operator) { - super(); - this.column = column; - this.operator = operator; - this.value = null; - this.values = null; - } - - QueryParameter(Column column, Collection values, String operator) { - - this.column = column; - this.operator = operator; - this.value = null; - this.values = values; - } - - public ColumnType getValue() { - return value; - } - - public Collection getValues() { - return values; - } - - public Column getColumn() { - return column; - } - - public String getOperator() { - return operator; - } - - public boolean hasValues(){ - - return this.value != null || this.values != null; - } - - public boolean hasMultipleValues(){ - - return this.values != null; - } + private final ColumnType value; + private final Collection values; + private Column column; + private String operator = QueryOperators.EQUALS.getOperator(); + + QueryParameter(Column column, ColumnType value) { + super(); + this.column = column; + this.value = value; + this.values = null; + } + + QueryParameter(Column column, ColumnType value, String operator) { + super(); + this.column = column; + this.value = value; + this.operator = operator; + this.values = null; + } + + QueryParameter(Column column, String operator) { + super(); + this.column = column; + this.operator = operator; + this.value = null; + this.values = null; + } + + QueryParameter(Column column, Collection values, String operator) { + + this.column = column; + this.operator = operator; + this.value = null; + this.values = values; + } + + public ColumnType getValue() { + return value; + } + + public Collection getValues() { + return values; + } + + public Column getColumn() { + return column; + } + + public String getOperator() { + return operator; + } + + public boolean hasValues(){ + + return this.value != null || this.values != null; + } + + public boolean hasMultipleValues(){ + + return this.values != null; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameterFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameterFactory.java index 5a3bd1aef2a..432422c48ff 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameterFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/QueryParameterFactory.java @@ -14,60 +14,60 @@ public class QueryParameterFactory { - private Column column; - - QueryParameterFactory(Column column) { - super(); - this.column = column; - } - - public QueryParameter getParameter(Type value){ - - if(value == null){ - - throw new RuntimeException("Value cannot be null, it will result in invalid SQL"); - } - - return new QueryParameter(column, value); - } - - public QueryParameter getParameter(Type value, QueryOperators queryOperator){ - - if(value == null){ - - throw new RuntimeException("Value cannot be null, it will result in invalid SQL"); - } - - return new QueryParameter(column, value, queryOperator.getOperator()); - } - - public QueryParameter getIsNullParameter(){ - - return new QueryParameter(column, "IS NULL"); - } - - public QueryParameter getIsNotNullParameter(){ - - return new QueryParameter(column, "IS NOT NULL"); - } - - public QueryParameter getWhereInParameter(Collection values){ - - if(CollectionUtils.isEmpty(values)){ - - throw new RuntimeException("Values cannot be null or empty, it will result in invalid SQL"); - } - - return new QueryParameter(column, values, "IN"); - } - - public QueryParameter getWhereNotInParameter(List values){ - - if(CollectionUtils.isEmpty(values)){ - - throw new RuntimeException("Values cannot be null or empty, it will result in invalid SQL"); - } - - return new QueryParameter(column, values, "NOT IN"); - } + private Column column; + + QueryParameterFactory(Column column) { + super(); + this.column = column; + } + + public QueryParameter getParameter(Type value){ + + if(value == null){ + + throw new RuntimeException("Value cannot be null, it will result in invalid SQL"); + } + + return new QueryParameter(column, value); + } + + public QueryParameter getParameter(Type value, QueryOperators queryOperator){ + + if(value == null){ + + throw new RuntimeException("Value cannot be null, it will result in invalid SQL"); + } + + return new QueryParameter(column, value, queryOperator.getOperator()); + } + + public QueryParameter getIsNullParameter(){ + + return new QueryParameter(column, "IS NULL"); + } + + public QueryParameter getIsNotNullParameter(){ + + return new QueryParameter(column, "IS NOT NULL"); + } + + public QueryParameter getWhereInParameter(Collection values){ + + if(CollectionUtils.isEmpty(values)){ + + throw new RuntimeException("Values cannot be null or empty, it will result in invalid SQL"); + } + + return new QueryParameter(column, values, "IN"); + } + + public QueryParameter getWhereNotInParameter(List values){ + + if(CollectionUtils.isEmpty(values)){ + + throw new RuntimeException("Values cannot be null or empty, it will result in invalid SQL"); + } + + return new QueryParameter(column, values, "NOT IN"); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/RelationQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/RelationQuery.java index 90314ff3c15..ba792e7ac64 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/RelationQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/RelationQuery.java @@ -15,185 +15,185 @@ public class RelationQuery { - private List relations; - private List excludedRelations; + private List relations; + private List excludedRelations; - private boolean disableAutoRelations; - - public RelationQuery() {} + private boolean disableAutoRelations; - public RelationQuery(List relations) { + public RelationQuery() {} - this.relations = relations; - } + public RelationQuery(List relations) { - public RelationQuery(Field... relations) { + this.relations = relations; + } - this.addRelations(relations); - } + public RelationQuery(Field... relations) { - public RelationQuery(RelationQuery relationQuery) { + this.addRelations(relations); + } - this.addRelations(relationQuery); - } + public RelationQuery(RelationQuery relationQuery) { - public List getRelations() { + this.addRelations(relationQuery); + } - return relations; - } + public List getRelations() { - public void setRelations(List relations) { + return relations; + } - this.relations = relations; - } + public void setRelations(List relations) { - public void addRelation(Field relation){ + this.relations = relations; + } - if(this.relations == null){ + public void addRelation(Field relation){ - this.relations = new ArrayList(); - } + if(this.relations == null){ - this.relations.add(relation); - } + this.relations = new ArrayList(); + } - public void addRelations(Field... relations){ + this.relations.add(relation); + } - if(this.relations == null){ + public void addRelations(Field... relations){ - this.relations = new ArrayList(); - } + if(this.relations == null){ - this.relations.addAll(Arrays.asList(relations)); - } + this.relations = new ArrayList(); + } - public static boolean hasRelations(RelationQuery query){ + this.relations.addAll(Arrays.asList(relations)); + } - if(query == null || query.getRelations() == null || query.getRelations().isEmpty()){ - return false; - } + public static boolean hasRelations(RelationQuery query){ - return true; - } + if(query == null || query.getRelations() == null || query.getRelations().isEmpty()){ + return false; + } - public boolean hasRelations(){ + return true; + } - return hasRelations(this); - } + public boolean hasRelations(){ - public void addRelations(RelationQuery relationQuery) { + return hasRelations(this); + } - if(hasRelations(relationQuery)){ + public void addRelations(RelationQuery relationQuery) { - this.addRelations(relationQuery.getRelations()); - } - } + if(hasRelations(relationQuery)){ - public void addRelations(List relations){ + this.addRelations(relationQuery.getRelations()); + } + } - if(this.relations == null){ + public void addRelations(List relations){ - this.relations = relations; + if(this.relations == null){ - }else{ + this.relations = relations; - this.relations.addAll(relations); - } - } + }else{ - public List getExcludedRelations() { + this.relations.addAll(relations); + } + } - return excludedRelations; - } + public List getExcludedRelations() { - public void setExcludedRelations(List excludedRelations) { + return excludedRelations; + } - this.excludedRelations = excludedRelations; - } + public void setExcludedRelations(List excludedRelations) { - public void addExcludedRelation(Field relation){ + this.excludedRelations = excludedRelations; + } - if(this.excludedRelations == null){ + public void addExcludedRelation(Field relation){ - this.excludedRelations = new ArrayList(); - } + if(this.excludedRelations == null){ - this.excludedRelations.add(relation); - } + this.excludedRelations = new ArrayList(); + } - public void addExcludedRelations(Field... excludedRelations){ + this.excludedRelations.add(relation); + } - if(this.excludedRelations == null){ + public void addExcludedRelations(Field... excludedRelations){ - this.excludedRelations = new ArrayList(); - } + if(this.excludedRelations == null){ - this.excludedRelations.addAll(Arrays.asList(excludedRelations)); - } + this.excludedRelations = new ArrayList(); + } - public static boolean hasExcludedRelations(RelationQuery query){ + this.excludedRelations.addAll(Arrays.asList(excludedRelations)); + } - if(query == null || query.getExcludedRelations() == null || query.getExcludedRelations().isEmpty()){ - return false; - } + public static boolean hasExcludedRelations(RelationQuery query){ - return true; - } + if(query == null || query.getExcludedRelations() == null || query.getExcludedRelations().isEmpty()){ + return false; + } - public boolean hasExcludedRelations(){ + return true; + } - return hasExcludedRelations(this); - } + public boolean hasExcludedRelations(){ - public void addExcludedRelations(RelationQuery relationQuery) { + return hasExcludedRelations(this); + } - if(hasExcludedRelations(relationQuery)){ + public void addExcludedRelations(RelationQuery relationQuery) { - this.addExcludedRelations(relationQuery.getExcludedRelations()); - } - } + if(hasExcludedRelations(relationQuery)){ - public void addExcludedRelations(List excludedRelations){ + this.addExcludedRelations(relationQuery.getExcludedRelations()); + } + } - if(this.excludedRelations == null){ + public void addExcludedRelations(List excludedRelations){ - this.excludedRelations = excludedRelations; + if(this.excludedRelations == null){ - }else{ + this.excludedRelations = excludedRelations; - this.excludedRelations.addAll(excludedRelations); - } - } + }else{ - public boolean containsRelation(Field field) { + this.excludedRelations.addAll(excludedRelations); + } + } - if(this.relations != null){ + public boolean containsRelation(Field field) { - return this.relations.contains(field); - } + if(this.relations != null){ - return false; - } + return this.relations.contains(field); + } - public boolean containsExcludedRelation(Field field) { + return false; + } - if(this.excludedRelations != null){ + public boolean containsExcludedRelation(Field field) { - return this.excludedRelations.contains(field); - } + if(this.excludedRelations != null){ - return false; - } + return this.excludedRelations.contains(field); + } - - public boolean isDisableAutoRelations() { - - return disableAutoRelations; - } + return false; + } - - public void disableAutoRelations(boolean disableAutoRelations) { - - this.disableAutoRelations = disableAutoRelations; - } + + public boolean isDisableAutoRelations() { + + return disableAutoRelations; + } + + + public void disableAutoRelations(boolean disableAutoRelations) { + + this.disableAutoRelations = disableAutoRelations; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetField.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetField.java index ad381de266f..cc48252e7b3 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetField.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetField.java @@ -14,38 +14,38 @@ public class ResultSetField { - private final Field beanField; - private final Method resultSetColumnNameMethod; - private final Method resultSetColumnIndexMethod; - private final BeanStringPopulator beanStringPopulator; - private final String alias; - - public ResultSetField(Field beanField, Method resultSetColumnNameMethod, Method resultSetColumnIndexMethod, String alias , BeanStringPopulator typePopulator) { - super(); - this.beanField = beanField; - this.resultSetColumnNameMethod = resultSetColumnNameMethod; - this.resultSetColumnIndexMethod = resultSetColumnIndexMethod; - this.alias = alias; - this.beanStringPopulator = typePopulator; - } - - public BeanStringPopulator getBeanStringPopulator() { - return beanStringPopulator; - } - - public Field getBeanField() { - return beanField; - } - - public Method getResultSetColumnNameMethod() { - return resultSetColumnNameMethod; - } - - public String getAlias() { - return alias; - } - - public Method getResultSetColumnIndexMethod() { - return resultSetColumnIndexMethod; - } + private final Field beanField; + private final Method resultSetColumnNameMethod; + private final Method resultSetColumnIndexMethod; + private final BeanStringPopulator beanStringPopulator; + private final String alias; + + public ResultSetField(Field beanField, Method resultSetColumnNameMethod, Method resultSetColumnIndexMethod, String alias , BeanStringPopulator typePopulator) { + super(); + this.beanField = beanField; + this.resultSetColumnNameMethod = resultSetColumnNameMethod; + this.resultSetColumnIndexMethod = resultSetColumnIndexMethod; + this.alias = alias; + this.beanStringPopulator = typePopulator; + } + + public BeanStringPopulator getBeanStringPopulator() { + return beanStringPopulator; + } + + public Field getBeanField() { + return beanField; + } + + public Method getResultSetColumnNameMethod() { + return resultSetColumnNameMethod; + } + + public String getAlias() { + return alias; + } + + public Method getResultSetColumnIndexMethod() { + return resultSetColumnIndexMethod; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetMethods.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetMethods.java index ab608394a2c..07de848d81d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetMethods.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/ResultSetMethods.java @@ -17,85 +17,85 @@ public class ResultSetMethods { - private static final LinkedHashMap,Method> RESULTSET_COLUMNNAME_METHODS = new LinkedHashMap, Method>(); + private static final LinkedHashMap,Method> RESULTSET_COLUMNNAME_METHODS = new LinkedHashMap, Method>(); - static{ - try { - RESULTSET_COLUMNNAME_METHODS.put(String.class, ResultSet.class.getMethod("getString", String.class)); + static{ + try { + RESULTSET_COLUMNNAME_METHODS.put(String.class, ResultSet.class.getMethod("getString", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Timestamp.class, ResultSet.class.getMethod("getTimestamp", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(Timestamp.class, ResultSet.class.getMethod("getTimestamp", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Blob.class, ResultSet.class.getMethod("getBlob", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(Blob.class, ResultSet.class.getMethod("getBlob", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Date.class, ResultSet.class.getMethod("getDate", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(Date.class, ResultSet.class.getMethod("getDate", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Boolean.class, ResultSet.class.getMethod("getBoolean", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(boolean.class, ResultSet.class.getMethod("getBoolean", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(Boolean.class, ResultSet.class.getMethod("getBoolean", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(boolean.class, ResultSet.class.getMethod("getBoolean", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Integer.class, ResultSet.class.getMethod("getInt", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(int.class, ResultSet.class.getMethod("getInt", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(Integer.class, ResultSet.class.getMethod("getInt", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(int.class, ResultSet.class.getMethod("getInt", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Long.class, ResultSet.class.getMethod("getLong", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(long.class, ResultSet.class.getMethod("getLong", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(Long.class, ResultSet.class.getMethod("getLong", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(long.class, ResultSet.class.getMethod("getLong", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Float.class, ResultSet.class.getMethod("getFloat", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(float.class, ResultSet.class.getMethod("getFloat", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(Float.class, ResultSet.class.getMethod("getFloat", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(float.class, ResultSet.class.getMethod("getFloat", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(Double.class, ResultSet.class.getMethod("getDouble", String.class)); - RESULTSET_COLUMNNAME_METHODS.put(double.class, ResultSet.class.getMethod("getDouble", String.class)); - } catch (SecurityException e) { + RESULTSET_COLUMNNAME_METHODS.put(Double.class, ResultSet.class.getMethod("getDouble", String.class)); + RESULTSET_COLUMNNAME_METHODS.put(double.class, ResultSet.class.getMethod("getDouble", String.class)); + } catch (SecurityException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - private static final LinkedHashMap,Method> RESULTSET_COLUMNINDEX_METHODS = new LinkedHashMap, Method>(); + private static final LinkedHashMap,Method> RESULTSET_COLUMNINDEX_METHODS = new LinkedHashMap, Method>(); - static{ - try { - RESULTSET_COLUMNINDEX_METHODS.put(int.class, ResultSet.class.getMethod("getString", int.class)); + static{ + try { + RESULTSET_COLUMNINDEX_METHODS.put(int.class, ResultSet.class.getMethod("getString", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Timestamp.class, ResultSet.class.getMethod("getTimestamp", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(Timestamp.class, ResultSet.class.getMethod("getTimestamp", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Blob.class, ResultSet.class.getMethod("getBlob", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(Blob.class, ResultSet.class.getMethod("getBlob", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Date.class, ResultSet.class.getMethod("getDate", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(Date.class, ResultSet.class.getMethod("getDate", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Boolean.class, ResultSet.class.getMethod("getBoolean", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(boolean.class, ResultSet.class.getMethod("getBoolean", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(Boolean.class, ResultSet.class.getMethod("getBoolean", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(boolean.class, ResultSet.class.getMethod("getBoolean", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Integer.class, ResultSet.class.getMethod("getInt", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(int.class, ResultSet.class.getMethod("getInt", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(Integer.class, ResultSet.class.getMethod("getInt", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(int.class, ResultSet.class.getMethod("getInt", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Long.class, ResultSet.class.getMethod("getLong", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(long.class, ResultSet.class.getMethod("getLong", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(Long.class, ResultSet.class.getMethod("getLong", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(long.class, ResultSet.class.getMethod("getLong", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Float.class, ResultSet.class.getMethod("getFloat", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(float.class, ResultSet.class.getMethod("getFloat", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(Float.class, ResultSet.class.getMethod("getFloat", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(float.class, ResultSet.class.getMethod("getFloat", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(Double.class, ResultSet.class.getMethod("getDouble", int.class)); - RESULTSET_COLUMNINDEX_METHODS.put(double.class, ResultSet.class.getMethod("getDouble", int.class)); - } catch (SecurityException e) { + RESULTSET_COLUMNINDEX_METHODS.put(Double.class, ResultSet.class.getMethod("getDouble", int.class)); + RESULTSET_COLUMNINDEX_METHODS.put(double.class, ResultSet.class.getMethod("getDouble", int.class)); + } catch (SecurityException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (NoSuchMethodException e) { + } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - public static Method getColumnNameMethod(Class clazz){ + public static Method getColumnNameMethod(Class clazz){ - return RESULTSET_COLUMNNAME_METHODS.get(clazz); - } + return RESULTSET_COLUMNNAME_METHODS.get(clazz); + } - public static Method getColumnIndexMethod(Class clazz){ + public static Method getColumnIndexMethod(Class clazz){ - return RESULTSET_COLUMNINDEX_METHODS.get(clazz); - } + return RESULTSET_COLUMNINDEX_METHODS.get(clazz); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleAnnotatedDAOFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleAnnotatedDAOFactory.java index ff943fc0a59..b87096ec8e1 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleAnnotatedDAOFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleAnnotatedDAOFactory.java @@ -18,97 +18,97 @@ public class SimpleAnnotatedDAOFactory implements AnnotatedDAOFactory{ - private final DataSource dataSource; - private final HashMap, AnnotatedDAO> daoMap = new HashMap, AnnotatedDAO>(); + private final DataSource dataSource; + private final HashMap, AnnotatedDAO> daoMap = new HashMap, AnnotatedDAO>(); - public SimpleAnnotatedDAOFactory(DataSource dataSource) { + public SimpleAnnotatedDAOFactory(DataSource dataSource) { - super(); - this.dataSource = dataSource; - } + super(); + this.dataSource = dataSource; + } - public SimpleAnnotatedDAOFactory() { + public SimpleAnnotatedDAOFactory() { - super(); - this.dataSource = null; - } + super(); + this.dataSource = null; + } - @SuppressWarnings("unchecked") - public synchronized AnnotatedDAO getDAO(Class beanClass) { + @SuppressWarnings("unchecked") + public synchronized AnnotatedDAO getDAO(Class beanClass) { - AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); + AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); - if(dao == null){ + if(dao == null){ - dao = new AnnotatedDAO(dataSource, beanClass, this); - this.daoMap.put(beanClass, dao); - } + dao = new AnnotatedDAO(dataSource, beanClass, this); + this.daoMap.put(beanClass, dao); + } - return dao; - } + return dao; + } - @SuppressWarnings("unchecked") - public synchronized AnnotatedDAO getDAO(Class beanClass, AnnotatedResultSetPopulator populator) { + @SuppressWarnings("unchecked") + public synchronized AnnotatedDAO getDAO(Class beanClass, AnnotatedResultSetPopulator populator) { - AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); + AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); - if(dao == null){ + if(dao == null){ - dao = new AnnotatedDAO(dataSource, beanClass, this, populator, null, null); - this.daoMap.put(beanClass, dao); - } + dao = new AnnotatedDAO(dataSource, beanClass, this, populator, null, null); + this.daoMap.put(beanClass, dao); + } - return dao; - } + return dao; + } - @SuppressWarnings("unchecked") - public synchronized AnnotatedDAO getDAO(Class beanClass, AnnotatedResultSetPopulator populator, QueryParameterPopulator... queryParameterPopulators) { + @SuppressWarnings("unchecked") + public synchronized AnnotatedDAO getDAO(Class beanClass, AnnotatedResultSetPopulator populator, QueryParameterPopulator... queryParameterPopulators) { - AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); + AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); - if(dao == null){ + if(dao == null){ - dao = new AnnotatedDAO(dataSource, beanClass, this, populator, queryParameterPopulators); - this.daoMap.put(beanClass, dao); - } + dao = new AnnotatedDAO(dataSource, beanClass, this, populator, queryParameterPopulators); + this.daoMap.put(beanClass, dao); + } - return dao; - } + return dao; + } - @SuppressWarnings("unchecked") - public synchronized AnnotatedDAO getDAO(Class beanClass, List> queryParameterPopulators, List> typePopulators) { + @SuppressWarnings("unchecked") + public synchronized AnnotatedDAO getDAO(Class beanClass, List> queryParameterPopulators, List> typePopulators) { - AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); + AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); - if(dao == null){ + if(dao == null){ - dao = new AnnotatedDAO(dataSource, beanClass, this, queryParameterPopulators, typePopulators); - this.daoMap.put(beanClass, dao); - } + dao = new AnnotatedDAO(dataSource, beanClass, this, queryParameterPopulators, typePopulators); + this.daoMap.put(beanClass, dao); + } - return dao; - } - - @SuppressWarnings("unchecked") - public synchronized AnnotatedDAO getDAO(Class beanClass, AnnotatedResultSetPopulator populator, List> queryParameterPopulators, List> typePopulators) { + return dao; + } - AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); + @SuppressWarnings("unchecked") + public synchronized AnnotatedDAO getDAO(Class beanClass, AnnotatedResultSetPopulator populator, List> queryParameterPopulators, List> typePopulators) { - if(dao == null){ + AnnotatedDAO dao = (AnnotatedDAO) this.daoMap.get(beanClass); - dao = new AnnotatedDAO(dataSource, beanClass, this, populator, queryParameterPopulators, typePopulators); - this.daoMap.put(beanClass, dao); - } + if(dao == null){ - return dao; - } + dao = new AnnotatedDAO(dataSource, beanClass, this, populator, queryParameterPopulators, typePopulators); + this.daoMap.put(beanClass, dao); + } - public DataSource getDataSource() { + return dao; + } - return dataSource; - } + public DataSource getDataSource() { - public void addDAO(Class beanClass, AnnotatedDAO daoInstance) { - daoMap.put(beanClass, daoInstance); - } + return dataSource; + } + + public void addDAO(Class beanClass, AnnotatedDAO daoInstance) { + daoMap.put(beanClass, daoInstance); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleColumn.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleColumn.java index de3b90e8cf1..61b79e7be73 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleColumn.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleColumn.java @@ -14,71 +14,71 @@ public class SimpleColumn implements Column { - private final Field beanField; - private final Method queryMethod; - private final QueryParameterPopulator queryParameterPopulator; - private final String columnName; - private final boolean autoGenerated; + private final Field beanField; + private final Method queryMethod; + private final QueryParameterPopulator queryParameterPopulator; + private final String columnName; + private final boolean autoGenerated; - public SimpleColumn(Field beanField, Method queryMethod, QueryParameterPopulator queryPopulator, String columnName, boolean autoGenerated) { - super(); - this.beanField = beanField; - this.queryMethod = queryMethod; - this.columnName = columnName; - this.autoGenerated = autoGenerated; - this.queryParameterPopulator = queryPopulator; - } + public SimpleColumn(Field beanField, Method queryMethod, QueryParameterPopulator queryPopulator, String columnName, boolean autoGenerated) { + super(); + this.beanField = beanField; + this.queryMethod = queryMethod; + this.columnName = columnName; + this.autoGenerated = autoGenerated; + this.queryParameterPopulator = queryPopulator; + } - @SuppressWarnings("unchecked") - public ColumnType getParamValue(Object paramValue) { + @SuppressWarnings("unchecked") + public ColumnType getParamValue(Object paramValue) { - return (ColumnType) paramValue; - } + return (ColumnType) paramValue; + } - @SuppressWarnings("unchecked") - public ColumnType getBeanValue(BeanType bean) { + @SuppressWarnings("unchecked") + public ColumnType getBeanValue(BeanType bean) { - try { - return (ColumnType) beanField.get(bean); + try { + return (ColumnType) beanField.get(bean); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - public Field getBeanField(){ + public Field getBeanField(){ - return beanField; - } + return beanField; + } - public Class getParamType(){ + public Class getParamType(){ - return beanField.getType(); - } + return beanField.getType(); + } - public Method getQueryMethod() { - return queryMethod; - } + public Method getQueryMethod() { + return queryMethod; + } - public String getColumnName() { - return columnName; - } + public String getColumnName() { + return columnName; + } - public boolean isAutoGenerated() { - return autoGenerated; - } + public boolean isAutoGenerated() { + return autoGenerated; + } - public QueryParameterPopulator getQueryParameterPopulator() { - return queryParameterPopulator; - } + public QueryParameterPopulator getQueryParameterPopulator() { + return queryParameterPopulator; + } - public static SimpleColumn getGenericInstance(Class beanClass, Class fieldClass, Field beanField, Method queryMethod, QueryParameterPopulator queryPopulator, String columnName, boolean autoGenerated) { + public static SimpleColumn getGenericInstance(Class beanClass, Class fieldClass, Field beanField, Method queryMethod, QueryParameterPopulator queryPopulator, String columnName, boolean autoGenerated) { - return new SimpleColumn(beanField, queryMethod, queryPopulator, columnName, autoGenerated); - } + return new SimpleColumn(beanField, queryMethod, queryPopulator, columnName, autoGenerated); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleDataSource.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleDataSource.java index eb4934280be..c8e5977ffec 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleDataSource.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimpleDataSource.java @@ -19,57 +19,57 @@ public class SimpleDataSource implements DataSource { - private String url; - private String username; - private String password; - - public SimpleDataSource(String driver, String url, String username, String password) throws ClassNotFoundException { + private String url; + private String username; + private String password; - super(); - this.url = url; - this.username = username; - this.password = password; - - Class.forName(driver); - } + public SimpleDataSource(String driver, String url, String username, String password) throws ClassNotFoundException { - public Connection getConnection() throws SQLException { + super(); + this.url = url; + this.username = username; + this.password = password; - return DriverManager.getConnection(this.url, username, password); - } + Class.forName(driver); + } + + public Connection getConnection() throws SQLException { + + return DriverManager.getConnection(this.url, username, password); + } - public Connection getConnection(String username, String password) throws SQLException { + public Connection getConnection(String username, String password) throws SQLException { - return DriverManager.getConnection(this.url, username, password); - } + return DriverManager.getConnection(this.url, username, password); + } - public PrintWriter getLogWriter() throws SQLException { + public PrintWriter getLogWriter() throws SQLException { - throw new UnsupportedOperationException(); - } + throw new UnsupportedOperationException(); + } - public int getLoginTimeout() throws SQLException { + public int getLoginTimeout() throws SQLException { - throw new UnsupportedOperationException(); - } + throw new UnsupportedOperationException(); + } - public void setLogWriter(PrintWriter out) throws SQLException { + public void setLogWriter(PrintWriter out) throws SQLException { - throw new UnsupportedOperationException(); - } + throw new UnsupportedOperationException(); + } - public void setLoginTimeout(int seconds) throws SQLException { + public void setLoginTimeout(int seconds) throws SQLException { - throw new UnsupportedOperationException(); - } + throw new UnsupportedOperationException(); + } - public boolean isWrapperFor(Class arg0) throws SQLException { - return false; - } + public boolean isWrapperFor(Class arg0) throws SQLException { + return false; + } - public T unwrap(Class arg0) throws SQLException { - return null; - } + public T unwrap(Class arg0) throws SQLException { + return null; + } public Logger getParentLogger() throws SQLFeatureNotSupportedException { diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimplifiedOneToManyRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimplifiedOneToManyRelation.java index 951f7724c92..f246d563d49 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/SimplifiedOneToManyRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/SimplifiedOneToManyRelation.java @@ -30,335 +30,335 @@ public class SimplifiedOneToManyRelation implements OneToManyRelation { - private final AnnotatedDAO localDAO; - private final Field field; + private final AnnotatedDAO localDAO; + private final Field field; - private String selectSQL; - private String insertSQL; - private String deleteSQL; + private String selectSQL; + private String insertSQL; + private String deleteSQL; - private boolean preserveListOrder; - private String indexColumnName; - - private QueryParameterPopulator queryParameterPopulator; - private Method preparedStatementMethod; + private boolean preserveListOrder; + private String indexColumnName; - private BeanResultSetPopulator beanResultSetPopulator; + private QueryParameterPopulator queryParameterPopulator; + private Method preparedStatementMethod; - private Field keyField; - private Column keyColumn; + private BeanResultSetPopulator beanResultSetPopulator; - private final String remoteTableName; - private String remoteKeyColumnName; - private final String remoteValueColumnName; - private Order order; + private Field keyField; + private Column keyColumn; - private boolean initialized; + private final String remoteTableName; + private String remoteKeyColumnName; + private final String remoteValueColumnName; + private Order order; - @SuppressWarnings("unchecked") - public SimplifiedOneToManyRelation(Class beanClass, Class remoteClass, Field field, AnnotatedDAO localDAO, List> typePopulators, List> queryParameterPopulators) { + private boolean initialized; - super(); - this.localDAO = localDAO; - this.field = field; + @SuppressWarnings("unchecked") + public SimplifiedOneToManyRelation(Class beanClass, Class remoteClass, Field field, AnnotatedDAO localDAO, List> typePopulators, List> queryParameterPopulators) { - SimplifiedRelation simplifiedRelation = field.getAnnotation(SimplifiedRelation.class); + super(); + this.localDAO = localDAO; + this.field = field; - remoteKeyColumnName = simplifiedRelation.remoteKeyColumnName(); - remoteValueColumnName = simplifiedRelation.remoteValueColumnName(); - order = simplifiedRelation.order(); + SimplifiedRelation simplifiedRelation = field.getAnnotation(SimplifiedRelation.class); - if(simplifiedRelation.addTablePrefix()){ - - if(simplifiedRelation.deplurifyTablePrefix() && localDAO.getTableName().endsWith("s")){ - - remoteTableName = localDAO.getTableName().substring(0, localDAO.getTableName().length()-1) + simplifiedRelation.table(); - - }else{ - - remoteTableName = localDAO.getTableName() + simplifiedRelation.table(); - } - }else{ - - remoteTableName = simplifiedRelation.table(); - } - - if (!StringUtils.isEmpty(simplifiedRelation.keyField())) { + remoteKeyColumnName = simplifiedRelation.remoteKeyColumnName(); + remoteValueColumnName = simplifiedRelation.remoteValueColumnName(); + order = simplifiedRelation.order(); - try { - keyField = ReflectionUtils.getField(beanClass, simplifiedRelation.keyField()); + if(simplifiedRelation.addTablePrefix()){ - if (keyField == null) { + if(simplifiedRelation.deplurifyTablePrefix() && localDAO.getTableName().endsWith("s")){ - throw new RuntimeException("Unable to find field " + simplifiedRelation.keyField() + " in " + beanClass.getClass()); - } + remoteTableName = localDAO.getTableName().substring(0, localDAO.getTableName().length()-1) + simplifiedRelation.table(); - } catch (SecurityException e) { + }else{ - throw new RuntimeException(e); + remoteTableName = localDAO.getTableName() + simplifiedRelation.table(); + } + }else{ - } + remoteTableName = simplifiedRelation.table(); + } - } else { + if (!StringUtils.isEmpty(simplifiedRelation.keyField())) { - List fields = ReflectionUtils.getFields(beanClass); + try { + keyField = ReflectionUtils.getField(beanClass, simplifiedRelation.keyField()); - for (Field localBeanField : fields) { + if (keyField == null) { - if (localBeanField.isAnnotationPresent(DAOManaged.class) && localBeanField.isAnnotationPresent(Key.class)) { + throw new RuntimeException("Unable to find field " + simplifiedRelation.keyField() + " in " + beanClass.getClass()); + } - if (this.keyField == null) { + } catch (SecurityException e) { - keyField = localBeanField; + throw new RuntimeException(e); - } else { + } - throw new RuntimeException("Multiple fields marked with @Key annotation found in class " + beanClass + " therefore keyField has to set on the @SimplifiedRelation annotation of field " + field.getName()); - } - } - } - } + } else { - if (queryParameterPopulators != null) { + List fields = ReflectionUtils.getFields(beanClass); - for (QueryParameterPopulator queryParameterPopulator : queryParameterPopulators) { + for (Field localBeanField : fields) { - if (queryParameterPopulator.getType().equals(remoteClass)) { + if (localBeanField.isAnnotationPresent(DAOManaged.class) && localBeanField.isAnnotationPresent(Key.class)) { - this.queryParameterPopulator = (QueryParameterPopulator) queryParameterPopulator; - } - } - } + if (this.keyField == null) { - if (this.queryParameterPopulator == null) { + keyField = localBeanField; - preparedStatementMethod = PreparedStatementQueryMethods.getQueryMethod(remoteClass); + } else { - if (preparedStatementMethod == null) { + throw new RuntimeException("Multiple fields marked with @Key annotation found in class " + beanClass + " therefore keyField has to set on the @SimplifiedRelation annotation of field " + field.getName()); + } + } + } + } - throw new RuntimeException("Unable to to find a query parameter populator or prepared statement method matching " + remoteClass + " of @SimplfiedRelation and @OneToMany annotated field " + field.getName() + " in " + beanClass); - } - } + if (queryParameterPopulators != null) { - if (typePopulators != null) { + for (QueryParameterPopulator queryParameterPopulator : queryParameterPopulators) { - for (BeanStringPopulator typePopulator : typePopulators) { + if (queryParameterPopulator.getType().equals(remoteClass)) { - if (typePopulator.getType().equals(remoteClass)) { + this.queryParameterPopulator = (QueryParameterPopulator) queryParameterPopulator; + } + } + } - beanResultSetPopulator = new TypeBasedResultSetPopulator((BeanStringPopulator) typePopulator, remoteValueColumnName); - } - } - } + if (this.queryParameterPopulator == null) { - if (beanResultSetPopulator == null) { + preparedStatementMethod = PreparedStatementQueryMethods.getQueryMethod(remoteClass); - Method resultSetMethod = ResultSetMethods.getColumnNameMethod(remoteClass); + if (preparedStatementMethod == null) { - if (resultSetMethod != null) { + throw new RuntimeException("Unable to to find a query parameter populator or prepared statement method matching " + remoteClass + " of @SimplfiedRelation and @OneToMany annotated field " + field.getName() + " in " + beanClass); + } + } - beanResultSetPopulator = new MethodBasedResultSetPopulator(resultSetMethod, remoteValueColumnName); + if (typePopulators != null) { - } else { + for (BeanStringPopulator typePopulator : typePopulators) { - throw new RuntimeException("Unable to to find a type populator or resultset method matching " + remoteClass + " of @SimplfiedRelation and @OneToMany annotated field " + field.getName() + " in " + beanClass); - } - } - - if(simplifiedRelation.preserveListOrder()){ - - if(StringUtils.isEmpty(simplifiedRelation.indexColumn())){ - - throw new RuntimeException("Preserve list order enabled but no index column specified for @SimplifiedRelation annotated field " + field.getName() + " in " + beanClass); - } - - preserveListOrder = true; - indexColumnName = simplifiedRelation.indexColumn(); - } - } + if (typePopulator.getType().equals(remoteClass)) { - private void init() { + beanResultSetPopulator = new TypeBasedResultSetPopulator((BeanStringPopulator) typePopulator, remoteValueColumnName); + } + } + } - this.keyColumn = localDAO.getColumn(keyField); + if (beanResultSetPopulator == null) { - if (StringUtils.isEmpty(remoteKeyColumnName)) { + Method resultSetMethod = ResultSetMethods.getColumnNameMethod(remoteClass); - remoteKeyColumnName = keyColumn.getColumnName(); - } + if (resultSetMethod != null) { - this.deleteSQL = "DELETE FROM " + remoteTableName + " WHERE " + remoteKeyColumnName + "=?"; + beanResultSetPopulator = new MethodBasedResultSetPopulator(resultSetMethod, remoteValueColumnName); - if(preserveListOrder){ - - this.selectSQL = "SELECT * FROM " + remoteTableName + " WHERE " + remoteKeyColumnName + " = ? ORDER BY " + indexColumnName + " " + order; - this.insertSQL = "INSERT INTO " + remoteTableName + "(" + remoteKeyColumnName + "," + remoteValueColumnName + "," + indexColumnName + ") VALUES (?,?,?)"; - - }else{ - - this.selectSQL = "SELECT * FROM " + remoteTableName + " WHERE " + remoteKeyColumnName + " = ? ORDER BY " + remoteValueColumnName + " " + order; - this.insertSQL = "INSERT INTO " + remoteTableName + "(" + remoteKeyColumnName + "," + remoteValueColumnName + ") VALUES (?,?)"; - } - - this.initialized = true; - } + } else { - /* - * (non-Javadoc) - * - * @see se.unlogic.utils.dao.OneToManyRelation#setValue(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - public void getRemoteValue(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException { + throw new RuntimeException("Unable to to find a type populator or resultset method matching " + remoteClass + " of @SimplfiedRelation and @OneToMany annotated field " + field.getName() + " in " + beanClass); + } + } - if (!initialized) { - init(); - } + if(simplifiedRelation.preserveListOrder()){ - try { - ArrayListQuery query = new ArrayListQuery(connection, false, selectSQL, beanResultSetPopulator); + if(StringUtils.isEmpty(simplifiedRelation.indexColumn())){ - setKey(query, bean); + throw new RuntimeException("Preserve list order enabled but no index column specified for @SimplifiedRelation annotated field " + field.getName() + " in " + beanClass); + } - ArrayList list = query.executeQuery(); + preserveListOrder = true; + indexColumnName = simplifiedRelation.indexColumn(); + } + } - if (list != null) { + private void init() { - CollectionUtils.removeNullValues(list); - } + this.keyColumn = localDAO.getColumn(keyField); - field.set(bean, list); + if (StringUtils.isEmpty(remoteKeyColumnName)) { - } catch (IllegalArgumentException e) { + remoteKeyColumnName = keyColumn.getColumnName(); + } - throw new RuntimeException(e); + this.deleteSQL = "DELETE FROM " + remoteTableName + " WHERE " + remoteKeyColumnName + "=?"; - } catch (IllegalAccessException e) { + if(preserveListOrder){ - throw new RuntimeException(e); - } - } + this.selectSQL = "SELECT * FROM " + remoteTableName + " WHERE " + remoteKeyColumnName + " = ? ORDER BY " + indexColumnName + " " + order; + this.insertSQL = "INSERT INTO " + remoteTableName + "(" + remoteKeyColumnName + "," + remoteValueColumnName + "," + indexColumnName + ") VALUES (?,?,?)"; - private void setKey(PreparedStatementQuery query, LocalType bean) throws SQLException { + }else{ - if (keyColumn.getQueryParameterPopulator() != null) { + this.selectSQL = "SELECT * FROM " + remoteTableName + " WHERE " + remoteKeyColumnName + " = ? ORDER BY " + remoteValueColumnName + " " + order; + this.insertSQL = "INSERT INTO " + remoteTableName + "(" + remoteKeyColumnName + "," + remoteValueColumnName + ") VALUES (?,?)"; + } - keyColumn.getQueryParameterPopulator().populate(query, 1, bean); + this.initialized = true; + } - } else { + /* + * (non-Javadoc) + * + * @see se.unlogic.utils.dao.OneToManyRelation#setValue(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + public void getRemoteValue(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException { - try { - keyColumn.getQueryMethod().invoke(query, 1, keyColumn.getBeanValue(bean)); + if (!initialized) { + init(); + } - } catch (IllegalArgumentException e) { + try { + ArrayListQuery query = new ArrayListQuery(connection, false, selectSQL, beanResultSetPopulator); - throw new RuntimeException(e); + setKey(query, bean); - } catch (IllegalAccessException e) { + ArrayList list = query.executeQuery(); - throw new RuntimeException(e); + if (list != null) { - } catch (InvocationTargetException e) { + CollectionUtils.removeNullValues(list); + } - throw new RuntimeException(e); - } - } - } + field.set(bean, list); - private void setValue(RemoteType value, UpdateQuery query) throws SQLException { + } catch (IllegalArgumentException e) { - if (queryParameterPopulator != null) { + throw new RuntimeException(e); - queryParameterPopulator.populate(query, 2, value); + } catch (IllegalAccessException e) { - } else { + throw new RuntimeException(e); + } + } - try { - preparedStatementMethod.invoke(query, 2, value); + private void setKey(PreparedStatementQuery query, LocalType bean) throws SQLException { - } catch (IllegalArgumentException e) { + if (keyColumn.getQueryParameterPopulator() != null) { - throw new RuntimeException(e); + keyColumn.getQueryParameterPopulator().populate(query, 1, bean); - } catch (IllegalAccessException e) { + } else { - throw new RuntimeException(e); + try { + keyColumn.getQueryMethod().invoke(query, 1, keyColumn.getBeanValue(bean)); - } catch (InvocationTargetException e) { + } catch (IllegalArgumentException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); - } + } catch (IllegalAccessException e) { - /* - * (non-Javadoc) - * - * @see se.unlogic.utils.dao.OneToManyRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - @SuppressWarnings("unchecked") - public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException { + throw new RuntimeException(e); - if (!initialized) { - init(); - } + } catch (InvocationTargetException e) { - try { - List values = (List) field.get(bean); + throw new RuntimeException(e); + } + } + } - if (values != null) { + private void setValue(RemoteType value, UpdateQuery query) throws SQLException { - int listIndex = 0; - - for (RemoteType value : values) { + if (queryParameterPopulator != null) { - UpdateQuery query = new UpdateQuery(connection, false, insertSQL); + queryParameterPopulator.populate(query, 2, value); - setKey(query, bean); + } else { - setValue(value, query); + try { + preparedStatementMethod.invoke(query, 2, value); - if(preserveListOrder){ - - query.setInt(3, listIndex); - listIndex++; - } - - query.executeUpdate(); - } - } + } catch (IllegalArgumentException e) { - } catch (IllegalArgumentException e) { + throw new RuntimeException(e); - throw new RuntimeException(e); + } catch (IllegalAccessException e) { - } catch (IllegalAccessException e) { + throw new RuntimeException(e); - throw new RuntimeException(e); - } - } + } catch (InvocationTargetException e) { - /* - * (non-Javadoc) - * - * @see se.unlogic.utils.dao.OneToManyRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field[]) - */ - public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException { + throw new RuntimeException(e); + } + } - if (!initialized) { - init(); - } + } - UpdateQuery query = new UpdateQuery(connection, false, deleteSQL); + /* + * (non-Javadoc) + * + * @see se.unlogic.utils.dao.OneToManyRelation#add(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + @SuppressWarnings("unchecked") + public void add(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException { - setKey(query, bean); + if (!initialized) { + init(); + } - query.executeUpdate(); + try { + List values = (List) field.get(bean); - this.add(bean, connection, relationQuery); - } + if (values != null) { - public static OneToManyRelation getGenericInstance(Class beanClass, Class remoteClass, Field field, AnnotatedDAO localDAO, List> typePopulators, List> queryParameterPopulators) { + int listIndex = 0; - return new SimplifiedOneToManyRelation(beanClass, remoteClass, field, localDAO, typePopulators, queryParameterPopulators); - } + for (RemoteType value : values) { + + UpdateQuery query = new UpdateQuery(connection, false, insertSQL); + + setKey(query, bean); + + setValue(value, query); + + if(preserveListOrder){ + + query.setInt(3, listIndex); + listIndex++; + } + + query.executeUpdate(); + } + } + + } catch (IllegalArgumentException e) { + + throw new RuntimeException(e); + + } catch (IllegalAccessException e) { + + throw new RuntimeException(e); + } + } + + /* + * (non-Javadoc) + * + * @see se.unlogic.utils.dao.OneToManyRelation#update(LocalType, java.sql.Connection, java.lang.reflect.Field[]) + */ + public void update(LocalType bean, Connection connection, RelationQuery relationQuery) throws SQLException { + + if (!initialized) { + init(); + } + + UpdateQuery query = new UpdateQuery(connection, false, deleteSQL); + + setKey(query, bean); + + query.executeUpdate(); + + this.add(bean, connection, relationQuery); + } + + public static OneToManyRelation getGenericInstance(Class beanClass, Class remoteClass, Field field, AnnotatedDAO localDAO, List> typePopulators, List> queryParameterPopulators) { + + return new SimplifiedOneToManyRelation(beanClass, remoteClass, field, localDAO, typePopulators, queryParameterPopulators); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyAbortedException.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyAbortedException.java index 2283b5fe1cc..4ae0eac45a1 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyAbortedException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyAbortedException.java @@ -9,6 +9,6 @@ public class TransactionAlreadyAbortedException extends RuntimeException { - private static final long serialVersionUID = -6159981132857395802L; + private static final long serialVersionUID = -6159981132857395802L; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyComittedException.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyComittedException.java index 97eb345452c..a89fae6de96 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyComittedException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionAlreadyComittedException.java @@ -9,6 +9,6 @@ public class TransactionAlreadyComittedException extends RuntimeException { - private static final long serialVersionUID = 628962939940339634L; + private static final long serialVersionUID = 628962939940339634L; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionHandler.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionHandler.java index 80f384bf03a..15245c0b3a7 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionHandler.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/TransactionHandler.java @@ -23,187 +23,187 @@ public class TransactionHandler { - private final Connection connection; - private ArrayList queryList; - private boolean aborted; - private boolean commited; - - public TransactionHandler(DataSource dataSource) throws SQLException { - - super(); - this.connection = dataSource.getConnection(); - connection.setAutoCommit(false); - } - - public TransactionHandler(Connection connection) throws SQLException { - - super(); - this.connection = connection; - connection.setAutoCommit(false); - } - - public UpdateQuery getUpdateQuery(String sqlExpression) throws SQLException { - - this.checkStatus(); - - UpdateQuery query = new UpdateQuery(connection, false, sqlExpression); - - checkQueryList(); - - this.queryList.add(query); - - return query; - } - - private synchronized void checkQueryList() { - - if(queryList == null){ - - queryList = new ArrayList(); - } - - } - - public BooleanQuery getBooleanQuery(String sql) throws SQLException { - - BooleanQuery query = new BooleanQuery(connection, false, sql); - - checkQueryList(); - - this.queryList.add(query); - - return query; - } - - public ObjectQuery getObjectQuery(String sql, BeanResultSetPopulator populator) throws SQLException { - - ObjectQuery query = new ObjectQuery(connection, false, sql, populator); - - checkQueryList(); - - this.queryList.add(query); - - return query; - } + private final Connection connection; + private ArrayList queryList; + private boolean aborted; + private boolean commited; - public ArrayListQuery getArrayListQuery(String sql, BeanResultSetPopulator populator) throws SQLException { - - ArrayListQuery query = new ArrayListQuery(connection, false, sql, populator); - - checkQueryList(); - - this.queryList.add(query); - - return query; - } + public TransactionHandler(DataSource dataSource) throws SQLException { - public HashMapQuery getHashMapQuery(String sql, BeanResultSetPopulator> populator) throws SQLException { + super(); + this.connection = dataSource.getConnection(); + connection.setAutoCommit(false); + } - HashMapQuery query = new HashMapQuery(connection, false, sql, populator); - - checkQueryList(); - - this.queryList.add(query); - - return query; - } + public TransactionHandler(Connection connection) throws SQLException { - public synchronized void commit() throws SQLException { + super(); + this.connection = connection; + connection.setAutoCommit(false); + } - this.checkStatus(); + public UpdateQuery getUpdateQuery(String sqlExpression) throws SQLException { - try { - connection.commit(); - this.commited = true; - } finally { + this.checkStatus(); - if (!this.commited) { - this.abort(); - } else { - this.closeConnection(); - } - } - } + UpdateQuery query = new UpdateQuery(connection, false, sqlExpression); - public synchronized int getQueryCount() { + checkQueryList(); - if(queryList == null){ - - return 0; - } - - return this.queryList.size(); - } + this.queryList.add(query); - public synchronized void abort() { + return query; + } - this.checkStatus(); + private synchronized void checkQueryList() { - if(queryList != null){ - for (PreparedStatementQuery query : queryList) { - query.abort(); - } - } - - if (connection != null) { - try { - connection.rollback(); - } catch (SQLException e) {} - } - - this.closeConnection(); - this.aborted = true; - } - - private void closeConnection() { - - DBUtils.closeConnection(connection); - } - - private void checkStatus() { - - if (aborted) { - throw new TransactionAlreadyAbortedException(); - } else if (commited) { - throw new TransactionAlreadyComittedException(); - } - } - - @Override - protected void finalize() throws Throwable { + if(queryList == null){ - if (!commited && !aborted) { - this.abort(); - } + queryList = new ArrayList(); + } - super.finalize(); - } - - public boolean isClosed() { + } - return commited || aborted; - } + public BooleanQuery getBooleanQuery(String sql) throws SQLException { - public static void autoClose(TransactionHandler transactionHandler) { + BooleanQuery query = new BooleanQuery(connection, false, sql); - if (transactionHandler != null && !transactionHandler.isClosed()) { - transactionHandler.abort(); - } - } + checkQueryList(); - //Workaround for AnnotatedDAO, needs a better solution in the long run - Connection getConnection() { + this.queryList.add(query); - return connection; - } + return query; + } - public boolean isAborted() { + public ObjectQuery getObjectQuery(String sql, BeanResultSetPopulator populator) throws SQLException { - return aborted; - } + ObjectQuery query = new ObjectQuery(connection, false, sql, populator); - public boolean isCommited() { + checkQueryList(); - return commited; - } + this.queryList.add(query); + + return query; + } + + public ArrayListQuery getArrayListQuery(String sql, BeanResultSetPopulator populator) throws SQLException { + + ArrayListQuery query = new ArrayListQuery(connection, false, sql, populator); + + checkQueryList(); + + this.queryList.add(query); + + return query; + } + + public HashMapQuery getHashMapQuery(String sql, BeanResultSetPopulator> populator) throws SQLException { + + HashMapQuery query = new HashMapQuery(connection, false, sql, populator); + + checkQueryList(); + + this.queryList.add(query); + + return query; + } + + public synchronized void commit() throws SQLException { + + this.checkStatus(); + + try { + connection.commit(); + this.commited = true; + } finally { + + if (!this.commited) { + this.abort(); + } else { + this.closeConnection(); + } + } + } + + public synchronized int getQueryCount() { + + if(queryList == null){ + + return 0; + } + + return this.queryList.size(); + } + + public synchronized void abort() { + + this.checkStatus(); + + if(queryList != null){ + for (PreparedStatementQuery query : queryList) { + query.abort(); + } + } + + if (connection != null) { + try { + connection.rollback(); + } catch (SQLException e) {} + } + + this.closeConnection(); + this.aborted = true; + } + + private void closeConnection() { + + DBUtils.closeConnection(connection); + } + + private void checkStatus() { + + if (aborted) { + throw new TransactionAlreadyAbortedException(); + } else if (commited) { + throw new TransactionAlreadyComittedException(); + } + } + + @Override + protected void finalize() throws Throwable { + + if (!commited && !aborted) { + this.abort(); + } + + super.finalize(); + } + + public boolean isClosed() { + + return commited || aborted; + } + + public static void autoClose(TransactionHandler transactionHandler) { + + if (transactionHandler != null && !transactionHandler.isClosed()) { + transactionHandler.abort(); + } + } + + //Workaround for AnnotatedDAO, needs a better solution in the long run + Connection getConnection() { + + return connection; + } + + public boolean isAborted() { + + return aborted; + } + + public boolean isCommited() { + + return commited; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/TypeBasedResultSetPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/TypeBasedResultSetPopulator.java index 2d338f26797..5263c3b2f2a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/TypeBasedResultSetPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/TypeBasedResultSetPopulator.java @@ -15,24 +15,24 @@ public class TypeBasedResultSetPopulator implements BeanResultSetPopulator { - private BeanStringPopulator beanStringPopulator; - private String columnName; + private BeanStringPopulator beanStringPopulator; + private String columnName; - public TypeBasedResultSetPopulator(BeanStringPopulator typePopulator, String columnName) { + public TypeBasedResultSetPopulator(BeanStringPopulator typePopulator, String columnName) { - this.beanStringPopulator = typePopulator; - this.columnName = columnName; - } + this.beanStringPopulator = typePopulator; + this.columnName = columnName; + } - public Type populate(ResultSet rs) throws SQLException { + public Type populate(ResultSet rs) throws SQLException { - String value = rs.getString(columnName); + String value = rs.getString(columnName); - if(value == null){ + if(value == null){ - return null; - } + return null; + } - return beanStringPopulator.getValue(value); - } + return beanStringPopulator.getValue(value); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/DAOManaged.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/DAOManaged.java index a18508945fa..eb26a53b2ea 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/DAOManaged.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/DAOManaged.java @@ -18,8 +18,8 @@ @Target(ElementType.FIELD) public @interface DAOManaged { - String columnName() default ""; - String populatorID() default ""; - boolean autoGenerated() default false; - int autGenerationColumnIndex() default 0; + String columnName() default ""; + String populatorID() default ""; + boolean autoGenerated() default false; + int autGenerationColumnIndex() default 0; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToMany.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToMany.java index 2b0891fdff6..23fe0468bc2 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToMany.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToMany.java @@ -18,9 +18,9 @@ @Target(ElementType.FIELD) public @interface ManyToMany { - String linkTable(); - String keyField() default ""; - boolean autoGet() default false; - boolean autoAdd() default false; - boolean autoUpdate() default false; + String linkTable(); + String keyField() default ""; + boolean autoGet() default false; + boolean autoAdd() default false; + boolean autoUpdate() default false; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToOne.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToOne.java index 8fe3a4d009c..db1e80ad75d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToOne.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/ManyToOne.java @@ -18,8 +18,8 @@ @Target(ElementType.FIELD) public @interface ManyToOne { - String remoteKeyField() default ""; - boolean autoGet() default false; - boolean autoAdd() default false; - boolean autoUpdate() default false; + String remoteKeyField() default ""; + boolean autoGet() default false; + boolean autoAdd() default false; + boolean autoUpdate() default false; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToMany.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToMany.java index dd8be7837bc..cd98123e307 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToMany.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToMany.java @@ -18,7 +18,7 @@ @Target(ElementType.FIELD) public @interface OneToMany { - boolean autoGet() default false; - boolean autoAdd() default false; - boolean autoUpdate() default false; + boolean autoGet() default false; + boolean autoAdd() default false; + boolean autoUpdate() default false; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToOne.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToOne.java index 5a7f06a4dce..d047354168b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToOne.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OneToOne.java @@ -18,8 +18,8 @@ @Target(ElementType.FIELD) public @interface OneToOne { - String remoteColumn() default ""; - boolean autoGet() default false; - boolean autoAdd() default false; - boolean autoUpdate() default false; + String remoteColumn() default ""; + boolean autoGet() default false; + boolean autoAdd() default false; + boolean autoUpdate() default false; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OrderBy.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OrderBy.java index 39c38030f36..af8e7d69d82 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OrderBy.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/OrderBy.java @@ -20,6 +20,6 @@ @Target(ElementType.FIELD) public @interface OrderBy{ - Order order() default Order.ASC; - int priority() default 0; + Order order() default Order.ASC; + int priority() default 0; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/SimplifiedRelation.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/SimplifiedRelation.java index a8db84cefb6..3923ab9f7e8 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/SimplifiedRelation.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/SimplifiedRelation.java @@ -26,13 +26,13 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface SimplifiedRelation { - String keyField() default ""; - String table(); - String remoteKeyColumnName() default ""; - String remoteValueColumnName(); - Order order() default Order.ASC; - boolean addTablePrefix() default false; - boolean deplurifyTablePrefix() default false; - boolean preserveListOrder() default false; - String indexColumn() default ""; + String keyField() default ""; + String table(); + String remoteKeyColumnName() default ""; + String remoteValueColumnName(); + Order order() default Order.ASC; + boolean addTablePrefix() default false; + boolean deplurifyTablePrefix() default false; + boolean preserveListOrder() default false; + String indexColumn() default ""; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/Table.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/Table.java index a7cf36e045c..09509e282fc 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/Table.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/annotations/Table.java @@ -17,5 +17,5 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Table { - String name(); + String name(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/enums/Order.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/enums/Order.java index e340f5a6957..feb3e787641 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/enums/Order.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/enums/Order.java @@ -9,5 +9,5 @@ public enum Order { - ASC, DESC + ASC, DESC } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ArrayListQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ArrayListQuery.java index 5441b58c5bc..890203eea68 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ArrayListQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ArrayListQuery.java @@ -19,52 +19,52 @@ public class ArrayListQuery extends PopulatedQuery { - public ArrayListQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { - super(connection, closeConnectionOnExit, query, bp); - } + public ArrayListQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { + super(connection, closeConnectionOnExit, query, bp); + } - public ArrayListQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { - super(dataSource, closeConnectionOnExit, query, bp); - } + public ArrayListQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { + super(dataSource, closeConnectionOnExit, query, bp); + } - public ArrayList executeQuery() throws SQLException { + public ArrayList executeQuery() throws SQLException { - ResultSet rs = null; - ArrayList returnTypeList = null; + ResultSet rs = null; + ArrayList returnTypeList = null; - try { - // Send query to database and store results. - rs = pstmt.executeQuery(); + try { + // Send query to database and store results. + rs = pstmt.executeQuery(); - if (rs.next()) { - rs.last(); - returnTypeList = new ArrayList(rs.getRow()); - rs.beforeFirst(); + if (rs.next()) { + rs.last(); + returnTypeList = new ArrayList(rs.getRow()); + rs.beforeFirst(); - while (rs.next()) { - returnTypeList.add(beanPopulator.populate(rs)); - } - } + while (rs.next()) { + returnTypeList.add(beanPopulator.populate(rs)); + } + } - return returnTypeList; + return returnTypeList; - } catch (SQLException sqle) { - throw sqle; - } finally { - DBUtils.closeResultSet(rs); - DBUtils.closePreparedStatement(pstmt); + } catch (SQLException sqle) { + throw sqle; + } finally { + DBUtils.closeResultSet(rs); + DBUtils.closePreparedStatement(pstmt); - if (this.closeConnectionOnExit) { - DBUtils.closeConnection(connection); - } + if (this.closeConnectionOnExit) { + DBUtils.closeConnection(connection); + } - this.closed = true; - } - } + this.closed = true; + } + } - @Override - protected PreparedStatement getPreparedStatement(String query) throws SQLException { + @Override + protected PreparedStatement getPreparedStatement(String query) throws SQLException { - return connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - } + return connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/BooleanQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/BooleanQuery.java index 2b06a043738..e9877685064 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/BooleanQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/BooleanQuery.java @@ -16,37 +16,37 @@ public class BooleanQuery extends PreparedStatementQuery { - public BooleanQuery(Connection connection, boolean closeConnectionOnExit, String query) throws SQLException { - super(connection, closeConnectionOnExit, query); - } - - public BooleanQuery(DataSource dataSource, boolean closeConnectionOnExit, String query) throws SQLException { - super(dataSource, closeConnectionOnExit, query); - } - - public boolean executeQuery() throws SQLException { - - ResultSet rs = null; - - try { - rs = pstmt.executeQuery(); - - if (rs.next()) { - return true; - } else { - return false; - } - } catch (SQLException sqle) { - throw sqle; - } finally { - DBUtils.closeResultSet(rs); - DBUtils.closePreparedStatement(pstmt); - - if (this.closeConnectionOnExit) { - DBUtils.closeConnection(connection); - } - - this.closed = true; - } - } + public BooleanQuery(Connection connection, boolean closeConnectionOnExit, String query) throws SQLException { + super(connection, closeConnectionOnExit, query); + } + + public BooleanQuery(DataSource dataSource, boolean closeConnectionOnExit, String query) throws SQLException { + super(dataSource, closeConnectionOnExit, query); + } + + public boolean executeQuery() throws SQLException { + + ResultSet rs = null; + + try { + rs = pstmt.executeQuery(); + + if (rs.next()) { + return true; + } else { + return false; + } + } catch (SQLException sqle) { + throw sqle; + } finally { + DBUtils.closeResultSet(rs); + DBUtils.closePreparedStatement(pstmt); + + if (this.closeConnectionOnExit) { + DBUtils.closeConnection(connection); + } + + this.closed = true; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/GeneratedKeyCollector.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/GeneratedKeyCollector.java index bd4d2f0db33..f992c3c3395 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/GeneratedKeyCollector.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/GeneratedKeyCollector.java @@ -13,6 +13,6 @@ public interface GeneratedKeyCollector { - void collect(ResultSet rs) throws SQLException; + void collect(ResultSet rs) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/HashMapQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/HashMapQuery.java index 25650e44d7d..398c9b4977b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/HashMapQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/HashMapQuery.java @@ -19,46 +19,46 @@ public class HashMapQuery extends PopulatedQuery> { - public HashMapQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator> bp) throws SQLException { - super(connection, closeConnectionOnExit, query, bp); - } + public HashMapQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator> bp) throws SQLException { + super(connection, closeConnectionOnExit, query, bp); + } - public HashMapQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator> bp) throws SQLException { - super(dataSource, closeConnectionOnExit, query, bp); - } + public HashMapQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator> bp) throws SQLException { + super(dataSource, closeConnectionOnExit, query, bp); + } - public HashMap executeQuery() throws SQLException { + public HashMap executeQuery() throws SQLException { - ResultSet rs = null; - HashMap returnTypeMap = null; + ResultSet rs = null; + HashMap returnTypeMap = null; - try { - // Send query to database and store results. - rs = pstmt.executeQuery(); + try { + // Send query to database and store results. + rs = pstmt.executeQuery(); - if (rs.next()) { - returnTypeMap = new HashMap(); - rs.beforeFirst(); + if (rs.next()) { + returnTypeMap = new HashMap(); + rs.beforeFirst(); - while (rs.next()) { - Entry entry = beanPopulator.populate(rs); - returnTypeMap.put(entry.getKey(), entry.getValue()); - } - } + while (rs.next()) { + Entry entry = beanPopulator.populate(rs); + returnTypeMap.put(entry.getKey(), entry.getValue()); + } + } - return returnTypeMap; + return returnTypeMap; - } catch (SQLException sqle) { - throw sqle; - } finally { - DBUtils.closeResultSet(rs); - DBUtils.closePreparedStatement(pstmt); + } catch (SQLException sqle) { + throw sqle; + } finally { + DBUtils.closeResultSet(rs); + DBUtils.closePreparedStatement(pstmt); - if (this.closeConnectionOnExit) { - DBUtils.closeConnection(connection); - } + if (this.closeConnectionOnExit) { + DBUtils.closeConnection(connection); + } - this.closed = true; - } - } + this.closed = true; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/IntegerKeyCollector.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/IntegerKeyCollector.java index c90ad568b12..abdbaf8ffdf 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/IntegerKeyCollector.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/IntegerKeyCollector.java @@ -13,23 +13,23 @@ public class IntegerKeyCollector implements GeneratedKeyCollector { - private Integer keyValue; - private int columnIndex = 1; + private Integer keyValue; + private int columnIndex = 1; - public IntegerKeyCollector() {} + public IntegerKeyCollector() {} - public IntegerKeyCollector(int columnIndex) { - super(); - this.columnIndex = columnIndex; - } + public IntegerKeyCollector(int columnIndex) { + super(); + this.columnIndex = columnIndex; + } - public void collect(ResultSet rs) throws SQLException { + public void collect(ResultSet rs) throws SQLException { - keyValue = rs.getInt(columnIndex); - } + keyValue = rs.getInt(columnIndex); + } - public Integer getKeyValue() { + public Integer getKeyValue() { - return keyValue; - } + return keyValue; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ObjectQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ObjectQuery.java index a125ce244f5..c07c2e9625a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ObjectQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/ObjectQuery.java @@ -17,39 +17,39 @@ public class ObjectQuery extends PopulatedQuery { - public ObjectQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { - super(connection, closeConnectionOnExit, query, bp); - } + public ObjectQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { + super(connection, closeConnectionOnExit, query, bp); + } - public ObjectQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { - super(dataSource, closeConnectionOnExit, query, bp); - } + public ObjectQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { + super(dataSource, closeConnectionOnExit, query, bp); + } - public ReturnType executeQuery() throws SQLException { + public ReturnType executeQuery() throws SQLException { - ResultSet rs = null; + ResultSet rs = null; - try { + try { - // Send query to database and store results. - rs = pstmt.executeQuery(); + // Send query to database and store results. + rs = pstmt.executeQuery(); - if (rs.next()) { - return this.beanPopulator.populate(rs); - } else { - return null; - } - } catch (SQLException sqle) { - throw sqle; - } finally { - DBUtils.closeResultSet(rs); - DBUtils.closePreparedStatement(pstmt); + if (rs.next()) { + return this.beanPopulator.populate(rs); + } else { + return null; + } + } catch (SQLException sqle) { + throw sqle; + } finally { + DBUtils.closeResultSet(rs); + DBUtils.closePreparedStatement(pstmt); - if (this.closeConnectionOnExit) { - DBUtils.closeConnection(connection); - } + if (this.closeConnectionOnExit) { + DBUtils.closeConnection(connection); + } - this.closed = true; - } - } + this.closed = true; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PopulatedQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PopulatedQuery.java index c4134cbdcae..589aa8bb091 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PopulatedQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PopulatedQuery.java @@ -15,19 +15,19 @@ public abstract class PopulatedQuery extends PreparedStatementQuery { - protected BeanResultSetPopulator beanPopulator; + protected BeanResultSetPopulator beanPopulator; - public PopulatedQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { - super(connection, closeConnectionOnExit, query); - this.beanPopulator = bp; - } + public PopulatedQuery(Connection connection, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { + super(connection, closeConnectionOnExit, query); + this.beanPopulator = bp; + } - public PopulatedQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { - super(dataSource, closeConnectionOnExit, query); - this.beanPopulator = bp; - } + public PopulatedQuery(DataSource dataSource, boolean closeConnectionOnExit, String query, BeanResultSetPopulator bp) throws SQLException { + super(dataSource, closeConnectionOnExit, query); + this.beanPopulator = bp; + } - public BeanResultSetPopulator getBeanPopulator() { - return beanPopulator; - } + public BeanResultSetPopulator getBeanPopulator() { + return beanPopulator; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PreparedStatementQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PreparedStatementQuery.java index 135add527e0..04eae63d564 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PreparedStatementQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/PreparedStatementQuery.java @@ -27,527 +27,527 @@ public abstract class PreparedStatementQuery { - protected Connection connection; - protected boolean closeConnectionOnExit; - protected PreparedStatement pstmt; - protected boolean closed; + protected Connection connection; + protected boolean closeConnectionOnExit; + protected PreparedStatement pstmt; + protected boolean closed; - public PreparedStatementQuery(Connection connection, boolean closeConnectionOnExit, String query) throws SQLException { - this.closeConnectionOnExit = closeConnectionOnExit; - this.connection = connection; + public PreparedStatementQuery(Connection connection, boolean closeConnectionOnExit, String query) throws SQLException { + this.closeConnectionOnExit = closeConnectionOnExit; + this.connection = connection; - try { - this.pstmt = this.getPreparedStatement(query); - } catch (SQLException e) { + try { + this.pstmt = this.getPreparedStatement(query); + } catch (SQLException e) { - this.abort(); + this.abort(); - throw e; - } - } + throw e; + } + } - protected PreparedStatement getPreparedStatement(String query) throws SQLException { + protected PreparedStatement getPreparedStatement(String query) throws SQLException { - return connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); - } + return connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); + } - public PreparedStatementQuery(DataSource dataSource, boolean closeConnectionOnExit, String query) throws SQLException { - this(dataSource.getConnection(), closeConnectionOnExit, query); - } + public PreparedStatementQuery(DataSource dataSource, boolean closeConnectionOnExit, String query) throws SQLException { + this(dataSource.getConnection(), closeConnectionOnExit, query); + } - public void setArray(int arg0, java.sql.Array arg1) throws SQLException { + public void setArray(int arg0, java.sql.Array arg1) throws SQLException { - try { + try { - pstmt.setArray(arg0, arg1); + pstmt.setArray(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setAsciiStream(int arg0, InputStream arg1, int arg2) throws SQLException { + public void setAsciiStream(int arg0, InputStream arg1, int arg2) throws SQLException { - try { + try { - pstmt.setAsciiStream(arg0, arg1, arg2); + pstmt.setAsciiStream(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setBigDecimal(int arg0, BigDecimal arg1) throws SQLException { + public void setBigDecimal(int arg0, BigDecimal arg1) throws SQLException { - try { + try { - pstmt.setBigDecimal(arg0, arg1); + pstmt.setBigDecimal(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setBinaryStream(int arg0, InputStream arg1, int arg2) throws SQLException { + public void setBinaryStream(int arg0, InputStream arg1, int arg2) throws SQLException { - try { + try { - pstmt.setBinaryStream(arg0, arg1, arg2); + pstmt.setBinaryStream(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setBlob(int arg0, Blob arg1) throws SQLException { + public void setBlob(int arg0, Blob arg1) throws SQLException { - try { + try { - pstmt.setBlob(arg0, arg1); + pstmt.setBlob(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setBoolean(int arg0, boolean arg1) throws SQLException { + public void setBoolean(int arg0, boolean arg1) throws SQLException { - try { + try { - pstmt.setBoolean(arg0, arg1); + pstmt.setBoolean(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setByte(int arg0, byte arg1) throws SQLException { + public void setByte(int arg0, byte arg1) throws SQLException { - try { + try { - pstmt.setByte(arg0, arg1); + pstmt.setByte(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setBytes(int arg0, byte[] arg1) throws SQLException { + public void setBytes(int arg0, byte[] arg1) throws SQLException { - try { + try { - pstmt.setBytes(arg0, arg1); + pstmt.setBytes(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setCharacterStream(int arg0, Reader arg1, int arg2) throws SQLException { + public void setCharacterStream(int arg0, Reader arg1, int arg2) throws SQLException { - try { + try { - pstmt.setCharacterStream(arg0, arg1, arg2); + pstmt.setCharacterStream(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setClob(int arg0, Clob arg1) throws SQLException { + public void setClob(int arg0, Clob arg1) throws SQLException { - try { + try { - pstmt.setClob(arg0, arg1); + pstmt.setClob(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setCursorName(String arg0) throws SQLException { + public void setCursorName(String arg0) throws SQLException { - try { + try { - pstmt.setCursorName(arg0); + pstmt.setCursorName(arg0); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setDate(int arg0, Date arg1, Calendar arg2) throws SQLException { + public void setDate(int arg0, Date arg1, Calendar arg2) throws SQLException { - try { + try { - pstmt.setDate(arg0, arg1, arg2); + pstmt.setDate(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setDate(int arg0, Date arg1) throws SQLException { + public void setDate(int arg0, Date arg1) throws SQLException { - try { + try { - pstmt.setDate(arg0, arg1); + pstmt.setDate(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setDouble(int arg0, double arg1) throws SQLException { + public void setDouble(int arg0, double arg1) throws SQLException { - try { + try { - pstmt.setDouble(arg0, arg1); + pstmt.setDouble(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setEscapeProcessing(boolean arg0) throws SQLException { + public void setEscapeProcessing(boolean arg0) throws SQLException { - try { + try { - pstmt.setEscapeProcessing(arg0); + pstmt.setEscapeProcessing(arg0); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setFetchDirection(int arg0) throws SQLException { + public void setFetchDirection(int arg0) throws SQLException { - try { + try { - pstmt.setFetchDirection(arg0); + pstmt.setFetchDirection(arg0); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setFetchSize(int arg0) throws SQLException { + public void setFetchSize(int arg0) throws SQLException { - try { + try { - pstmt.setFetchSize(arg0); + pstmt.setFetchSize(arg0); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setFloat(int arg0, float arg1) throws SQLException { + public void setFloat(int arg0, float arg1) throws SQLException { - try { + try { - pstmt.setFloat(arg0, arg1); + pstmt.setFloat(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setInt(int arg0, int arg1) throws SQLException { + public void setInt(int arg0, int arg1) throws SQLException { - try { + try { - pstmt.setInt(arg0, arg1); + pstmt.setInt(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setLong(int arg0, long arg1) throws SQLException { + public void setLong(int arg0, long arg1) throws SQLException { - try { + try { - pstmt.setLong(arg0, arg1); + pstmt.setLong(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setMaxFieldSize(int arg0) throws SQLException { + public void setMaxFieldSize(int arg0) throws SQLException { - try { + try { - pstmt.setMaxFieldSize(arg0); + pstmt.setMaxFieldSize(arg0); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setMaxRows(int arg0) throws SQLException { + public void setMaxRows(int arg0) throws SQLException { - try { + try { - pstmt.setMaxRows(arg0); + pstmt.setMaxRows(arg0); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setNull(int arg0, int arg1, String arg2) throws SQLException { + public void setNull(int arg0, int arg1, String arg2) throws SQLException { - try { + try { - pstmt.setNull(arg0, arg1, arg2); + pstmt.setNull(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setNull(int arg0, int arg1) throws SQLException { + public void setNull(int arg0, int arg1) throws SQLException { - try { + try { - pstmt.setNull(arg0, arg1); + pstmt.setNull(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setObject(int arg0, Object arg1, int arg2, int arg3) throws SQLException { + public void setObject(int arg0, Object arg1, int arg2, int arg3) throws SQLException { - try { + try { - pstmt.setObject(arg0, arg1, arg2, arg3); + pstmt.setObject(arg0, arg1, arg2, arg3); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setObject(int arg0, Object arg1, int arg2) throws SQLException { + public void setObject(int arg0, Object arg1, int arg2) throws SQLException { - try { + try { - pstmt.setObject(arg0, arg1, arg2); + pstmt.setObject(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setObject(int arg0, Object arg1) throws SQLException { + public void setObject(int arg0, Object arg1) throws SQLException { - try { + try { - pstmt.setObject(arg0, arg1); + pstmt.setObject(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setQueryTimeout(int arg0) throws SQLException { + public void setQueryTimeout(int arg0) throws SQLException { - try { + try { - pstmt.setQueryTimeout(arg0); + pstmt.setQueryTimeout(arg0); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setRef(int arg0, Ref arg1) throws SQLException { + public void setRef(int arg0, Ref arg1) throws SQLException { - try { + try { - pstmt.setRef(arg0, arg1); + pstmt.setRef(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setShort(int arg0, short arg1) throws SQLException { + public void setShort(int arg0, short arg1) throws SQLException { - try { + try { - pstmt.setShort(arg0, arg1); + pstmt.setShort(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setString(int arg0, String arg1) throws SQLException { + public void setString(int arg0, String arg1) throws SQLException { - try { + try { - pstmt.setString(arg0, arg1); + pstmt.setString(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setTime(int arg0, Time arg1, Calendar arg2) throws SQLException { + public void setTime(int arg0, Time arg1, Calendar arg2) throws SQLException { - try { + try { - pstmt.setTime(arg0, arg1, arg2); + pstmt.setTime(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setTime(int arg0, Time arg1) throws SQLException { + public void setTime(int arg0, Time arg1) throws SQLException { - try { + try { - pstmt.setTime(arg0, arg1); + pstmt.setTime(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setTimestamp(int arg0, Timestamp arg1, Calendar arg2) throws SQLException { + public void setTimestamp(int arg0, Timestamp arg1, Calendar arg2) throws SQLException { - try { + try { - pstmt.setTimestamp(arg0, arg1, arg2); + pstmt.setTimestamp(arg0, arg1, arg2); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setTimestamp(int arg0, Timestamp arg1) throws SQLException { + public void setTimestamp(int arg0, Timestamp arg1) throws SQLException { - try { + try { - pstmt.setTimestamp(arg0, arg1); + pstmt.setTimestamp(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public void setURL(int arg0, URL arg1) throws SQLException { + public void setURL(int arg0, URL arg1) throws SQLException { - try { + try { - pstmt.setURL(arg0, arg1); + pstmt.setURL(arg0, arg1); - } catch (SQLException e) { + } catch (SQLException e) { - this.abort(); - throw e; - } - } + this.abort(); + throw e; + } + } - public boolean isCloseConnectionOnExit() { - return closeConnectionOnExit; - } + public boolean isCloseConnectionOnExit() { + return closeConnectionOnExit; + } - public void abort() { + public void abort() { - DBUtils.closePreparedStatement(pstmt); + DBUtils.closePreparedStatement(pstmt); - if (this.closeConnectionOnExit) { + if (this.closeConnectionOnExit) { - DBUtils.closeConnection(connection); - } + DBUtils.closeConnection(connection); + } - this.closed = true; - } + this.closed = true; + } - public static void autoCloseQuery(PreparedStatementQuery query){ + public static void autoCloseQuery(PreparedStatementQuery query){ - if(query != null && !query.isClosed()){ + if(query != null && !query.isClosed()){ - query.abort(); - } - } + query.abort(); + } + } - public boolean isClosed() { - return closed; - } + public boolean isClosed() { + return closed; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/UpdateQuery.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/UpdateQuery.java index 1813faf296b..dc6d73b8506 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/UpdateQuery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/querys/UpdateQuery.java @@ -18,79 +18,79 @@ public class UpdateQuery extends PreparedStatementQuery { - private Integer affectedRows; + private Integer affectedRows; - public UpdateQuery(Connection connection, boolean closeConnectionOnExit, String query) throws SQLException { + public UpdateQuery(Connection connection, boolean closeConnectionOnExit, String query) throws SQLException { - super(connection, closeConnectionOnExit, query); - } + super(connection, closeConnectionOnExit, query); + } - public UpdateQuery(DataSource dataSource, boolean closeConnectionOnExit, String query) throws SQLException { + public UpdateQuery(DataSource dataSource, boolean closeConnectionOnExit, String query) throws SQLException { - super(dataSource, closeConnectionOnExit, query); - } + super(dataSource, closeConnectionOnExit, query); + } - public void executeUpdate() throws SQLException { + public void executeUpdate() throws SQLException { - ResultSet rs = null; + ResultSet rs = null; - try { - affectedRows = this.pstmt.executeUpdate(); + try { + affectedRows = this.pstmt.executeUpdate(); - } catch (SQLException sqle) { - throw sqle; - } finally { - DBUtils.closeResultSet(rs); - DBUtils.closePreparedStatement(pstmt); + } catch (SQLException sqle) { + throw sqle; + } finally { + DBUtils.closeResultSet(rs); + DBUtils.closePreparedStatement(pstmt); - if (this.closeConnectionOnExit) { - DBUtils.closeConnection(connection); - } + if (this.closeConnectionOnExit) { + DBUtils.closeConnection(connection); + } - this.closed = true; - } - } + this.closed = true; + } + } - public void executeUpdate(List keyCollectors) throws SQLException { + public void executeUpdate(List keyCollectors) throws SQLException { - ResultSet rs = null; + ResultSet rs = null; - try { - affectedRows = this.pstmt.executeUpdate(); + try { + affectedRows = this.pstmt.executeUpdate(); - if (affectedRows > 0) { - rs = pstmt.getGeneratedKeys(); + if (affectedRows > 0) { + rs = pstmt.getGeneratedKeys(); - if (rs.next()) { + if (rs.next()) { - for (GeneratedKeyCollector keyCollector : keyCollectors) { + for (GeneratedKeyCollector keyCollector : keyCollectors) { - keyCollector.collect(rs); - } - } - } + keyCollector.collect(rs); + } + } + } - } catch (SQLException sqle) { - throw sqle; - } finally { - DBUtils.closeResultSet(rs); - DBUtils.closePreparedStatement(pstmt); + } catch (SQLException sqle) { + throw sqle; + } finally { + DBUtils.closeResultSet(rs); + DBUtils.closePreparedStatement(pstmt); - if (this.closeConnectionOnExit) { - DBUtils.closeConnection(connection); - } + if (this.closeConnectionOnExit) { + DBUtils.closeConnection(connection); + } - this.closed = true; - } - } + this.closed = true; + } + } - public void executeUpdate(GeneratedKeyCollector... keyCollectors) throws SQLException { + public void executeUpdate(GeneratedKeyCollector... keyCollectors) throws SQLException { - executeUpdate(Arrays.asList(keyCollectors)); - } + executeUpdate(Arrays.asList(keyCollectors)); + } - public Integer getAffectedRows() { + public Integer getAffectedRows() { - return affectedRows; - } + return affectedRows; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptDAO.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptDAO.java index 5a488b787b3..99dda7fc58e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptDAO.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptDAO.java @@ -19,62 +19,62 @@ import java.util.List; public class MySQLScriptDAO implements ScriptDAO { - - protected final DataSource dataSource; - public MySQLScriptDAO(DataSource dataSource) { - this.dataSource = dataSource; - } + protected final DataSource dataSource; - public void executeScript(InputStream inputStream) throws SQLException, IOException { + public MySQLScriptDAO(DataSource dataSource) { + this.dataSource = dataSource; + } - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - - StringBuilder sb = new StringBuilder(); + public void executeScript(InputStream inputStream) throws SQLException, IOException { - String line = null; - try { - while ((line = reader.readLine()) != null) { - sb.append(line + "\n"); - } - } catch (IOException e) { + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + + StringBuilder sb = new StringBuilder(); + + String line = null; + try { + while ((line = reader.readLine()) != null) { + sb.append(line + "\n"); + } + } catch (IOException e) { + throw e; + } finally { + try { + reader.close(); + inputStream.close(); + } catch (IOException e) { throw e; - } finally { - try { - reader.close(); - inputStream.close(); - } catch (IOException e) { - throw e; - } - } - - this.executeScript(sb.toString()); - - } - - public void executeScript(String script) throws SQLException { - - TransactionHandler transactionHandler = null; - UpdateQuery updateQuery; - - ScriptUtility scriptUtility = new MySQLScriptUtility(); - List statements = scriptUtility.getStatements(script); - - try { - - transactionHandler = new TransactionHandler(this.dataSource); - - for(String query : statements) { - updateQuery = transactionHandler.getUpdateQuery(query.toString()); - updateQuery.executeUpdate(); - } - - transactionHandler.commit(); - - } finally { - - TransactionHandler.autoClose(transactionHandler); - - } - } + } + } + + this.executeScript(sb.toString()); + + } + + public void executeScript(String script) throws SQLException { + + TransactionHandler transactionHandler = null; + UpdateQuery updateQuery; + + ScriptUtility scriptUtility = new MySQLScriptUtility(); + List statements = scriptUtility.getStatements(script); + + try { + + transactionHandler = new TransactionHandler(this.dataSource); + + for(String query : statements) { + updateQuery = transactionHandler.getUpdateQuery(query.toString()); + updateQuery.executeUpdate(); + } + + transactionHandler.commit(); + + } finally { + + TransactionHandler.autoClose(transactionHandler); + + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptUtility.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptUtility.java index 9359f0e9b14..5d1cb0631a2 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptUtility.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/MySQLScriptUtility.java @@ -14,183 +14,183 @@ public class MySQLScriptUtility implements ScriptUtility { - private static final String MULTI_LINE_COMMENT_START_SYMBOL = "\\/\\*"; - private static final String MULTI_LINE_COMMENT_END_SYMBOL = "\\*\\/"; - - private static final String LINE_COMMENT_START_SYMBOL = "^--|^#"; - private static final String LINE_COMMENT_END_SYMBOL = "\\n"; - - private static final String STRING_TYPE1_SYMBOL = "\'"; - private static final String STRING_TYPE2_SYMBOL = "\""; - - private static final String STATEMENT_TERMINATOR = ";"; - - public List getStatements(String script) { - - List statements = new ArrayList(); - - List allSymbols = new ArrayList(); - allSymbols.addAll(this.findSymbols(STRING_TYPE1_SYMBOL, script)); - allSymbols.addAll(this.findSymbols(STRING_TYPE2_SYMBOL, script)); - allSymbols.addAll(this.findSymbols(LINE_COMMENT_START_SYMBOL, script)); - allSymbols.addAll(this.findSymbols(LINE_COMMENT_END_SYMBOL, script)); - allSymbols.addAll(this.findSymbols(MULTI_LINE_COMMENT_START_SYMBOL, script)); - allSymbols.addAll(this.findSymbols(MULTI_LINE_COMMENT_END_SYMBOL, script)); - - String str = script; - int startIndex = 0; - for(Symbol terminator : this.getValidSymbols(this.findSymbols(STATEMENT_TERMINATOR, script), this.createRegions(this.getValidSymbols(allSymbols)))) { - str = script.substring(startIndex, terminator.getOffsets().getEnd()); - startIndex += str.length(); - statements.add(str); - } - - return statements; - } - - /** - * Searches the sequence for symbols - * @param regex - A regular expression used to find the symbol (a sequence) within the sequence - * @param sequence - The haystack in which to search for symbols - * @return - */ - private List findSymbols(String regex, String sequence) { - List symbols = new ArrayList(); - Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE); - Matcher matcher = pattern.matcher(sequence); - while(matcher.find()) { - symbols.add(new Symbol(regex, new Offsets(matcher.start(),matcher.end()))); - } - return symbols; - } - - /** - * Creates regions between supplied symbols - * @param symbols - * @return - */ - private List createRegions(List symbols) { - - List regions = new ArrayList(); - - Symbol stringType1Symbol = null; - Symbol stringType2Symbol = null; - Symbol lineCommentStartSymbol = null; - Symbol multiLineCommentStartSymbol = null; - - for(Symbol symbol : symbols) { - if(symbol.getKey().equals(STRING_TYPE1_SYMBOL)) { - if(stringType1Symbol != null) { - regions.add(new Region(stringType1Symbol, symbol)); - stringType1Symbol = null; - } else { - stringType1Symbol = symbol; - } - } else if(symbol.getKey().equals(STRING_TYPE2_SYMBOL)) { - - if(stringType2Symbol != null) { - regions.add(new Region(stringType2Symbol, symbol)); - stringType2Symbol = null; - } else { - stringType2Symbol = symbol; - } - } else if(symbol.getKey().equals(LINE_COMMENT_END_SYMBOL) && lineCommentStartSymbol != null) { - regions.add(new Region(lineCommentStartSymbol, symbol)); - lineCommentStartSymbol = null; - } else if(symbol.getKey().equals(LINE_COMMENT_START_SYMBOL)) { - lineCommentStartSymbol = symbol; - } else if(symbol.getKey().equals(MULTI_LINE_COMMENT_END_SYMBOL) && multiLineCommentStartSymbol != null) { - regions.add(new Region(multiLineCommentStartSymbol, symbol)); - multiLineCommentStartSymbol = null; - } else if(symbol.getKey().equals(MULTI_LINE_COMMENT_START_SYMBOL)) { - multiLineCommentStartSymbol = symbol; - } - - } - - if(stringType1Symbol != null) { - regions.add(new Region(stringType1Symbol, null)); - stringType1Symbol = null; - } - if(stringType2Symbol != null) { - regions.add(new Region(stringType2Symbol, null)); - stringType2Symbol = null; - } - if(lineCommentStartSymbol != null) { - regions.add(new Region(lineCommentStartSymbol, null)); - lineCommentStartSymbol = null; - } - if(multiLineCommentStartSymbol != null) { - regions.add(new Region(multiLineCommentStartSymbol, null)); - multiLineCommentStartSymbol = null; - } - return regions; - } - - /** - * Returns valid symbols from a collection of symbols - * @param symbols - * @return - */ - private List getValidSymbols(List symbols) { - - List validSymbols = new ArrayList(); - - boolean withinStringType1 = false; - boolean withinStringType2 = false; - boolean withinLineComment = false; - boolean withinMultiLineComment = false; - - Collections.sort(symbols, new Symbol.SymbolStartComparator()); - - for(Symbol symbol : symbols) { - if(!withinStringType1 && !withinStringType2 && !withinLineComment && !withinMultiLineComment) { - validSymbols.add(symbol); - if(symbol.getKey().equals(STRING_TYPE1_SYMBOL)) { - withinStringType1 = true; - } else if(symbol.getKey().equals(STRING_TYPE2_SYMBOL)) { - withinStringType2 = true; - } else if(symbol.getKey().equals(LINE_COMMENT_START_SYMBOL)) { - withinLineComment = true; - } else if(symbol.getKey().equals(MULTI_LINE_COMMENT_START_SYMBOL)) { - withinMultiLineComment = true; - } - } else if(withinStringType1 && symbol.getKey().equals(STRING_TYPE1_SYMBOL)) { - validSymbols.add(symbol); - withinStringType1 = false; - } else if(withinStringType2 && symbol.getKey().equals(STRING_TYPE2_SYMBOL)) { - validSymbols.add(symbol); - withinStringType2 = false; - } else if(withinLineComment && symbol.getKey().equals(LINE_COMMENT_END_SYMBOL)) { - validSymbols.add(symbol); - withinLineComment = false; - } else if(withinMultiLineComment && symbol.getKey().equals(MULTI_LINE_COMMENT_END_SYMBOL)) { - validSymbols.add(symbol); - withinMultiLineComment = false; - } - } - return validSymbols; - } - - /** - * Returns valid symbols from a set of symbols and regions - * @param symbols - symbols to validate against supplied regions - * @param invalidRegions - invalid regions. Symbols within these regions are considered invalid. - * @return - */ - private List getValidSymbols(List symbols, List invalidRegions) { - - List validSymbols = new ArrayList(); - - symbol: - for(Symbol symbol : symbols) { - for(Region invalidRegion : invalidRegions) { - if(symbol.getOffsets().getStart() >= invalidRegion.getStart() && (invalidRegion.getEnd() == null || symbol.getOffsets().getStart() < invalidRegion.getEnd())) { - continue symbol; - } - } - validSymbols.add(symbol); - } - return validSymbols; - } + private static final String MULTI_LINE_COMMENT_START_SYMBOL = "\\/\\*"; + private static final String MULTI_LINE_COMMENT_END_SYMBOL = "\\*\\/"; + + private static final String LINE_COMMENT_START_SYMBOL = "^--|^#"; + private static final String LINE_COMMENT_END_SYMBOL = "\\n"; + + private static final String STRING_TYPE1_SYMBOL = "\'"; + private static final String STRING_TYPE2_SYMBOL = "\""; + + private static final String STATEMENT_TERMINATOR = ";"; + + public List getStatements(String script) { + + List statements = new ArrayList(); + + List allSymbols = new ArrayList(); + allSymbols.addAll(this.findSymbols(STRING_TYPE1_SYMBOL, script)); + allSymbols.addAll(this.findSymbols(STRING_TYPE2_SYMBOL, script)); + allSymbols.addAll(this.findSymbols(LINE_COMMENT_START_SYMBOL, script)); + allSymbols.addAll(this.findSymbols(LINE_COMMENT_END_SYMBOL, script)); + allSymbols.addAll(this.findSymbols(MULTI_LINE_COMMENT_START_SYMBOL, script)); + allSymbols.addAll(this.findSymbols(MULTI_LINE_COMMENT_END_SYMBOL, script)); + + String str = script; + int startIndex = 0; + for(Symbol terminator : this.getValidSymbols(this.findSymbols(STATEMENT_TERMINATOR, script), this.createRegions(this.getValidSymbols(allSymbols)))) { + str = script.substring(startIndex, terminator.getOffsets().getEnd()); + startIndex += str.length(); + statements.add(str); + } + + return statements; + } + + /** + * Searches the sequence for symbols + * @param regex - A regular expression used to find the symbol (a sequence) within the sequence + * @param sequence - The haystack in which to search for symbols + * @return + */ + private List findSymbols(String regex, String sequence) { + List symbols = new ArrayList(); + Pattern pattern = Pattern.compile(regex,Pattern.MULTILINE); + Matcher matcher = pattern.matcher(sequence); + while(matcher.find()) { + symbols.add(new Symbol(regex, new Offsets(matcher.start(),matcher.end()))); + } + return symbols; + } + + /** + * Creates regions between supplied symbols + * @param symbols + * @return + */ + private List createRegions(List symbols) { + + List regions = new ArrayList(); + + Symbol stringType1Symbol = null; + Symbol stringType2Symbol = null; + Symbol lineCommentStartSymbol = null; + Symbol multiLineCommentStartSymbol = null; + + for(Symbol symbol : symbols) { + if(symbol.getKey().equals(STRING_TYPE1_SYMBOL)) { + if(stringType1Symbol != null) { + regions.add(new Region(stringType1Symbol, symbol)); + stringType1Symbol = null; + } else { + stringType1Symbol = symbol; + } + } else if(symbol.getKey().equals(STRING_TYPE2_SYMBOL)) { + + if(stringType2Symbol != null) { + regions.add(new Region(stringType2Symbol, symbol)); + stringType2Symbol = null; + } else { + stringType2Symbol = symbol; + } + } else if(symbol.getKey().equals(LINE_COMMENT_END_SYMBOL) && lineCommentStartSymbol != null) { + regions.add(new Region(lineCommentStartSymbol, symbol)); + lineCommentStartSymbol = null; + } else if(symbol.getKey().equals(LINE_COMMENT_START_SYMBOL)) { + lineCommentStartSymbol = symbol; + } else if(symbol.getKey().equals(MULTI_LINE_COMMENT_END_SYMBOL) && multiLineCommentStartSymbol != null) { + regions.add(new Region(multiLineCommentStartSymbol, symbol)); + multiLineCommentStartSymbol = null; + } else if(symbol.getKey().equals(MULTI_LINE_COMMENT_START_SYMBOL)) { + multiLineCommentStartSymbol = symbol; + } + + } + + if(stringType1Symbol != null) { + regions.add(new Region(stringType1Symbol, null)); + stringType1Symbol = null; + } + if(stringType2Symbol != null) { + regions.add(new Region(stringType2Symbol, null)); + stringType2Symbol = null; + } + if(lineCommentStartSymbol != null) { + regions.add(new Region(lineCommentStartSymbol, null)); + lineCommentStartSymbol = null; + } + if(multiLineCommentStartSymbol != null) { + regions.add(new Region(multiLineCommentStartSymbol, null)); + multiLineCommentStartSymbol = null; + } + return regions; + } + + /** + * Returns valid symbols from a collection of symbols + * @param symbols + * @return + */ + private List getValidSymbols(List symbols) { + + List validSymbols = new ArrayList(); + + boolean withinStringType1 = false; + boolean withinStringType2 = false; + boolean withinLineComment = false; + boolean withinMultiLineComment = false; + + Collections.sort(symbols, new Symbol.SymbolStartComparator()); + + for(Symbol symbol : symbols) { + if(!withinStringType1 && !withinStringType2 && !withinLineComment && !withinMultiLineComment) { + validSymbols.add(symbol); + if(symbol.getKey().equals(STRING_TYPE1_SYMBOL)) { + withinStringType1 = true; + } else if(symbol.getKey().equals(STRING_TYPE2_SYMBOL)) { + withinStringType2 = true; + } else if(symbol.getKey().equals(LINE_COMMENT_START_SYMBOL)) { + withinLineComment = true; + } else if(symbol.getKey().equals(MULTI_LINE_COMMENT_START_SYMBOL)) { + withinMultiLineComment = true; + } + } else if(withinStringType1 && symbol.getKey().equals(STRING_TYPE1_SYMBOL)) { + validSymbols.add(symbol); + withinStringType1 = false; + } else if(withinStringType2 && symbol.getKey().equals(STRING_TYPE2_SYMBOL)) { + validSymbols.add(symbol); + withinStringType2 = false; + } else if(withinLineComment && symbol.getKey().equals(LINE_COMMENT_END_SYMBOL)) { + validSymbols.add(symbol); + withinLineComment = false; + } else if(withinMultiLineComment && symbol.getKey().equals(MULTI_LINE_COMMENT_END_SYMBOL)) { + validSymbols.add(symbol); + withinMultiLineComment = false; + } + } + return validSymbols; + } + + /** + * Returns valid symbols from a set of symbols and regions + * @param symbols - symbols to validate against supplied regions + * @param invalidRegions - invalid regions. Symbols within these regions are considered invalid. + * @return + */ + private List getValidSymbols(List symbols, List invalidRegions) { + + List validSymbols = new ArrayList(); + + symbol: + for(Symbol symbol : symbols) { + for(Region invalidRegion : invalidRegions) { + if(symbol.getOffsets().getStart() >= invalidRegion.getStart() && (invalidRegion.getEnd() == null || symbol.getOffsets().getStart() < invalidRegion.getEnd())) { + continue symbol; + } + } + validSymbols.add(symbol); + } + return validSymbols; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Offsets.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Offsets.java index 59e07dcea37..09a0d39be31 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Offsets.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Offsets.java @@ -13,20 +13,20 @@ */ public class Offsets { - private final Integer start; - private final Integer end; + private final Integer start; + private final Integer end; - public Offsets(Integer start, Integer end) { - super(); - this.start = start; - this.end = end; - } + public Offsets(Integer start, Integer end) { + super(); + this.start = start; + this.end = end; + } - public Integer getStart() { - return start; - } + public Integer getStart() { + return start; + } - public Integer getEnd() { - return end; - } + public Integer getEnd() { + return end; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Region.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Region.java index 9b0a07bbffe..fe76f564160 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Region.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Region.java @@ -13,21 +13,21 @@ */ public class Region { - private final Symbol start; - private final Symbol end; + private final Symbol start; + private final Symbol end; - public Region(Symbol start, Symbol end) { - this.start = start; - this.end = end; - } + public Region(Symbol start, Symbol end) { + this.start = start; + this.end = end; + } + + public Integer getStart() { + return this.start.getOffsets().getEnd(); + } + + public Integer getEnd() { + return this.end.getOffsets().getStart(); + } - public Integer getStart() { - return this.start.getOffsets().getEnd(); - } - public Integer getEnd() { - return this.end.getOffsets().getStart(); - } - - } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptDAO.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptDAO.java index 056aaa50359..60dfdb8b843 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptDAO.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptDAO.java @@ -13,8 +13,8 @@ public interface ScriptDAO { - void executeScript(InputStream inputStream) throws SQLException, IOException; - - void executeScript(String script) throws SQLException; + void executeScript(InputStream inputStream) throws SQLException, IOException; + + void executeScript(String script) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptUtility.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptUtility.java index 8bf7754097a..ef439b8dfd3 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptUtility.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/ScriptUtility.java @@ -10,6 +10,6 @@ public interface ScriptUtility { - List getStatements(String script); - + List getStatements(String script); + } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Symbol.java b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Symbol.java index 059bd215c9b..aa3098e2693 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Symbol.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/dao/script/Symbol.java @@ -13,25 +13,25 @@ public class Symbol { - public Symbol(String key, Offsets offsets) { - this.key = key; - this.offsets = offsets; - } + public Symbol(String key, Offsets offsets) { + this.key = key; + this.offsets = offsets; + } - private final String key; - private final Offsets offsets; + private final String key; + private final Offsets offsets; - public Offsets getOffsets() { - return this.offsets; - } + public Offsets getOffsets() { + return this.offsets; + } - public String getKey() { - return this.key; - } - - public static class SymbolStartComparator implements Comparator { - public int compare(Symbol o1, Symbol o2) { - return o1.getOffsets().getStart().compareTo(o2.getOffsets().getStart()); - } - } + public String getKey() { + return this.key; + } + + public static class SymbolStartComparator implements Comparator { + public int compare(Symbol o1, Symbol o2) { + return o1.getOffsets().getStart().compareTo(o2.getOffsets().getStart()); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/datatypes/Matrix.java b/eagledns/src/main/java/se/unlogic/standardutils/datatypes/Matrix.java index e4d02a52f2c..ebc47ac26a5 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/datatypes/Matrix.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/datatypes/Matrix.java @@ -12,42 +12,42 @@ public class Matrix { - - private CellType[][] matrix; - - @SuppressWarnings("unchecked") - public Matrix(int rows, int cols){ - this.matrix = (CellType[][])(new Object[rows][cols]); - } - - public List getRow(int rowPos){ - return Arrays.asList(this.matrix[rowPos]); - } - - public List getColumn(int columnPos){ - - ArrayList columnCells = new ArrayList(this.getColumnCount()); - - for(CellType[] row : this.matrix){ - columnCells.add(row[columnPos]); - } - - return columnCells; - } - - public CellType getCell(int rowPos , int colPos){ - return this.matrix[rowPos][colPos]; - } - - public void setCell(int rowPos , int colPos, CellType cell){ - this.matrix[rowPos][colPos] = cell; - } - - public int getRowCount(){ - return this.matrix.length; - } - - public int getColumnCount(){ - return this.matrix[0].length; - } + + private CellType[][] matrix; + + @SuppressWarnings("unchecked") + public Matrix(int rows, int cols){ + this.matrix = (CellType[][])(new Object[rows][cols]); + } + + public List getRow(int rowPos){ + return Arrays.asList(this.matrix[rowPos]); + } + + public List getColumn(int columnPos){ + + ArrayList columnCells = new ArrayList(this.getColumnCount()); + + for(CellType[] row : this.matrix){ + columnCells.add(row[columnPos]); + } + + return columnCells; + } + + public CellType getCell(int rowPos , int colPos){ + return this.matrix[rowPos][colPos]; + } + + public void setCell(int rowPos , int colPos, CellType cell){ + this.matrix[rowPos][colPos] = cell; + } + + public int getRowCount(){ + return this.matrix.length; + } + + public int getColumnCount(){ + return this.matrix[0].length; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/datatypes/SimpleEntry.java b/eagledns/src/main/java/se/unlogic/standardutils/datatypes/SimpleEntry.java index 07949d1998b..3063639d53d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/datatypes/SimpleEntry.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/datatypes/SimpleEntry.java @@ -12,67 +12,67 @@ public class SimpleEntry implements Entry, Serializable{ - private static final long serialVersionUID = 2017770345032632182L; + private static final long serialVersionUID = 2017770345032632182L; - public SimpleEntry(KeyType key, ValueType value) { - super(); - this.key = key; - this.value = value; - } + public SimpleEntry(KeyType key, ValueType value) { + super(); + this.key = key; + this.value = value; + } - private final KeyType key; - private ValueType value; + private final KeyType key; + private ValueType value; - public ValueType getValue() { - return value; - } - public ValueType setValue(ValueType value) { + public ValueType getValue() { + return value; + } + public ValueType setValue(ValueType value) { - ValueType oldValue = this.value; + ValueType oldValue = this.value; - this.value = value; + this.value = value; - return oldValue; - } - public KeyType getKey() { - return key; - } - @Override - public int hashCode() { + return oldValue; + } + public KeyType getKey() { + return key; + } + @Override + public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SimpleEntry other = (SimpleEntry) obj; - if (key == null) { - if (other.key != null) { - return false; - } - } else if (!key.equals(other.key)) { - return false; - } - if (value == null) { - if (other.value != null) { - return false; - } - } else if (!value.equals(other.value)) { - return false; - } - return true; - } + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + SimpleEntry other = (SimpleEntry) obj; + if (key == null) { + if (other.key != null) { + return false; + } + } else if (!key.equals(other.key)) { + return false; + } + if (value == null) { + if (other.value != null) { + return false; + } + } else if (!value.equals(other.value)) { + return false; + } + return true; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/date/DateStringyfier.java b/eagledns/src/main/java/se/unlogic/standardutils/date/DateStringyfier.java index 776c85d957d..1864a88f995 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/date/DateStringyfier.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/date/DateStringyfier.java @@ -7,9 +7,9 @@ public class DateStringyfier implements Stringyfier { - public String format(Object bean) { + public String format(Object bean) { - return DateUtils.DATE_FORMATTER.format((Date)bean); - } + return DateUtils.DATE_FORMATTER.format((Date)bean); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/date/DateUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/date/DateUtils.java index 134f858acfb..82ae4162c8a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/date/DateUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/date/DateUtils.java @@ -15,72 +15,72 @@ public class DateUtils { - public static final SimpleDateFormat DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - public static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); - public static final SimpleDateFormat YEAR_FORMATTER = new SimpleDateFormat("yyyy"); + public static final SimpleDateFormat DATE_TIME_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + public static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); + public static final SimpleDateFormat YEAR_FORMATTER = new SimpleDateFormat("yyyy"); - public static boolean isValidDate(DateFormat sdf, String date) { + public static boolean isValidDate(DateFormat sdf, String date) { - try { - sdf.parse(date); - } catch (ParseException e) { - return false; - } catch (RuntimeException e) { - return false; - } - return true; - } + try { + sdf.parse(date); + } catch (ParseException e) { + return false; + } catch (RuntimeException e) { + return false; + } + return true; + } - public static Date getDate(DateFormat sdf, String date) { + public static Date getDate(DateFormat sdf, String date) { - try { - return sdf.parse(date); - } catch (ParseException e) { - return null; - } catch (RuntimeException e) { - return null; - } - } + try { + return sdf.parse(date); + } catch (ParseException e) { + return null; + } catch (RuntimeException e) { + return null; + } + } - public static long daysBetween(Date startDate, Date endDate) { + public static long daysBetween(Date startDate, Date endDate) { - Calendar start = Calendar.getInstance(); - start.setTime(startDate); + Calendar start = Calendar.getInstance(); + start.setTime(startDate); - Calendar end = Calendar.getInstance(); - end.setTime(endDate); + Calendar end = Calendar.getInstance(); + end.setTime(endDate); - return daysBetween(start, end); - } + return daysBetween(start, end); + } - public static long daysBetween(Calendar startDate, Calendar endDate) { + public static long daysBetween(Calendar startDate, Calendar endDate) { - startDate = (Calendar) startDate.clone(); + startDate = (Calendar) startDate.clone(); - long daysBetween = 0; + long daysBetween = 0; - while (startDate.get(Calendar.YEAR) < endDate.get(Calendar.YEAR)) { + while (startDate.get(Calendar.YEAR) < endDate.get(Calendar.YEAR)) { - if(startDate.get(Calendar.DAY_OF_YEAR) != 1){ + if(startDate.get(Calendar.DAY_OF_YEAR) != 1){ - int diff = startDate.getMaximum(Calendar.DAY_OF_YEAR) - startDate.get(Calendar.DAY_OF_YEAR); + int diff = startDate.getMaximum(Calendar.DAY_OF_YEAR) - startDate.get(Calendar.DAY_OF_YEAR); - diff++; + diff++; - startDate.add(Calendar.DAY_OF_YEAR, diff); + startDate.add(Calendar.DAY_OF_YEAR, diff); - daysBetween += diff; + daysBetween += diff; - }else{ + }else{ - daysBetween += startDate.getMaximum(Calendar.DAY_OF_YEAR); + daysBetween += startDate.getMaximum(Calendar.DAY_OF_YEAR); - startDate.add(Calendar.YEAR, 1); - } - } + startDate.add(Calendar.YEAR, 1); + } + } - daysBetween += endDate.get(Calendar.DAY_OF_YEAR) - startDate.get(Calendar.DAY_OF_YEAR); + daysBetween += endDate.get(Calendar.DAY_OF_YEAR) - startDate.get(Calendar.DAY_OF_YEAR); - return daysBetween; - } + return daysBetween; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/db/ConnectionHandler.java b/eagledns/src/main/java/se/unlogic/standardutils/db/ConnectionHandler.java index 16195ad8662..6058f87e3f0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/db/ConnectionHandler.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/db/ConnectionHandler.java @@ -16,35 +16,35 @@ @Deprecated public class ConnectionHandler { - private DataSource datasource = null; - - public ConnectionHandler(String datasource) throws NamingException{ - setDataSource(datasource); - } - - public ConnectionHandler(DataSource datasource){ - setDataSource(datasource); - } - - public void setDataSource(DataSource ds){ - this.datasource = ds; - } - - public void setDataSource(String datasource) throws NamingException{ - Context initContext = new InitialContext(); - Context envContext = (Context)initContext.lookup("java:/comp/env"); - this.datasource = (DataSource)envContext.lookup(datasource); - } - - public DataSource getDataSource(){ - return this.datasource; - } - - public Connection getConnection() throws SQLException{ - return datasource.getConnection(); - } - - public String toString(){ - return this.datasource.toString(); - } + private DataSource datasource = null; + + public ConnectionHandler(String datasource) throws NamingException{ + setDataSource(datasource); + } + + public ConnectionHandler(DataSource datasource){ + setDataSource(datasource); + } + + public void setDataSource(DataSource ds){ + this.datasource = ds; + } + + public void setDataSource(String datasource) throws NamingException{ + Context initContext = new InitialContext(); + Context envContext = (Context)initContext.lookup("java:/comp/env"); + this.datasource = (DataSource)envContext.lookup(datasource); + } + + public DataSource getDataSource(){ + return this.datasource; + } + + public Connection getConnection() throws SQLException{ + return datasource.getConnection(); + } + + public String toString(){ + return this.datasource.toString(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/db/DBUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/db/DBUtils.java index e927e40a170..f05835d49b3 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/db/DBUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/db/DBUtils.java @@ -21,141 +21,141 @@ public class DBUtils { - public static boolean tableExists(DataSource dataSource, String tableName) throws SQLException { + public static boolean tableExists(DataSource dataSource, String tableName) throws SQLException { - Connection connection = null; - ResultSet rs = null; + Connection connection = null; + ResultSet rs = null; - try { - connection = dataSource.getConnection(); + try { + connection = dataSource.getConnection(); - DatabaseMetaData meta = connection.getMetaData(); + DatabaseMetaData meta = connection.getMetaData(); - rs = meta.getTables(null, null, tableName, null); + rs = meta.getTables(null, null, tableName, null); - if (rs.next()) { - return true; - } - } finally { - closeResultSet(rs); - closeConnection(connection); - } + if (rs.next()) { + return true; + } + } finally { + closeResultSet(rs); + closeConnection(connection); + } - return false; - } + return false; + } - public static ArrayList listAllTables(Connection connection) throws SQLException { + public static ArrayList listAllTables(Connection connection) throws SQLException { - ResultSet rs = null; + ResultSet rs = null; - try { - DatabaseMetaData meta = connection.getMetaData(); + try { + DatabaseMetaData meta = connection.getMetaData(); - rs = meta.getTables(null, null, null, null); + rs = meta.getTables(null, null, null, null); - ArrayList tableList = new ArrayList(); + ArrayList tableList = new ArrayList(); - while (rs.next()) { + while (rs.next()) { - tableList.add(rs.getString(3)); - } + tableList.add(rs.getString(3)); + } - return tableList; + return tableList; - } finally { - closeResultSet(rs); - closeConnection(connection); - } - } + } finally { + closeResultSet(rs); + closeConnection(connection); + } + } - public static DataSource getDataSource(String name) throws NamingException { - Context initContext = new InitialContext(); - Context envContext = (Context) initContext.lookup("java:/comp/env"); - return (DataSource) envContext.lookup(name); - } + public static DataSource getDataSource(String name) throws NamingException { + Context initContext = new InitialContext(); + Context envContext = (Context) initContext.lookup("java:/comp/env"); + return (DataSource) envContext.lookup(name); + } - public static boolean containsColumn(ResultSet rs, String columnName) { - try { - rs.findColumn(columnName); - return true; - } catch (SQLException e) { - return false; - } - } + public static boolean containsColumn(ResultSet rs, String columnName) { + try { + rs.findColumn(columnName); + return true; + } catch (SQLException e) { + return false; + } + } - public static List getTableColumns(Connection connection, String selectedTable) throws SQLException { + public static List getTableColumns(Connection connection, String selectedTable) throws SQLException { - ResultSet rs = null; + ResultSet rs = null; - try { - DatabaseMetaData meta = connection.getMetaData(); + try { + DatabaseMetaData meta = connection.getMetaData(); - rs = meta.getColumns(null, null, selectedTable, null); + rs = meta.getColumns(null, null, selectedTable, null); - ArrayList columnNames = new ArrayList(); + ArrayList columnNames = new ArrayList(); - while (rs.next()) { + while (rs.next()) { - columnNames.add(rs.getString(4)); - } + columnNames.add(rs.getString(4)); + } - return columnNames; + return columnNames; - } finally { - closeResultSet(rs); - closeConnection(connection); - } - } + } finally { + closeResultSet(rs); + closeConnection(connection); + } + } - public static int getTableColumnCount(DataSource dataSource, String selectedTable) throws SQLException { + public static int getTableColumnCount(DataSource dataSource, String selectedTable) throws SQLException { - Connection connection = null; - ResultSet rs = null; + Connection connection = null; + ResultSet rs = null; - try { + try { - connection = dataSource.getConnection(); + connection = dataSource.getConnection(); - DatabaseMetaData meta = connection.getMetaData(); + DatabaseMetaData meta = connection.getMetaData(); - rs = meta.getColumns(null, null, selectedTable, null); + rs = meta.getColumns(null, null, selectedTable, null); - rs.last(); + rs.last(); - return rs.getRow(); + return rs.getRow(); - } finally { - closeResultSet(rs); - closeConnection(connection); - } - } + } finally { + closeResultSet(rs); + closeConnection(connection); + } + } - public static void closeConnection(Connection connection) { - try { - if (connection != null && !connection.isClosed()) { - connection.close(); - } - } catch (SQLException e) { - } - } + public static void closeConnection(Connection connection) { + try { + if (connection != null && !connection.isClosed()) { + connection.close(); + } + } catch (SQLException e) { + } + } - public static void closeResultSet(ResultSet rs) { - try { - if (rs != null) { - rs.close(); - } - } catch (SQLException e) { - } - } + public static void closeResultSet(ResultSet rs) { + try { + if (rs != null) { + rs.close(); + } + } catch (SQLException e) { + } + } - public static void closePreparedStatement(PreparedStatement pstmt) { + public static void closePreparedStatement(PreparedStatement pstmt) { + + try { + if (pstmt != null) { + pstmt.close(); + } + } catch (SQLException e) { + } + } - try { - if (pstmt != null) { - pstmt.close(); - } - } catch (SQLException e) { - } - } - } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/enums/EnumUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/enums/EnumUtils.java index d7fd76ddf25..9b5c39529af 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/enums/EnumUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/enums/EnumUtils.java @@ -12,71 +12,71 @@ public class EnumUtils { - public static > boolean isEnum(Class e, String s) { - try { - Enum.valueOf(e, s); - return true; - } catch (IllegalArgumentException ex) { - return false; - } catch (NullPointerException ex) { - return false; - } - } + public static > boolean isEnum(Class e, String s) { + try { + Enum.valueOf(e, s); + return true; + } catch (IllegalArgumentException ex) { + return false; + } catch (NullPointerException ex) { + return false; + } + } - public static > Type toEnum(Class e, String s) { - try { - return Type.valueOf(e, s); - } catch (IllegalArgumentException ex) { - return null; - } catch (NullPointerException ex) { - return null; - } - } + public static > Type toEnum(Class e, String s) { + try { + return Type.valueOf(e, s); + } catch (IllegalArgumentException ex) { + return null; + } catch (NullPointerException ex) { + return null; + } + } - public static > ArrayList toEnum(Class e, String[] values) { + public static > ArrayList toEnum(Class e, String[] values) { - ArrayList enumValues = new ArrayList(); + ArrayList enumValues = new ArrayList(); - for (String value : values) { + for (String value : values) { - Type enumValue = toEnum(e, value); + Type enumValue = toEnum(e, value); - if (enumValue != null) { - enumValues.add(enumValue); - } - } + if (enumValue != null) { + enumValues.add(enumValue); + } + } - if (enumValues.isEmpty()) { - return null; - } else { - return enumValues; - } - } + if (enumValues.isEmpty()) { + return null; + } else { + return enumValues; + } + } - public static > Type toEnum(Type[] es, int ordinal) { + public static > Type toEnum(Type[] es, int ordinal) { - for (Type typeValue : es) { + for (Type typeValue : es) { - if (typeValue.ordinal() == ordinal) { + if (typeValue.ordinal() == ordinal) { - return typeValue; - } - } + return typeValue; + } + } - return null; - } + return null; + } - public static Enum getInstanceFromField(Field field) { + public static Enum getInstanceFromField(Field field) { - Object[] enumValues = field.getType().getEnumConstants(); + Object[] enumValues = field.getType().getEnumConstants(); - return (Enum) enumValues[0]; - } + return (Enum) enumValues[0]; + } - public static Enum[] getValuesFromField(Field field) { + public static Enum[] getValuesFromField(Field field) { - Object[] enumValues = field.getType().getEnumConstants(); + Object[] enumValues = field.getType().getEnumConstants(); - return (Enum[]) enumValues; - } + return (Enum[]) enumValues; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/enums/Month.java b/eagledns/src/main/java/se/unlogic/standardutils/enums/Month.java index 0cf66eb8812..8318281b316 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/enums/Month.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/enums/Month.java @@ -8,5 +8,5 @@ package se.unlogic.standardutils.enums; public enum Month { - JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER + JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/exec/ExecUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/exec/ExecUtils.java index 0553f94089c..2837d7302c9 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/exec/ExecUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/exec/ExecUtils.java @@ -18,202 +18,202 @@ */ public class ExecUtils { - /** - * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

- * - * All data written to standard out is piped to System.out with the given prefix

- * - * All data written to error out is piped to System.err with the given prefix

- * - * @param command the command to executed - * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed - * @return the exit value of the process. By convention, 0 indicates normal termination. - * @throws IOException - * @throws InterruptedException - */ - public static int execAndWait(String command, Long timeout) throws IOException, InterruptedException { - - Runtime rt = Runtime.getRuntime(); - Process proc = rt.exec(command); - - try{ - - //CHECKSTYLE.OFF: RegexpSinglelineJava - StreamHandler errorOutHandler = new StreamPrinter(System.err); - //CHECKSTYLE.ON: RegexpSinglelineJava - StreamHandler stdOutHandler = new StreamPrinter(); - - errorOutHandler.handleStream(proc.getErrorStream()); - stdOutHandler.handleStream(proc.getInputStream()); - - return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler, timeout); - - }finally{ - - if(proc != null){ - proc.destroy(); - } - } - } - - /** - * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

- * - * @param command the command to executed - * @param stdOutHandler the {@link StreamHandler} to handle all output the process writes on standard out - * @param errorOutHandler the {@link StreamHandler} to handle all output the process writes on error out - * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed - * @return the exit value of the process. By convention, 0 indicates normal termination. - * @throws IOException - * @throws InterruptedException - */ - public static int execAndWait(String command, StreamHandler stdOutHandler, StreamHandler errorOutHandler, Long timeout) throws IOException, InterruptedException { - - Runtime rt = Runtime.getRuntime(); - Process proc = rt.exec(command); - - try{ - errorOutHandler.handleStream(proc.getErrorStream()); - stdOutHandler.handleStream(proc.getInputStream()); - - return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler,timeout); - - }finally{ - - if(proc != null){ - proc.destroy(); - } - } - } - - /** - * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

- * - * All data written to standard out and error out is piped to the given {@link OutputStream}

- * - * @param command the command to executed - * @param outputStream the {@link OutputStream} to handle all output of the process - * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed - * @return the exit value of the process. By convention, 0 indicates normal termination. - * @throws IOException - * @throws InterruptedException - */ - public static int execAndWait(String command, OutputStream outputStream, Long timeout) throws IOException, InterruptedException { - - Runtime rt = Runtime.getRuntime(); - Process proc = rt.exec(command); - - try{ - - StreamHandler errorOutHandler = new StreamPrinter(outputStream); - StreamHandler stdOutHandler = new StreamPrinter(outputStream); - - errorOutHandler.handleStream(proc.getErrorStream()); - stdOutHandler.handleStream(proc.getInputStream()); - - return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler, timeout); - - }finally{ - - if(proc != null){ - proc.destroy(); - } - } - } - - /** - * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

- * - * All data written to standard out and error out is piped to the given {@link OutputStream}

- * - * @param builder the ProcessBuilder to get to start the Process through - * @param outputStream the {@link OutputStream} to handle all output of the process - * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed - * @return the exit value of the process. By convention, 0 indicates normal termination. - * @throws IOException - * @throws InterruptedException - */ - public static int execAndWait(ProcessBuilder builder, OutputStream outputStream, Long timeout) throws IOException, InterruptedException { - - Process proc = builder.start(); - - try{ - - StreamHandler errorOutHandler = new StreamPrinter(outputStream); - StreamHandler stdOutHandler = new StreamPrinter(outputStream); - - errorOutHandler.handleStream(proc.getErrorStream()); - stdOutHandler.handleStream(proc.getInputStream()); - - return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler, timeout); - - }finally{ - - if(proc != null){ - proc.destroy(); - } - } - } - - /** - * Waits for the given processes to terminate and all data written to standard out and error out to be handled.

- * - * All data written to standard out and error out is piped to the given {@link OutputStream}

- * - * @param command the command to executed - * @param outputStream the {@link OutputStream} to handle all output of the process - * @return the exit value of the process. By convention, 0 indicates normal termination. - * @throws IOException - * @throws InterruptedException - */ - - public static int waitForProcessAndStreams(Process proc, StreamHandler stdOutHandler, StreamHandler errorOutHandler, Long timeout) throws InterruptedException { - - int exitVal; - - if(timeout != null){ - - long elapsedTimeout = 0; - - while(true){ - - if(elapsedTimeout > timeout){ - proc.destroy(); - } - - Thread.sleep(100); - - try{ - exitVal = proc.exitValue(); - break; - - }catch(IllegalThreadStateException e){ - - elapsedTimeout += 100; - } - } - - exitVal = proc.exitValue(); - - stdOutHandler.terminate(); - errorOutHandler.terminate(); - - }else{ - - exitVal = proc.waitFor(); - } - - if(!stdOutHandler.isFinished()){ - stdOutHandler.awaitFinish(); - } - - if(errorOutHandler != null){ - - if(!errorOutHandler.isFinished()){ - errorOutHandler.awaitFinish(); - } - } - - return exitVal; - } + /** + * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

+ * + * All data written to standard out is piped to System.out with the given prefix

+ * + * All data written to error out is piped to System.err with the given prefix

+ * + * @param command the command to executed + * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed + * @return the exit value of the process. By convention, 0 indicates normal termination. + * @throws IOException + * @throws InterruptedException + */ + public static int execAndWait(String command, Long timeout) throws IOException, InterruptedException { + + Runtime rt = Runtime.getRuntime(); + Process proc = rt.exec(command); + + try{ + + //CHECKSTYLE.OFF: RegexpSinglelineJava + StreamHandler errorOutHandler = new StreamPrinter(System.err); + //CHECKSTYLE.ON: RegexpSinglelineJava + StreamHandler stdOutHandler = new StreamPrinter(); + + errorOutHandler.handleStream(proc.getErrorStream()); + stdOutHandler.handleStream(proc.getInputStream()); + + return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler, timeout); + + }finally{ + + if(proc != null){ + proc.destroy(); + } + } + } + + /** + * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

+ * + * @param command the command to executed + * @param stdOutHandler the {@link StreamHandler} to handle all output the process writes on standard out + * @param errorOutHandler the {@link StreamHandler} to handle all output the process writes on error out + * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed + * @return the exit value of the process. By convention, 0 indicates normal termination. + * @throws IOException + * @throws InterruptedException + */ + public static int execAndWait(String command, StreamHandler stdOutHandler, StreamHandler errorOutHandler, Long timeout) throws IOException, InterruptedException { + + Runtime rt = Runtime.getRuntime(); + Process proc = rt.exec(command); + + try{ + errorOutHandler.handleStream(proc.getErrorStream()); + stdOutHandler.handleStream(proc.getInputStream()); + + return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler,timeout); + + }finally{ + + if(proc != null){ + proc.destroy(); + } + } + } + + /** + * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

+ * + * All data written to standard out and error out is piped to the given {@link OutputStream}

+ * + * @param command the command to executed + * @param outputStream the {@link OutputStream} to handle all output of the process + * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed + * @return the exit value of the process. By convention, 0 indicates normal termination. + * @throws IOException + * @throws InterruptedException + */ + public static int execAndWait(String command, OutputStream outputStream, Long timeout) throws IOException, InterruptedException { + + Runtime rt = Runtime.getRuntime(); + Process proc = rt.exec(command); + + try{ + + StreamHandler errorOutHandler = new StreamPrinter(outputStream); + StreamHandler stdOutHandler = new StreamPrinter(outputStream); + + errorOutHandler.handleStream(proc.getErrorStream()); + stdOutHandler.handleStream(proc.getInputStream()); + + return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler, timeout); + + }finally{ + + if(proc != null){ + proc.destroy(); + } + } + } + + /** + * Executes the given command and waits for the resulting processes to terminate and all data written to standard out and error out to be handled.

+ * + * All data written to standard out and error out is piped to the given {@link OutputStream}

+ * + * @param builder the ProcessBuilder to get to start the Process through + * @param outputStream the {@link OutputStream} to handle all output of the process + * @param timeout an optional timeout that controls how long the process i allowed to run before it is killed + * @return the exit value of the process. By convention, 0 indicates normal termination. + * @throws IOException + * @throws InterruptedException + */ + public static int execAndWait(ProcessBuilder builder, OutputStream outputStream, Long timeout) throws IOException, InterruptedException { + + Process proc = builder.start(); + + try{ + + StreamHandler errorOutHandler = new StreamPrinter(outputStream); + StreamHandler stdOutHandler = new StreamPrinter(outputStream); + + errorOutHandler.handleStream(proc.getErrorStream()); + stdOutHandler.handleStream(proc.getInputStream()); + + return waitForProcessAndStreams(proc,stdOutHandler,errorOutHandler, timeout); + + }finally{ + + if(proc != null){ + proc.destroy(); + } + } + } + + /** + * Waits for the given processes to terminate and all data written to standard out and error out to be handled.

+ * + * All data written to standard out and error out is piped to the given {@link OutputStream}

+ * + * @param command the command to executed + * @param outputStream the {@link OutputStream} to handle all output of the process + * @return the exit value of the process. By convention, 0 indicates normal termination. + * @throws IOException + * @throws InterruptedException + */ + + public static int waitForProcessAndStreams(Process proc, StreamHandler stdOutHandler, StreamHandler errorOutHandler, Long timeout) throws InterruptedException { + + int exitVal; + + if(timeout != null){ + + long elapsedTimeout = 0; + + while(true){ + + if(elapsedTimeout > timeout){ + proc.destroy(); + } + + Thread.sleep(100); + + try{ + exitVal = proc.exitValue(); + break; + + }catch(IllegalThreadStateException e){ + + elapsedTimeout += 100; + } + } + + exitVal = proc.exitValue(); + + stdOutHandler.terminate(); + errorOutHandler.terminate(); + + }else{ + + exitVal = proc.waitFor(); + } + + if(!stdOutHandler.isFinished()){ + stdOutHandler.awaitFinish(); + } + + if(errorOutHandler != null){ + + if(!errorOutHandler.isFinished()){ + errorOutHandler.awaitFinish(); + } + } + + return exitVal; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamHandler.java b/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamHandler.java index dd06954b147..2d69349d376 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamHandler.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamHandler.java @@ -17,14 +17,14 @@ */ public interface StreamHandler{ - void handleStream(InputStream inputStream); - - boolean isFinished(); - - void awaitFinish(); + void handleStream(InputStream inputStream); - boolean isTerminated(); + boolean isFinished(); - void terminate(); + void awaitFinish(); + + boolean isTerminated(); + + void terminate(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamPrinter.java b/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamPrinter.java index eb883fef0ac..ff319054112 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamPrinter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/exec/StreamPrinter.java @@ -28,114 +28,114 @@ */ public class StreamPrinter extends Thread implements StreamHandler { - private InputStream inputStream; - private String prefix; - private OutputStream outputStream; - - private boolean terminated = false; - - public StreamPrinter(String prefix, OutputStream os) { - super(); - this.outputStream = os; - this.prefix = prefix; - } - - public StreamPrinter(OutputStream os) { - super(); - this.outputStream = os; - } - - public StreamPrinter() {} - - public boolean isTerminated(){ - - return terminated; - } - - public void terminate(){ - - this.terminated = true; - } - - @Override - public void run() { - - InputStreamReader inputStreamReader = null; - BufferedReader bufferedReader = null; - - try { - PrintWriter pw = null; - - if (outputStream != null) { - pw = new PrintWriter(outputStream); - }else{ - //CHECKSTYLE.OFF: RegexpSinglelineJava - pw = new PrintWriter(System.out); - //CHECKSTYLE.ON: RegexpSinglelineJava - } - - inputStreamReader = new InputStreamReader(inputStream); - bufferedReader = new BufferedReader(inputStreamReader); - - String line = null; - - if(prefix != null){ - - while (!terminated && (line = bufferedReader.readLine()) != null) { - - pw.println(prefix + line); - } - - }else{ - - while (!terminated && (line = bufferedReader.readLine()) != null) { - - pw.println(line); - } - } - - if (pw != null) { - pw.flush(); - } - - } catch (IOException e) { - - throw new RuntimeException(e); - - }finally{ - ReadWriteUtils.closeReader(bufferedReader); - ReadWriteUtils.closeReader(inputStreamReader); - - this.terminated = true; - } - } - - public void handleStream(InputStream is) { - this.inputStream = is; - this.start(); - } - - public String getPrefix() { - return prefix; - } - - public OutputStream getOutputStream() { - return outputStream; - } - - public boolean isFinished() { - - return !this.isAlive(); - } - - public void awaitFinish() { - - try { - this.join(); - - } catch (InterruptedException e) { - - throw new RuntimeException(e); - } - } + private InputStream inputStream; + private String prefix; + private OutputStream outputStream; + + private boolean terminated = false; + + public StreamPrinter(String prefix, OutputStream os) { + super(); + this.outputStream = os; + this.prefix = prefix; + } + + public StreamPrinter(OutputStream os) { + super(); + this.outputStream = os; + } + + public StreamPrinter() {} + + public boolean isTerminated(){ + + return terminated; + } + + public void terminate(){ + + this.terminated = true; + } + + @Override + public void run() { + + InputStreamReader inputStreamReader = null; + BufferedReader bufferedReader = null; + + try { + PrintWriter pw = null; + + if (outputStream != null) { + pw = new PrintWriter(outputStream); + }else{ + //CHECKSTYLE.OFF: RegexpSinglelineJava + pw = new PrintWriter(System.out); + //CHECKSTYLE.ON: RegexpSinglelineJava + } + + inputStreamReader = new InputStreamReader(inputStream); + bufferedReader = new BufferedReader(inputStreamReader); + + String line = null; + + if(prefix != null){ + + while (!terminated && (line = bufferedReader.readLine()) != null) { + + pw.println(prefix + line); + } + + }else{ + + while (!terminated && (line = bufferedReader.readLine()) != null) { + + pw.println(line); + } + } + + if (pw != null) { + pw.flush(); + } + + } catch (IOException e) { + + throw new RuntimeException(e); + + }finally{ + ReadWriteUtils.closeReader(bufferedReader); + ReadWriteUtils.closeReader(inputStreamReader); + + this.terminated = true; + } + } + + public void handleStream(InputStream is) { + this.inputStream = is; + this.start(); + } + + public String getPrefix() { + return prefix; + } + + public OutputStream getOutputStream() { + return outputStream; + } + + public boolean isFinished() { + + return !this.isAlive(); + } + + public void awaitFinish() { + + try { + this.join(); + + } catch (InterruptedException e) { + + throw new RuntimeException(e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/Drive.java b/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/Drive.java index 287017a0fc9..c53969ffd0e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/Drive.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/Drive.java @@ -16,65 +16,65 @@ @XMLElement public class Drive implements Elementable{ - @XMLElement - private Integer temp; - - @XMLElement - private String type; - - @XMLElement - private String device; - - @XMLElement - private DriveState driveState; - - public Drive(Integer temp, String type, String device) - { - this.temp = temp; - this.device = device; - this.type = type; - } - - public Drive(){} - - public Integer getTemp() { - return temp; - } - public void setTemp(Integer temp) { - this.temp = temp; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getDevice() { - return device; - } - public void setDevice(String device) { - this.device = device; } - - @Override - public String toString() { - - return device + " " + temp + "-" + "(" + type + ")"; - } - - public Element toXML(Document doc) { - - return XMLGenerator.toXML(this, doc); - } - - - public DriveState getDriveState() { - - return driveState; - } - - - public void setDriveState(DriveState driveState) { - - this.driveState = driveState; - } + @XMLElement + private Integer temp; + + @XMLElement + private String type; + + @XMLElement + private String device; + + @XMLElement + private DriveState driveState; + + public Drive(Integer temp, String type, String device) + { + this.temp = temp; + this.device = device; + this.type = type; + } + + public Drive(){} + + public Integer getTemp() { + return temp; + } + public void setTemp(Integer temp) { + this.temp = temp; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getDevice() { + return device; + } + public void setDevice(String device) { + this.device = device; } + + @Override + public String toString() { + + return device + " " + temp + "-" + "(" + type + ")"; + } + + public Element toXML(Document doc) { + + return XMLGenerator.toXML(this, doc); + } + + + public DriveState getDriveState() { + + return driveState; + } + + + public void setDriveState(DriveState driveState) { + + this.driveState = driveState; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/DriveState.java b/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/DriveState.java index f17f0a1268b..60520b14b79 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/DriveState.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/DriveState.java @@ -10,8 +10,8 @@ public enum DriveState { - OK, - SLEEPING, - ERROR, - UNKNOWN + OK, + SLEEPING, + ERROR, + UNKNOWN } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/HDDTempUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/HDDTempUtils.java index b1d4b0c90da..a2bc357948c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/HDDTempUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/hddtemp/HDDTempUtils.java @@ -19,78 +19,78 @@ public class HDDTempUtils { - private static final String delims = "[|]+"; - - public static ArrayList getHddTemp(String host, int port, int timeout) throws IOException { - - Socket socket = null; - - try { - socket = SocketUtils.getSocket(host, port, timeout); - - BufferedReader bfrRd = new BufferedReader(new InputStreamReader(socket.getInputStream())); - - int waitCount = 0; - - while(!bfrRd.ready()){ - - if(waitCount >= timeout){ - - throw new SocketTimeoutException("No HDD temp response received"); - } - - try { - waitCount += 200; - Thread.sleep(200); - } catch (InterruptedException e) {} - } - - String response = new String(bfrRd.readLine()); - - String[] tokens = response.split(delims); - - if((tokens.length - 1) % 4 != 0){ - - throw new IOException("Invalid data received: " + response); - } - - ArrayList drives = new ArrayList(); - - for (int i = 1; i < tokens.length; i = i + 4) { - - Drive drive = new Drive(); - - drive.setDevice(tokens[i]); - drive.setType(tokens[i+1]); - drive.setTemp(NumberUtils.toInt(tokens[i+2])); - - if(drive.getTemp() != null){ - - drive.setDriveState(DriveState.OK); - - }else if(tokens[i+2].equals("SLP")){ - - drive.setDriveState(DriveState.SLEEPING); - - }else if(tokens[i+2].equals("ERR")){ - - drive.setDriveState(DriveState.ERROR); - - }else{ - - drive.setDriveState(DriveState.UNKNOWN); - } - - drives.add(drive); - } - - return drives; - - } finally { - - if (socket != null) { - socket.close(); - } - } - } + private static final String delims = "[|]+"; + + public static ArrayList getHddTemp(String host, int port, int timeout) throws IOException { + + Socket socket = null; + + try { + socket = SocketUtils.getSocket(host, port, timeout); + + BufferedReader bfrRd = new BufferedReader(new InputStreamReader(socket.getInputStream())); + + int waitCount = 0; + + while(!bfrRd.ready()){ + + if(waitCount >= timeout){ + + throw new SocketTimeoutException("No HDD temp response received"); + } + + try { + waitCount += 200; + Thread.sleep(200); + } catch (InterruptedException e) {} + } + + String response = new String(bfrRd.readLine()); + + String[] tokens = response.split(delims); + + if((tokens.length - 1) % 4 != 0){ + + throw new IOException("Invalid data received: " + response); + } + + ArrayList drives = new ArrayList(); + + for (int i = 1; i < tokens.length; i = i + 4) { + + Drive drive = new Drive(); + + drive.setDevice(tokens[i]); + drive.setType(tokens[i+1]); + drive.setTemp(NumberUtils.toInt(tokens[i+2])); + + if(drive.getTemp() != null){ + + drive.setDriveState(DriveState.OK); + + }else if(tokens[i+2].equals("SLP")){ + + drive.setDriveState(DriveState.SLEEPING); + + }else if(tokens[i+2].equals("ERR")){ + + drive.setDriveState(DriveState.ERROR); + + }else{ + + drive.setDriveState(DriveState.UNKNOWN); + } + + drives.add(drive); + } + + return drives; + + } finally { + + if (socket != null) { + socket.close(); + } + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/i18n/Language.java b/eagledns/src/main/java/se/unlogic/standardutils/i18n/Language.java index 316632c3720..8a5ab0f1622 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/i18n/Language.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/i18n/Language.java @@ -12,242 +12,242 @@ import org.w3c.dom.Node; public enum Language { - Abkhaz("ab"), - Afar("aa"), - Afrikaans("af"), - Akan("ak"), - Albanian("sq"), - Amharic("am"), - Arabic("ar"), - Aragonese("an"), - Armenian("hy"), - Assamese("as"), - Avaric("av"), - Avestan("ae"), - Aymara("ay"), - Azerbaijani("az"), - Bambara("bm"), - Bashkir("ba"), - Basque("eu"), - Belarusian("be"), - Bengali("bn"), - Bihari("bh"), - Bislama("bi"), - Bosnian("bs"), - Breton("br"), - Bulgarian("bg"), - Burmese("my"), - Catalan_Valencian("ca"), - Chamorro("ch"), - Chechen("ce"), - Chichewa_Chewa_Nyanja("ny"), - Chinese("zh"), - Chuvash("cv"), - Cornish("kw"), - Corsican("co"), - Cree("cr"), - Croatian("hr"), - Czech("cs"), - Danish("da"), - Divehi_Dhivehi_Maldivian("dv"), - Dutch("nl"), - Dzongkha("dz"), - English("en"), - Esperanto("eo"), - Estonian("et"), - Ewe("ee"), - Faroese("fo"), - Fijian("fj"), - Finnish("fi", "Suomi"), - French("fr"), - Fula_Fulah_Pulaar_Pular("ff"), - Galician("gl"), - Georgian("ka"), - German("de"), - Greek_Modern("el"), - Guarani("gn"), - Gujarati("gu"), - Haitian_Haitian_Creole("ht"), - Hausa("ha"), - Hebrew_modern("he"), - Herero("hz"), - Hindi("hi"), - Hiri_Motu("ho"), - Hungarian("hu"), - Interlingua("ia"), - Indonesian("id"), - Interlingue("ie"), - Irish("ga"), - Igbo("ig"), - Inupiaq("ik"), - Ido("io"), - Icelandic("is"), - Italian("it"), - Inuktitut("iu"), - Japanese("ja"), - Javanese("jv"), - Kalaallisut_Greenlandic("kl"), - Kannada("kn"), - Kanuri("kr"), - Kashmiri("ks"), - Kazakh("kk"), - Khmer("km"), - Kikuyu_Gikuyu("ki"), - Kinyarwanda("rw"), - Kirghiz_Kyrgyz("ky"), - Komi("kv"), - Kongo("kg"), - Korean("ko"), - Kurdish("ku"), - Kwanyama_Kuanyama("kj"), - Latin("la"), - Luxembourgish_Letzeburgesch("lb"), - Luganda("lg"), - Limburgish_Limburgan_Limburger("li"), - Lingala("ln"), - Lao("lo"), - Lithuanian("lt"), - Luba_Katanga("lu"), - Latvian("lv"), - Manx("gv"), - Macedonian("mk"), - Malagasy("mg"), - Malay("ms"), - Malayalam("ml"), - Maltese("mt"), - Maori("mi"), - Marathi("mr"), - Marshallese("mh"), - Mongolian("mn"), - Nauru("na"), - Navajo_Navaho("nv"), - Norwegian_Bokmål("nb"), - North_Ndebele("nd"), - Nepali("ne"), - Ndonga("ng"), - Norwegian_Nynorsk("nn"), - Norwegian("no"), - Nuosu("ii"), - South_Ndebele("nr"), - Occitan_after_1500("oc"), - Ojibwa("oj"), - Old_Church_Slavonic_Church_Slavic_Church_Slavonic_Old_Bulgarian_Old_Slavonic("cu"), - Oromo("om"), - Oriya("or"), - Ossetian_Ossetic("os"), - Panjabi_Punjabi("pa"), - Pali("pi"), - Persian("fa"), - Polish("pl"), - Pashto_Pushto("ps"), - Portuguese("pt"), - Quechua("qu"), - Romansh("rm"), - Kirundi("rn"), - Romanian_Moldavian_Moldovan("ro"), - Russian("ru"), - Sanskrit("sa"), - Sardinian("sc"), - Sindhi("sd"), - Northern_Sami("se"), - Samoan("sm"), - Sango("sg"), - Serbian("sr"), - Scottish_Gaelic_Gaelic("gd"), - Shona("sn"), - Sinhala_Sinhalese("si"), - Slovak("sk"), - Slovene("sl"), - Somali("so"), - Southern_Sotho("st"), - Spanish_Castilian("es"), - Sundanese("su"), - Swahili("sw"), - Swati("ss"), - Swedish("sv", "Svenska"), - Tamil("ta"), - Telugu("te"), - Tajik("tg"), - Thai("th"), - Tigrinya("ti"), - Tibetan_Standard_Tibetan_Central("bo"), - Turkmen("tk"), - Tagalog("tl"), - Tswana("tn"), - Tonga_Tonga_Islands("to"), - Turkish("tr"), - Tsonga("ts"), - Tatar("tt"), - Twi("tw"), - Tahitian("ty"), - Uighur_Uyghur("ug"), - Ukrainian("uk"), - Urdu("ur"), - Uzbek("uz"), - Venda("ve"), - Vietnamese("vi"), - Volapk("vo"), - Walloon("wa"), - Welsh("cy"), - Wolof("wo"), - Western_Frisian("fy"), - Xhosa("xh"), - Yiddish("yi"), - Yoruba("yo"), - Zhuang_Chuang("za"), - Zulu("zu"); - - private final String code; - private final String localName; - - Language(String code) { - - this(code, null); - } - - Language(String code, String localName) { - - this.code = code; - this.localName = localName; - } - - public String getLanguageCode() { - - return this.code; - } - - /** - * Returns the Language from its corresponding language code - * - * @param code - * @return Language - */ - public static Language getLanguage(String code) { - - for (Language language : Language.values()) { - if (language.code.equals(code)) { - return language; - } - } - return null; - } - - public Node toXML(Document doc) { - - Element languageElement = doc.createElement("language"); - Element nameElement = doc.createElement("name"); - nameElement.setTextContent(this.name()); - - Element codeElement = doc.createElement("code"); - codeElement.setTextContent(this.code); - - Element localNameElement = doc.createElement("localName"); - localNameElement.setTextContent(this.localName == null ? this.name() : this.localName); - - languageElement.appendChild(nameElement); - languageElement.appendChild(codeElement); - languageElement.appendChild(localNameElement); - - return languageElement; - } + Abkhaz("ab"), + Afar("aa"), + Afrikaans("af"), + Akan("ak"), + Albanian("sq"), + Amharic("am"), + Arabic("ar"), + Aragonese("an"), + Armenian("hy"), + Assamese("as"), + Avaric("av"), + Avestan("ae"), + Aymara("ay"), + Azerbaijani("az"), + Bambara("bm"), + Bashkir("ba"), + Basque("eu"), + Belarusian("be"), + Bengali("bn"), + Bihari("bh"), + Bislama("bi"), + Bosnian("bs"), + Breton("br"), + Bulgarian("bg"), + Burmese("my"), + Catalan_Valencian("ca"), + Chamorro("ch"), + Chechen("ce"), + Chichewa_Chewa_Nyanja("ny"), + Chinese("zh"), + Chuvash("cv"), + Cornish("kw"), + Corsican("co"), + Cree("cr"), + Croatian("hr"), + Czech("cs"), + Danish("da"), + Divehi_Dhivehi_Maldivian("dv"), + Dutch("nl"), + Dzongkha("dz"), + English("en"), + Esperanto("eo"), + Estonian("et"), + Ewe("ee"), + Faroese("fo"), + Fijian("fj"), + Finnish("fi", "Suomi"), + French("fr"), + Fula_Fulah_Pulaar_Pular("ff"), + Galician("gl"), + Georgian("ka"), + German("de"), + Greek_Modern("el"), + Guarani("gn"), + Gujarati("gu"), + Haitian_Haitian_Creole("ht"), + Hausa("ha"), + Hebrew_modern("he"), + Herero("hz"), + Hindi("hi"), + Hiri_Motu("ho"), + Hungarian("hu"), + Interlingua("ia"), + Indonesian("id"), + Interlingue("ie"), + Irish("ga"), + Igbo("ig"), + Inupiaq("ik"), + Ido("io"), + Icelandic("is"), + Italian("it"), + Inuktitut("iu"), + Japanese("ja"), + Javanese("jv"), + Kalaallisut_Greenlandic("kl"), + Kannada("kn"), + Kanuri("kr"), + Kashmiri("ks"), + Kazakh("kk"), + Khmer("km"), + Kikuyu_Gikuyu("ki"), + Kinyarwanda("rw"), + Kirghiz_Kyrgyz("ky"), + Komi("kv"), + Kongo("kg"), + Korean("ko"), + Kurdish("ku"), + Kwanyama_Kuanyama("kj"), + Latin("la"), + Luxembourgish_Letzeburgesch("lb"), + Luganda("lg"), + Limburgish_Limburgan_Limburger("li"), + Lingala("ln"), + Lao("lo"), + Lithuanian("lt"), + Luba_Katanga("lu"), + Latvian("lv"), + Manx("gv"), + Macedonian("mk"), + Malagasy("mg"), + Malay("ms"), + Malayalam("ml"), + Maltese("mt"), + Maori("mi"), + Marathi("mr"), + Marshallese("mh"), + Mongolian("mn"), + Nauru("na"), + Navajo_Navaho("nv"), + Norwegian_Bokmål("nb"), + North_Ndebele("nd"), + Nepali("ne"), + Ndonga("ng"), + Norwegian_Nynorsk("nn"), + Norwegian("no"), + Nuosu("ii"), + South_Ndebele("nr"), + Occitan_after_1500("oc"), + Ojibwa("oj"), + Old_Church_Slavonic_Church_Slavic_Church_Slavonic_Old_Bulgarian_Old_Slavonic("cu"), + Oromo("om"), + Oriya("or"), + Ossetian_Ossetic("os"), + Panjabi_Punjabi("pa"), + Pali("pi"), + Persian("fa"), + Polish("pl"), + Pashto_Pushto("ps"), + Portuguese("pt"), + Quechua("qu"), + Romansh("rm"), + Kirundi("rn"), + Romanian_Moldavian_Moldovan("ro"), + Russian("ru"), + Sanskrit("sa"), + Sardinian("sc"), + Sindhi("sd"), + Northern_Sami("se"), + Samoan("sm"), + Sango("sg"), + Serbian("sr"), + Scottish_Gaelic_Gaelic("gd"), + Shona("sn"), + Sinhala_Sinhalese("si"), + Slovak("sk"), + Slovene("sl"), + Somali("so"), + Southern_Sotho("st"), + Spanish_Castilian("es"), + Sundanese("su"), + Swahili("sw"), + Swati("ss"), + Swedish("sv", "Svenska"), + Tamil("ta"), + Telugu("te"), + Tajik("tg"), + Thai("th"), + Tigrinya("ti"), + Tibetan_Standard_Tibetan_Central("bo"), + Turkmen("tk"), + Tagalog("tl"), + Tswana("tn"), + Tonga_Tonga_Islands("to"), + Turkish("tr"), + Tsonga("ts"), + Tatar("tt"), + Twi("tw"), + Tahitian("ty"), + Uighur_Uyghur("ug"), + Ukrainian("uk"), + Urdu("ur"), + Uzbek("uz"), + Venda("ve"), + Vietnamese("vi"), + Volapk("vo"), + Walloon("wa"), + Welsh("cy"), + Wolof("wo"), + Western_Frisian("fy"), + Xhosa("xh"), + Yiddish("yi"), + Yoruba("yo"), + Zhuang_Chuang("za"), + Zulu("zu"); + + private final String code; + private final String localName; + + Language(String code) { + + this(code, null); + } + + Language(String code, String localName) { + + this.code = code; + this.localName = localName; + } + + public String getLanguageCode() { + + return this.code; + } + + /** + * Returns the Language from its corresponding language code + * + * @param code + * @return Language + */ + public static Language getLanguage(String code) { + + for (Language language : Language.values()) { + if (language.code.equals(code)) { + return language; + } + } + return null; + } + + public Node toXML(Document doc) { + + Element languageElement = doc.createElement("language"); + Element nameElement = doc.createElement("name"); + nameElement.setTextContent(this.name()); + + Element codeElement = doc.createElement("code"); + codeElement.setTextContent(this.code); + + Element localNameElement = doc.createElement("localName"); + localNameElement.setTextContent(this.localName == null ? this.name() : this.localName); + + languageElement.appendChild(nameElement); + languageElement.appendChild(codeElement); + languageElement.appendChild(localNameElement); + + return languageElement; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/image/ImageUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/image/ImageUtils.java index ddff90c220b..1266d88663e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/image/ImageUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/image/ImageUtils.java @@ -20,211 +20,211 @@ public class ImageUtils { - public static final String JPG = "jpg"; - public static final String GIF = "gif"; - public static final String PNG = "png"; - public static final String BMP = "bmp"; - public static final String WBMP = "wbmp"; - - public static BufferedImage getImageByResource(String url) { - - try { - return ImageIO.read(ImageUtils.class.getResource(url)); - } catch (Exception e) { - return null; - } - } - - public static BufferedImage getImage(String url) { - try { - return ImageIO.read(new File(url)); - } catch (Exception e) { - return null; - } - } - - public static boolean isReadable(String url) { - - File file = new File(url); - - if (file.exists() && file.canRead()) { - return true; - } - return false; - - } - - public static BufferedImage getImage(InputStream inputStream) { - - try { - return ImageIO.read(inputStream); - } catch (Exception e) { - return null; - } - } - - public static BufferedImage scaleImage(BufferedImage image, double xFactor, double yFactor) { - - if (image != null) { - return scale(image, xFactor, yFactor); - } - return null; - - } - - public static BufferedImage scaleImage(BufferedImage image, int maxHeight, int maxWidth, int quality, int imageType) { - - if (image.getWidth() > maxWidth && image.getHeight() > maxHeight) { + public static final String JPG = "jpg"; + public static final String GIF = "gif"; + public static final String PNG = "png"; + public static final String BMP = "bmp"; + public static final String WBMP = "wbmp"; - double aspectRatio = (double) image.getWidth() / (double) image.getHeight(); + public static BufferedImage getImageByResource(String url) { - if (aspectRatio >= 1) { - - return scaleImageByWidth(image, maxWidth, quality, imageType); - - } else { - - return scaleImageByHeight(image, maxHeight, quality, imageType); - } + try { + return ImageIO.read(ImageUtils.class.getResource(url)); + } catch (Exception e) { + return null; + } + } - } else if (image.getWidth() > maxWidth) { - - return scaleImageByWidth(image, maxWidth, quality, imageType); - - } else if (image.getHeight() > maxHeight) { - - return scaleImageByHeight(image, maxHeight, quality, imageType); - - } else if (image.getType() != imageType){ - - return scale(image, image.getHeight(), image.getWidth(), quality, imageType); - - } else { - - return image; - } - } + public static BufferedImage getImage(String url) { + try { + return ImageIO.read(new File(url)); + } catch (Exception e) { + return null; + } + } - public static BufferedImage scaleImageByWidth(BufferedImage image, int maxWidth, int quality, int imageType) { + public static boolean isReadable(String url) { - double scale; + File file = new File(url); - if (image.getWidth() > image.getHeight()) { - scale = (double) maxWidth / (double) image.getWidth(); - } else { - scale = (double) maxWidth / (double) image.getHeight(); - } + if (file.exists() && file.canRead()) { + return true; + } + return false; - int scaledW = (int) (scale * image.getWidth()); - int scaledH = (int) (scale * image.getHeight()); + } - scaledW = checkSize(scaledW); - scaledH = checkSize(scaledH); - - return scale(image, scaledH, scaledW, quality, imageType); - } - - private static int checkSize(int value) { + public static BufferedImage getImage(InputStream inputStream) { - if (value < 1) { - return 1; - } else { - return value; - } - } + try { + return ImageIO.read(inputStream); + } catch (Exception e) { + return null; + } + } - public static BufferedImage scaleImageByHeight(BufferedImage image, int maxHeight, int quality, int imageType) { + public static BufferedImage scaleImage(BufferedImage image, double xFactor, double yFactor) { - double scale; + if (image != null) { + return scale(image, xFactor, yFactor); + } + return null; - if (image.getHeight() > image.getWidth()) { - scale = (double) maxHeight / (double) image.getHeight(); - } else { - scale = (double) maxHeight / (double) image.getWidth(); - } + } - int scaledW = (int) (scale * image.getWidth()); - int scaledH = (int) (scale * image.getHeight()); + public static BufferedImage scaleImage(BufferedImage image, int maxHeight, int maxWidth, int quality, int imageType) { - scaledW = checkSize(scaledW); - scaledH = checkSize(scaledH); + if (image.getWidth() > maxWidth && image.getHeight() > maxHeight) { - return scale(image, scaledH, scaledW, quality, imageType); - } + double aspectRatio = (double) image.getWidth() / (double) image.getHeight(); - public static void writeImage(BufferedImage image, String url, String format) throws IOException, NullPointerException { + if (aspectRatio >= 1) { - // write image to file - if (!url.endsWith("." + format)) { - url += "." + format; - } + return scaleImageByWidth(image, maxWidth, quality, imageType); - File outputfile = new File(url); - if (image != null) { - ImageIO.write(image, format, outputfile); - } + } else { - } + return scaleImageByHeight(image, maxHeight, quality, imageType); + } - private static BufferedImage scale(BufferedImage image, double xFactor, double yFactor) { + } else if (image.getWidth() > maxWidth) { - // scale image based on factor x and y - AffineTransform scaleTransform = new AffineTransform(); - scaleTransform.scale(xFactor, yFactor); + return scaleImageByWidth(image, maxWidth, quality, imageType); - BufferedImage result = new BufferedImage((int) (image.getWidth() * xFactor), (int) (image.getHeight() * yFactor), BufferedImage.TYPE_INT_RGB); + } else if (image.getHeight() > maxHeight) { - Graphics2D g2 = (Graphics2D) result.getGraphics(); + return scaleImageByHeight(image, maxHeight, quality, imageType); - g2.setColor(Color.WHITE); - g2.fillRect(0, 0, result.getWidth(), result.getHeight()); - - g2.drawImage(image, scaleTransform, null); + } else if (image.getType() != imageType){ - return result; - } + return scale(image, image.getHeight(), image.getWidth(), quality, imageType); - private static BufferedImage scale(BufferedImage image, int height, int width, int quality, int imageType) { + } else { - BufferedImage result = new BufferedImage(width, height, imageType); + return image; + } + } - Graphics2D g2 = (Graphics2D) result.getGraphics(); - - g2.setColor(Color.WHITE); - g2.fillRect(0, 0, width, height); - - Canvas canvas = new Canvas(); - Image tImage = image.getScaledInstance(width, height, quality); + public static BufferedImage scaleImageByWidth(BufferedImage image, int maxWidth, int quality, int imageType) { - g2.drawImage(tImage, 0, 0, canvas); + double scale; - return result; - } + if (image.getWidth() > image.getHeight()) { + scale = (double) maxWidth / (double) image.getWidth(); + } else { + scale = (double) maxWidth / (double) image.getHeight(); + } - /*public static void scaleAndWriteImage(String inImgURL, String outImgURL, String format, double xFactor, double yFactor ) throws IOException{ + int scaledW = (int) (scale * image.getWidth()); + int scaledH = (int) (scale * image.getHeight()); - // scale and write the scaled image to file - BufferedImage image = getImage(inImgURL); + scaledW = checkSize(scaledW); + scaledH = checkSize(scaledH); - // changed - final int MaxDim = 120; - int thumb_width = image.getWidth(); - int thumb_height = image.getHeight(); - int b = thumb_height > thumb_width ? thumb_height : image.getWidth(); - double per = (b > MaxDim) ? (MaxDim * 1.0) / b : 1.0; - thumb_height = (int)(thumb_height * per); - thumb_width = (int)(thumb_width * per); - //// + return scale(image, scaledH, scaledW, quality, imageType); + } - BufferedImage scImage = null; - if(image != null){ - //scImage = scale(image, xFactor, yFactor); - scImage = scale(image, thumb_height, thumb_width); - } - else - throw new IOException(); - writeImage(scImage, outImgURL, format); + private static int checkSize(int value) { + if (value < 1) { + return 1; + } else { + return value; + } + } - }*/ + public static BufferedImage scaleImageByHeight(BufferedImage image, int maxHeight, int quality, int imageType) { + + double scale; + + if (image.getHeight() > image.getWidth()) { + scale = (double) maxHeight / (double) image.getHeight(); + } else { + scale = (double) maxHeight / (double) image.getWidth(); + } + + int scaledW = (int) (scale * image.getWidth()); + int scaledH = (int) (scale * image.getHeight()); + + scaledW = checkSize(scaledW); + scaledH = checkSize(scaledH); + + return scale(image, scaledH, scaledW, quality, imageType); + } + + public static void writeImage(BufferedImage image, String url, String format) throws IOException, NullPointerException { + + // write image to file + if (!url.endsWith("." + format)) { + url += "." + format; + } + + File outputfile = new File(url); + if (image != null) { + ImageIO.write(image, format, outputfile); + } + + } + + private static BufferedImage scale(BufferedImage image, double xFactor, double yFactor) { + + // scale image based on factor x and y + AffineTransform scaleTransform = new AffineTransform(); + scaleTransform.scale(xFactor, yFactor); + + BufferedImage result = new BufferedImage((int) (image.getWidth() * xFactor), (int) (image.getHeight() * yFactor), BufferedImage.TYPE_INT_RGB); + + Graphics2D g2 = (Graphics2D) result.getGraphics(); + + g2.setColor(Color.WHITE); + g2.fillRect(0, 0, result.getWidth(), result.getHeight()); + + g2.drawImage(image, scaleTransform, null); + + return result; + } + + private static BufferedImage scale(BufferedImage image, int height, int width, int quality, int imageType) { + + BufferedImage result = new BufferedImage(width, height, imageType); + + Graphics2D g2 = (Graphics2D) result.getGraphics(); + + g2.setColor(Color.WHITE); + g2.fillRect(0, 0, width, height); + + Canvas canvas = new Canvas(); + Image tImage = image.getScaledInstance(width, height, quality); + + g2.drawImage(tImage, 0, 0, canvas); + + return result; + } + + /*public static void scaleAndWriteImage(String inImgURL, String outImgURL, String format, double xFactor, double yFactor ) throws IOException{ + + // scale and write the scaled image to file + BufferedImage image = getImage(inImgURL); + + // changed + final int MaxDim = 120; + int thumb_width = image.getWidth(); + int thumb_height = image.getHeight(); + int b = thumb_height > thumb_width ? thumb_height : image.getWidth(); + double per = (b > MaxDim) ? (MaxDim * 1.0) / b : 1.0; + thumb_height = (int)(thumb_height * per); + thumb_width = (int)(thumb_width * per); + //// + + BufferedImage scImage = null; + if(image != null){ + //scImage = scale(image, xFactor, yFactor); + scImage = scale(image, thumb_height, thumb_width); + } + else + throw new IOException(); + writeImage(scImage, outImgURL, format); + + + }*/ } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/io/BinarySizes.java b/eagledns/src/main/java/se/unlogic/standardutils/io/BinarySizes.java index ffd617ac007..275bfac755c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/io/BinarySizes.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/io/BinarySizes.java @@ -8,7 +8,7 @@ package se.unlogic.standardutils.io; public class BinarySizes { - public static final int KiloByte = 1024; - public static final int MegaByte = 1048576; - public static final int GigaByte = 1073741824; + public static final int KiloByte = 1024; + public static final int MegaByte = 1048576; + public static final int GigaByte = 1073741824; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/io/ChannelUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/io/ChannelUtils.java index ff4533a1c09..fffafb10237 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/io/ChannelUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/io/ChannelUtils.java @@ -6,10 +6,10 @@ public class ChannelUtils { - public void closeChannel(Channel channel){ - - try{ - channel.close(); - }catch(IOException e){} - } + public void closeChannel(Channel channel){ + + try{ + channel.close(); + }catch(IOException e){} + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/io/EndsWithFileFilter.java b/eagledns/src/main/java/se/unlogic/standardutils/io/EndsWithFileFilter.java index a4edf6d152b..f12c755fd94 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/io/EndsWithFileFilter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/io/EndsWithFileFilter.java @@ -13,39 +13,39 @@ public class EndsWithFileFilter extends javax.swing.filechooser.FileFilter implements FileFilter { - protected String suffix; - protected boolean allowFolders; + protected String suffix; + protected boolean allowFolders; - public EndsWithFileFilter(String suffix) { - super(); - this.suffix = suffix; - } + public EndsWithFileFilter(String suffix) { + super(); + this.suffix = suffix; + } - public EndsWithFileFilter(String suffix, boolean allowFolders) { + public EndsWithFileFilter(String suffix, boolean allowFolders) { - super(); - this.suffix = suffix; - this.allowFolders = allowFolders; - } + super(); + this.suffix = suffix; + this.allowFolders = allowFolders; + } - @Override - public boolean accept(File file) { + @Override + public boolean accept(File file) { - if(file.getName().endsWith(suffix)){ + if(file.getName().endsWith(suffix)){ - return true; + return true; - }else if(allowFolders && file.isDirectory()){ + }else if(allowFolders && file.isDirectory()){ - return true; - } + return true; + } - return false; - } + return false; + } - @Override - public String getDescription() { + @Override + public String getDescription() { - return suffix; - } + return suffix; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/io/FileUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/io/FileUtils.java index 669d850ef77..e3e14f8faf7 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/io/FileUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/io/FileUtils.java @@ -24,194 +24,194 @@ */ public class FileUtils { - public static String toAsciiFilename(String string) { + public static String toAsciiFilename(String string) { - return string.replaceAll("[^0-9a-zA-Z-.]", "_"); - } + return string.replaceAll("[^0-9a-zA-Z-.]", "_"); + } - public static String toValidHttpFilename(String string) { + public static String toValidHttpFilename(String string) { - return string.replaceAll("[^0-9a-öA-Ö-+. ()-+!@é&%$§=´]", "_"); - } - - public final static byte[] getRawBytes(File f) throws IOException { - FileInputStream fin = new FileInputStream(f); - byte[] buffer = new byte[(int) f.length()]; - fin.read(buffer); - fin.close(); - return buffer; - } + return string.replaceAll("[^0-9a-�A-�-+. ()-+!@�&%$�=�]", "_"); + } - public static String getFileExtension(File file) { - return getFileExtension(file.getName()); - } + public final static byte[] getRawBytes(File f) throws IOException { + FileInputStream fin = new FileInputStream(f); + byte[] buffer = new byte[(int) f.length()]; + fin.read(buffer); + fin.close(); + return buffer; + } - public static String getFileExtension(String filename) { + public static String getFileExtension(File file) { + return getFileExtension(file.getName()); + } - int dotIndex = filename.lastIndexOf("."); + public static String getFileExtension(String filename) { - if (dotIndex == -1 || (dotIndex + 1) == filename.length()) { - return null; - } else { - return filename.substring(dotIndex + 1); - } - } + int dotIndex = filename.lastIndexOf("."); - public static boolean fileExists(String path) { + if (dotIndex == -1 || (dotIndex + 1) == filename.length()) { + return null; + } else { + return filename.substring(dotIndex + 1); + } + } - File file = new File(path); + public static boolean fileExists(String path) { - return file.exists(); - } + File file = new File(path); - /** - * Removes all files in the given directory matching the given filter - * - * @param directory - * the directory to be cleared - * @param filter - * {@link FileFilter} used to filter files - * @param recursive - * controls weather files should be deleted from sub directories too - */ - public static int deleteFiles(String directory, FileFilter filter, boolean recursive) { - - return deleteFiles(new File(directory), filter, recursive); - } - - public static int deleteFiles(File dir, FileFilter filter, boolean recursive) { - - if (dir.exists() && dir.isDirectory()) { - - int deletedFiles = 0; - - File[] files = dir.listFiles(filter); - - for (File file : files) { - - if (file.isDirectory()) { - - if (recursive) { - - deletedFiles += deleteFiles(file, filter, recursive); - } - - } else { - - if(file.delete()){ - - deletedFiles++; - } - } - } - - return deletedFiles; - } - - return 0; - } - - public static int replace(File dir, String filename, File replacementFile, boolean recursive, boolean caseSensitive, Callback callback) { - - if (dir.exists() && dir.isDirectory()) { - - int replacedFiles = 0; - - File[] files = dir.listFiles(); - - for (File file : files) { - - if (file.isDirectory()) { - - if (recursive) { - - replacedFiles += replace(file, filename,replacementFile, recursive, caseSensitive, callback); - } - - } else { - - if(caseSensitive){ - - if(!file.getName().equals(filename)){ - - continue; - } - - }else if(!file.getName().equalsIgnoreCase(filename)){ - - continue; - } - - if(file.canWrite()){ - - try { - if(callback != null){ - callback.callback(file); - } - - replaceFile(file,replacementFile); - - replacedFiles++; - - } catch (IOException e) {} - } - } - } - - return replacedFiles; - } - - return 0; - } - - public static void replaceFile(File target, File replacement) throws IOException { - - FileInputStream inputStream = null; - FileOutputStream outputStream = null; - - try{ - inputStream = new FileInputStream(replacement); - outputStream = new FileOutputStream(target); - - inputStream.getChannel().transferTo(0, replacement.length(), outputStream.getChannel()); - - StreamUtils.transfer(inputStream, outputStream); - - }finally{ - StreamUtils.closeStream(inputStream); - StreamUtils.closeStream(outputStream); - } - } - - public static boolean deleteDirectory(String directoryPath) { - - return deleteDirectory(new File(directoryPath)); - } - - public static boolean deleteDirectory(File directory) { - - if (directory.exists()) { - - File[] files = directory.listFiles(); - - for (File file : files) { - - if (file.isDirectory()) { - deleteDirectory(file); - } else { - file.delete(); - } - } - } - return directory.delete(); - } - - public static void deleteFile(String path) { - - File file = new File(path); - - if(file.exists()){ - file.delete(); - } - } + return file.exists(); + } + + /** + * Removes all files in the given directory matching the given filter + * + * @param directory + * the directory to be cleared + * @param filter + * {@link FileFilter} used to filter files + * @param recursive + * controls weather files should be deleted from sub directories too + */ + public static int deleteFiles(String directory, FileFilter filter, boolean recursive) { + + return deleteFiles(new File(directory), filter, recursive); + } + + public static int deleteFiles(File dir, FileFilter filter, boolean recursive) { + + if (dir.exists() && dir.isDirectory()) { + + int deletedFiles = 0; + + File[] files = dir.listFiles(filter); + + for (File file : files) { + + if (file.isDirectory()) { + + if (recursive) { + + deletedFiles += deleteFiles(file, filter, recursive); + } + + } else { + + if(file.delete()){ + + deletedFiles++; + } + } + } + + return deletedFiles; + } + + return 0; + } + + public static int replace(File dir, String filename, File replacementFile, boolean recursive, boolean caseSensitive, Callback callback) { + + if (dir.exists() && dir.isDirectory()) { + + int replacedFiles = 0; + + File[] files = dir.listFiles(); + + for (File file : files) { + + if (file.isDirectory()) { + + if (recursive) { + + replacedFiles += replace(file, filename,replacementFile, recursive, caseSensitive, callback); + } + + } else { + + if(caseSensitive){ + + if(!file.getName().equals(filename)){ + + continue; + } + + }else if(!file.getName().equalsIgnoreCase(filename)){ + + continue; + } + + if(file.canWrite()){ + + try { + if(callback != null){ + callback.callback(file); + } + + replaceFile(file,replacementFile); + + replacedFiles++; + + } catch (IOException e) {} + } + } + } + + return replacedFiles; + } + + return 0; + } + + public static void replaceFile(File target, File replacement) throws IOException { + + FileInputStream inputStream = null; + FileOutputStream outputStream = null; + + try{ + inputStream = new FileInputStream(replacement); + outputStream = new FileOutputStream(target); + + inputStream.getChannel().transferTo(0, replacement.length(), outputStream.getChannel()); + + StreamUtils.transfer(inputStream, outputStream); + + }finally{ + StreamUtils.closeStream(inputStream); + StreamUtils.closeStream(outputStream); + } + } + + public static boolean deleteDirectory(String directoryPath) { + + return deleteDirectory(new File(directoryPath)); + } + + public static boolean deleteDirectory(File directory) { + + if (directory.exists()) { + + File[] files = directory.listFiles(); + + for (File file : files) { + + if (file.isDirectory()) { + deleteDirectory(file); + } else { + file.delete(); + } + } + } + return directory.delete(); + } + + public static void deleteFile(String path) { + + File file = new File(path); + + if(file.exists()){ + file.delete(); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/io/StartsEndsWithFileFilter.java b/eagledns/src/main/java/se/unlogic/standardutils/io/StartsEndsWithFileFilter.java index 2953d93838e..f97f467b160 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/io/StartsEndsWithFileFilter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/io/StartsEndsWithFileFilter.java @@ -13,23 +13,23 @@ public class StartsEndsWithFileFilter implements FileFilter { - private String prefix; - private String suffix; + private String prefix; + private String suffix; - public StartsEndsWithFileFilter(String prefix, String suffix) { + public StartsEndsWithFileFilter(String prefix, String suffix) { - super(); - this.prefix = prefix; - this.suffix = suffix; - } + super(); + this.prefix = prefix; + this.suffix = suffix; + } - public boolean accept(File file) { + public boolean accept(File file) { - if(file.getName().startsWith(prefix) && file.getName().endsWith(suffix)){ + if(file.getName().startsWith(prefix) && file.getName().endsWith(suffix)){ - return true; - } + return true; + } - return false; - } + return false; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonArray.java b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonArray.java index f363e92da41..88052b5ae60 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonArray.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonArray.java @@ -21,66 +21,66 @@ */ public class JsonArray implements JsonNode { - /** - * - */ - private static final long serialVersionUID = 1497880281195635145L; - private final List nodes = new ArrayList(); - - public String toJson() { - return this.toJson(new StringBuilder()); - } - - public String toJson(StringBuilder stringBuilder) { - stringBuilder.append("["); - Iterator iterator = nodes.iterator(); - JsonNode node; - while(iterator.hasNext()) { - node = iterator.next(); - node.toJson(stringBuilder); - if(iterator.hasNext()) { - stringBuilder.append(","); - } - } - stringBuilder.append("]"); - return stringBuilder.toString(); - } + /** + * + */ + private static final long serialVersionUID = 1497880281195635145L; + private final List nodes = new ArrayList(); - public void addNode(JsonNode node) { - this.nodes.add(node); - } - - public void addNode(String value) { - this.nodes.add(new JsonLeaf(value)); - } - - public void removeNode(JsonNode node) { - this.nodes.remove(node); - } + public String toJson() { + return this.toJson(new StringBuilder()); + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((nodes == null) ? 0 : nodes.hashCode()); - return result; - } + public String toJson(StringBuilder stringBuilder) { + stringBuilder.append("["); + Iterator iterator = nodes.iterator(); + JsonNode node; + while(iterator.hasNext()) { + node = iterator.next(); + node.toJson(stringBuilder); + if(iterator.hasNext()) { + stringBuilder.append(","); + } + } + stringBuilder.append("]"); + return stringBuilder.toString(); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - JsonArray other = (JsonArray) obj; - if (nodes == null) { - if (other.nodes != null) - return false; - } else if (!nodes.equals(other.nodes)) - return false; - return true; - } + public void addNode(JsonNode node) { + this.nodes.add(node); + } + + public void addNode(String value) { + this.nodes.add(new JsonLeaf(value)); + } + + public void removeNode(JsonNode node) { + this.nodes.remove(node); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((nodes == null) ? 0 : nodes.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JsonArray other = (JsonArray) obj; + if (nodes == null) { + if (other.nodes != null) + return false; + } else if (!nodes.equals(other.nodes)) + return false; + return true; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonLeaf.java b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonLeaf.java index 4cddec1200c..597308565ac 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonLeaf.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonLeaf.java @@ -18,36 +18,36 @@ */ public class JsonLeaf implements JsonNode { - /** - * - */ - private static final long serialVersionUID = 1198871458505471824L; - private String value; - - public JsonLeaf(String value) { - this.value = value; - } + /** + * + */ + private static final long serialVersionUID = 1198871458505471824L; + private String value; - public String toJson() { - return this.toJson(new StringBuilder()); - } - - public String toJson(StringBuilder stringBuilder) { - if(value == null) { - return stringBuilder.append("null").toString(); - } - if(NumberUtils.isNumber(this.value)) { - stringBuilder.append(value); - } else if(this.value.equals("false")) { - stringBuilder.append(false); - } else if(this.value.equals("true")) { - stringBuilder.append(true); - } else { - stringBuilder.append("\""); - stringBuilder.append(value); - stringBuilder.append("\""); - } - return stringBuilder.toString(); - } + public JsonLeaf(String value) { + this.value = value; + } + + public String toJson() { + return this.toJson(new StringBuilder()); + } + + public String toJson(StringBuilder stringBuilder) { + if(value == null) { + return stringBuilder.append("null").toString(); + } + if(NumberUtils.isNumber(this.value)) { + stringBuilder.append(value); + } else if(this.value.equals("false")) { + stringBuilder.append(false); + } else if(this.value.equals("true")) { + stringBuilder.append(true); + } else { + stringBuilder.append("\""); + stringBuilder.append(value); + stringBuilder.append("\""); + } + return stringBuilder.toString(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonNode.java b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonNode.java index cf2e18b43e0..eecdcbeb58c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonNode.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonNode.java @@ -19,8 +19,8 @@ */ public interface JsonNode extends Serializable { - String toJson(); - - String toJson(StringBuilder stringBuilder); - + String toJson(); + + String toJson(StringBuilder stringBuilder); + } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonObject.java b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonObject.java index 398c2a7d879..8607528847a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonObject.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonObject.java @@ -22,69 +22,69 @@ */ public class JsonObject implements JsonNode { - /** - * - */ - private static final long serialVersionUID = -4958874287623042122L; - private final Map fields = new HashMap(); - - public String toJson() { - return this.toJson(new StringBuilder()); - } - - public String toJson(StringBuilder stringBuilder) { - stringBuilder.append("{"); - Iterator> iterator = fields.entrySet().iterator(); - Entry field; - while(iterator.hasNext()) { - field = iterator.next(); - stringBuilder.append("\""); - stringBuilder.append(field.getKey()); - stringBuilder.append("\""); - stringBuilder.append(":"); - field.getValue().toJson(stringBuilder); - if(iterator.hasNext()) { - stringBuilder.append(","); - } - } - stringBuilder.append("}"); - return stringBuilder.toString(); - } - - public void putField(String key, JsonNode value) { - this.fields.put(key, value); - } - - public void putField(String key, String value) { - this.fields.put(key, new JsonLeaf(value)); - } - - public void removeField(String key) { - this.fields.remove(key); - } + /** + * + */ + private static final long serialVersionUID = -4958874287623042122L; + private final Map fields = new HashMap(); - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((fields == null) ? 0 : fields.hashCode()); - return result; - } + public String toJson() { + return this.toJson(new StringBuilder()); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - JsonObject other = (JsonObject) obj; - if (fields == null) { - if (other.fields != null) - return false; - } else if (!fields.equals(other.fields)) - return false; - return true; - } + public String toJson(StringBuilder stringBuilder) { + stringBuilder.append("{"); + Iterator> iterator = fields.entrySet().iterator(); + Entry field; + while(iterator.hasNext()) { + field = iterator.next(); + stringBuilder.append("\""); + stringBuilder.append(field.getKey()); + stringBuilder.append("\""); + stringBuilder.append(":"); + field.getValue().toJson(stringBuilder); + if(iterator.hasNext()) { + stringBuilder.append(","); + } + } + stringBuilder.append("}"); + return stringBuilder.toString(); + } + + public void putField(String key, JsonNode value) { + this.fields.put(key, value); + } + + public void putField(String key, String value) { + this.fields.put(key, new JsonLeaf(value)); + } + + public void removeField(String key) { + this.fields.remove(key); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fields == null) ? 0 : fields.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JsonObject other = (JsonObject) obj; + if (fields == null) { + if (other.fields != null) + return false; + } else if (!fields.equals(other.fields)) + return false; + return true; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonUtils.java index 0f934dae087..9b843d27229 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/json/JsonUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/json/JsonUtils.java @@ -12,23 +12,23 @@ import java.util.Collection; public class JsonUtils { - - private static final String CONTENT_TYPE = "application/json"; - public static JsonNode encode(Collection validationErrors) { - JsonArray jsonArray = new JsonArray(); - JsonObject jsonObject; - for(ValidationError error : validationErrors) { - jsonObject = new JsonObject(); - jsonObject.putField("field", new JsonLeaf(error.getFieldName())); - jsonObject.putField("errorType", new JsonLeaf(error.getValidationErrorType().toString())); - jsonObject.putField("messageKey", new JsonLeaf(error.getMessageKey())); - jsonArray.addNode(jsonObject); - } - return jsonArray; - } + private static final String CONTENT_TYPE = "application/json"; - public static String getContentType() { - return CONTENT_TYPE; - } + public static JsonNode encode(Collection validationErrors) { + JsonArray jsonArray = new JsonArray(); + JsonObject jsonObject; + for(ValidationError error : validationErrors) { + jsonObject = new JsonObject(); + jsonObject.putField("field", new JsonLeaf(error.getFieldName())); + jsonObject.putField("errorType", new JsonLeaf(error.getValidationErrorType().toString())); + jsonObject.putField("messageKey", new JsonLeaf(error.getMessageKey())); + jsonArray.addNode(jsonObject); + } + return jsonArray; + } + + public static String getContentType() { + return CONTENT_TYPE; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/logging/LogUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/logging/LogUtils.java index 287f0aee7f0..7e4ab88365c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/logging/LogUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/logging/LogUtils.java @@ -12,26 +12,26 @@ public class LogUtils { - /** - * A method for triggering the LogFactory.release method on the commons logging library (http://commons.apache.org/logging/) without having compile time - * dependency to the library itself. Trigger of the release method can be nessecary sometimes in order to avoid memory leaks, see - * http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak for more information. - */ - public static void releaseCommonsLogging() { + /** + * A method for triggering the LogFactory.release method on the commons logging library (http://commons.apache.org/logging/) without having compile time + * dependency to the library itself. Trigger of the release method can be nessecary sometimes in order to avoid memory leaks, see + * http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak for more information. + */ + public static void releaseCommonsLogging() { - try { - Class logFactoryClass = Class.forName("org.apache.commons.logging.LogFactory"); + try { + Class logFactoryClass = Class.forName("org.apache.commons.logging.LogFactory"); - Method releaseMethod = logFactoryClass.getMethod("release", ClassLoader.class); + Method releaseMethod = logFactoryClass.getMethod("release", ClassLoader.class); - releaseMethod.invoke(null, Thread.currentThread().getContextClassLoader()); + releaseMethod.invoke(null, Thread.currentThread().getContextClassLoader()); - } catch (ClassNotFoundException e) { - } catch (SecurityException e) { - } catch (NoSuchMethodException e) { - } catch (IllegalArgumentException e) { - } catch (IllegalAccessException e) { - } catch (InvocationTargetException e) { - } - } + } catch (ClassNotFoundException e) { + } catch (SecurityException e) { + } catch (NoSuchMethodException e) { + } catch (IllegalArgumentException e) { + } catch (IllegalAccessException e) { + } catch (InvocationTargetException e) { + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/mime/MimeUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/mime/MimeUtils.java index b51b3b5c245..aad0335c950 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/mime/MimeUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/mime/MimeUtils.java @@ -19,50 +19,50 @@ public class MimeUtils { - private static String UnknownMimeType = "application/x-unknown"; - private static Properties MimeTypes = new Properties();; + private static String UnknownMimeType = "application/x-unknown"; + private static Properties MimeTypes = new Properties();; - static{ - try { - MimeTypes.load(MimeUtils.class.getResourceAsStream("mimetypes.properties")); - } catch (IOException e) {} - } + static{ + try { + MimeTypes.load(MimeUtils.class.getResourceAsStream("mimetypes.properties")); + } catch (IOException e) {} + } - public static String getMimeType(File file){ - return getMimeType(file.getName()); - } + public static String getMimeType(File file){ + return getMimeType(file.getName()); + } - public static String getMimeType(String filename){ + public static String getMimeType(String filename){ - String fileExtension = FileUtils.getFileExtension(filename); + String fileExtension = FileUtils.getFileExtension(filename); - if(fileExtension == null){ - return UnknownMimeType; - }else{ - return MimeTypes.getProperty(fileExtension.toLowerCase(),UnknownMimeType); - } - } + if(fileExtension == null){ + return UnknownMimeType; + }else{ + return MimeTypes.getProperty(fileExtension.toLowerCase(),UnknownMimeType); + } + } - public static int getMimeTypeCount(){ - return MimeTypes.size(); - } + public static int getMimeTypeCount(){ + return MimeTypes.size(); + } - public static Set> getMimeTypes(){ - return MimeTypes.entrySet(); - } + public static Set> getMimeTypes(){ + return MimeTypes.entrySet(); + } - public static void loadMimeTypes(InputStream inputStream) throws IOException{ - MimeTypes.clear(); - MimeTypes.load(inputStream); - } + public static void loadMimeTypes(InputStream inputStream) throws IOException{ + MimeTypes.clear(); + MimeTypes.load(inputStream); + } - /* JDK 1.6 only! - public void loadMimeTypes(Reader reader) throws IOException { - MimeTypes.load(reader); - } - */ + /* JDK 1.6 only! + public void loadMimeTypes(Reader reader) throws IOException { + MimeTypes.load(reader); + } + */ - public void loadMimeTypesFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { - MimeTypes.loadFromXML(in); - } + public void loadMimeTypesFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException { + MimeTypes.loadFromXML(in); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/net/SocketUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/net/SocketUtils.java index ee42fa237ba..c08c9d8588c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/net/SocketUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/net/SocketUtils.java @@ -17,47 +17,47 @@ public class SocketUtils { - public static Socket getSocket(String host, int port, int timeout) throws IOException{ - SocketAddress sockaddr = new InetSocketAddress(host, port); - Socket socket = new Socket(); - socket.connect(sockaddr, timeout); + public static Socket getSocket(String host, int port, int timeout) throws IOException{ + SocketAddress sockaddr = new InetSocketAddress(host, port); + Socket socket = new Socket(); + socket.connect(sockaddr, timeout); - return socket; - } + return socket; + } - public static boolean isValidInetAddress(String address){ + public static boolean isValidInetAddress(String address){ - try { + try { - InetAddress.getByName(address); + InetAddress.getByName(address); - return true; - - } catch (UnknownHostException e) { + return true; - return false; - } - } + } catch (UnknownHostException e) { - public static boolean isPortAvailable(int port) { + return false; + } + } - try { - ServerSocket srv = new ServerSocket(port); - srv.close(); - srv = null; - return true; - } catch (IOException e) { - return false; - } - } + public static boolean isPortAvailable(int port) { - public static void closeSocket(Socket socket) { + try { + ServerSocket srv = new ServerSocket(port); + srv.close(); + srv = null; + return true; + } catch (IOException e) { + return false; + } + } - if(socket != null){ - - try { - socket.close(); - } catch (IOException e) {} - } - } + public static void closeSocket(Socket socket) { + + if(socket != null){ + + try { + socket.close(); + } catch (IOException e) {} + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/numbers/IntegerCounter.java b/eagledns/src/main/java/se/unlogic/standardutils/numbers/IntegerCounter.java index 639b6e8b059..8b6a3816533 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/numbers/IntegerCounter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/numbers/IntegerCounter.java @@ -9,37 +9,37 @@ public class IntegerCounter { - private Integer value; + private Integer value; - IntegerCounter(Integer value) { - super(); - this.value = value; - } + IntegerCounter(Integer value) { + super(); + this.value = value; + } - public IntegerCounter() { - super(); - this.value = 0; - } + public IntegerCounter() { + super(); + this.value = 0; + } - public Integer getValue() { - return value; - } + public Integer getValue() { + return value; + } - public synchronized void setValue(Integer value) { - this.value = value; - } + public synchronized void setValue(Integer value) { + this.value = value; + } - public synchronized Integer increment(){ + public synchronized Integer increment(){ - value++; + value++; - return value; - } + return value; + } - public synchronized Integer decrement(){ + public synchronized Integer decrement(){ - value--; + value--; - return value; - } + return value; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/numbers/LongCounter.java b/eagledns/src/main/java/se/unlogic/standardutils/numbers/LongCounter.java index 4a4e6244519..620ac261304 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/numbers/LongCounter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/numbers/LongCounter.java @@ -9,37 +9,37 @@ public class LongCounter { - private Long value; + private Long value; - LongCounter(Long value) { - super(); - this.value = value; - } + LongCounter(Long value) { + super(); + this.value = value; + } - public LongCounter() { - super(); - this.value = 0l; - } + public LongCounter() { + super(); + this.value = 0l; + } - public Long getValue() { - return value; - } + public Long getValue() { + return value; + } - public synchronized void setValue(Long value) { - this.value = value; - } + public synchronized void setValue(Long value) { + this.value = value; + } - public synchronized Long increment(){ + public synchronized Long increment(){ - value++; + value++; - return value; - } + return value; + } - public synchronized Long decrement(){ + public synchronized Long decrement(){ - value--; + value--; - return value; - } + return value; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/numbers/NumberUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/numbers/NumberUtils.java index 9f84487cc10..24effb6ec9e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/numbers/NumberUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/numbers/NumberUtils.java @@ -19,305 +19,305 @@ public class NumberUtils { - private static final Pattern NUMBER_PATTERN = Pattern.compile("\\D*"); + private static final Pattern NUMBER_PATTERN = Pattern.compile("\\D*"); - public static boolean isLong(Double value) { + public static boolean isLong(Double value) { - if (value != null) { + if (value != null) { - Long longValue = value.longValue(); - Double doubleValue = longValue.doubleValue(); + Long longValue = value.longValue(); + Double doubleValue = longValue.doubleValue(); - if (doubleValue.equals(value)) { - return true; - } - } - return false; - } + if (doubleValue.equals(value)) { + return true; + } + } + return false; + } - public static boolean isInt(String value) { + public static boolean isInt(String value) { - if (value != null) { + if (value != null) { - try { - Integer.parseInt(value); - return true; + try { + Integer.parseInt(value); + return true; - } catch (NumberFormatException e) {} - } - return false; - } + } catch (NumberFormatException e) {} + } + return false; + } - public static boolean isLong(String value) { + public static boolean isLong(String value) { - if (value != null) { + if (value != null) { - try { - Long.parseLong(value); - return true; + try { + Long.parseLong(value); + return true; - } catch (NumberFormatException e) {} - } - return false; - } + } catch (NumberFormatException e) {} + } + return false; + } - public static boolean isFloat(String value) { + public static boolean isFloat(String value) { - if (value != null) { + if (value != null) { - try { - Float.parseFloat(value); - return true; + try { + Float.parseFloat(value); + return true; - } catch (NumberFormatException e) {} - } - return false; - } + } catch (NumberFormatException e) {} + } + return false; + } - public static boolean isDouble(String value) { + public static boolean isDouble(String value) { - if (value != null) { - try { - Double.parseDouble(value); - return true; + if (value != null) { + try { + Double.parseDouble(value); + return true; - } catch (NumberFormatException e) {} - } - return false; - } + } catch (NumberFormatException e) {} + } + return false; + } - public static boolean isNumber(String value) { + public static boolean isNumber(String value) { - return isDouble(value) || isLong(value) ? true : false; - } + return isDouble(value) || isLong(value) ? true : false; + } - public static Integer toInt(String value) { + public static Integer toInt(String value) { - if (value != null) { - try { - return Integer.parseInt(value); + if (value != null) { + try { + return Integer.parseInt(value); - } catch (NumberFormatException e) {} - } + } catch (NumberFormatException e) {} + } - return null; - } + return null; + } - public static List toInt(Collection list, Field field) throws IllegalArgumentException, IllegalAccessException { + public static List toInt(Collection list, Field field) throws IllegalArgumentException, IllegalAccessException { - Type type = field.getType(); + Type type = field.getType(); - if (list != null && type.equals(Integer.class) || type.equals(int.class)) { + if (list != null && type.equals(Integer.class) || type.equals(int.class)) { - List validIntegers = new ArrayList(); + List validIntegers = new ArrayList(); - for (Object object : list) { + for (Object object : list) { - Integer value = (Integer) field.get(object); + Integer value = (Integer) field.get(object); - if (value != null) { - validIntegers.add(value); - } + if (value != null) { + validIntegers.add(value); + } - } + } - return validIntegers; - } + return validIntegers; + } - return null; + return null; - } + } - public static ArrayList toInt(Collection values) { + public static ArrayList toInt(Collection values) { - if (values == null) { + if (values == null) { - return null; + return null; - } else { + } else { - ArrayList validIntegers = new ArrayList(); + ArrayList validIntegers = new ArrayList(); - for (String value : values) { + for (String value : values) { - if (value != null) { + if (value != null) { - Integer intValue = NumberUtils.toInt(value); + Integer intValue = NumberUtils.toInt(value); - if (intValue != null) { - validIntegers.add(intValue); - } - } - } + if (intValue != null) { + validIntegers.add(intValue); + } + } + } - if (validIntegers.isEmpty()) { + if (validIntegers.isEmpty()) { - return null; + return null; - } else { + } else { - return validIntegers; - } - } - } + return validIntegers; + } + } + } - public static ArrayList toInt(String[] values) { + public static ArrayList toInt(String[] values) { - if (values == null) { + if (values == null) { - return null; + return null; - } else { + } else { - ArrayList validIntegers = new ArrayList(); + ArrayList validIntegers = new ArrayList(); - for (String value : values) { + for (String value : values) { - if (value != null) { + if (value != null) { - Integer intValue = NumberUtils.toInt(value); + Integer intValue = NumberUtils.toInt(value); - if (intValue != null) { - validIntegers.add(intValue); - } - } - } + if (intValue != null) { + validIntegers.add(intValue); + } + } + } - if (validIntegers.isEmpty()) { + if (validIntegers.isEmpty()) { - return null; + return null; - } else { + } else { - return validIntegers; - } - } - } + return validIntegers; + } + } + } - public static Long toLong(String value) { + public static Long toLong(String value) { - if (value != null) { - try { - return Long.parseLong(value); - } catch (NumberFormatException e) {} - } + if (value != null) { + try { + return Long.parseLong(value); + } catch (NumberFormatException e) {} + } - return null; - } + return null; + } - public static Float toFloat(String value) { + public static Float toFloat(String value) { - if (value != null) { - try { - return Float.parseFloat(value); - } catch (NumberFormatException e) {} - } + if (value != null) { + try { + return Float.parseFloat(value); + } catch (NumberFormatException e) {} + } - return null; - } + return null; + } - public static Double toDouble(String value) { + public static Double toDouble(String value) { - if (value != null) { - try { - return Double.parseDouble(value); - } catch (NumberFormatException e) {} - } + if (value != null) { + try { + return Double.parseDouble(value); + } catch (NumberFormatException e) {} + } - return null; - } + return null; + } - public static List toDouble(List values) { + public static List toDouble(List values) { - if (values == null) { - - return null; - - } else { - - ArrayList validDoubles = new ArrayList(); + if (values == null) { - for (String value : values) { - - if (value != null) { - - Double doubleValue = NumberUtils.toDouble(value); + return null; - if (doubleValue != null) { - validDoubles.add(doubleValue); - } - } - } + } else { - if (validDoubles.isEmpty()) { - return null; - } else { - return validDoubles; - } - } - } + ArrayList validDoubles = new ArrayList(); - public static List toLong(List values) { + for (String value : values) { - if (values == null) { - return null; - } else { - ArrayList validLongs = new ArrayList(); + if (value != null) { - for (String value : values) { - if (value != null) { - Long LongValue = NumberUtils.toLong(value); + Double doubleValue = NumberUtils.toDouble(value); - if (LongValue != null) { - validLongs.add(LongValue); - } - } - } + if (doubleValue != null) { + validDoubles.add(doubleValue); + } + } + } - if (validLongs.isEmpty()) { - return null; - } else { - return validLongs; - } - } - } + if (validDoubles.isEmpty()) { + return null; + } else { + return validDoubles; + } + } + } - public static Long getNumbers(String revstring) { + public static List toLong(List values) { - String result = NUMBER_PATTERN.matcher(revstring).replaceAll(""); + if (values == null) { + return null; + } else { + ArrayList validLongs = new ArrayList(); - return toLong(result); - } + for (String value : values) { + if (value != null) { + Long LongValue = NumberUtils.toLong(value); - public static String formatNumber(Number value, int minDecimals, int maxDecimals, boolean grouping, boolean dotDecimalSymbol) { + if (LongValue != null) { + validLongs.add(LongValue); + } + } + } - DecimalFormat formatter = new DecimalFormat(); + if (validLongs.isEmpty()) { + return null; + } else { + return validLongs; + } + } + } - formatter.setMinimumFractionDigits(minDecimals); + public static Long getNumbers(String revstring) { - formatter.setMaximumFractionDigits(maxDecimals); + String result = NUMBER_PATTERN.matcher(revstring).replaceAll(""); - if (dotDecimalSymbol) { + return toLong(result); + } - formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); + public static String formatNumber(Number value, int minDecimals, int maxDecimals, boolean grouping, boolean dotDecimalSymbol) { - } + DecimalFormat formatter = new DecimalFormat(); - formatter.setGroupingUsed(grouping); + formatter.setMinimumFractionDigits(minDecimals); - return formatter.format(value); + formatter.setMaximumFractionDigits(maxDecimals); - } + if (dotDecimalSymbol) { - public static Byte toByte(String value) { + formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); - if (value != null) { - try { - return Byte.parseByte(value); - } catch (NumberFormatException e) {} - } + } - return null; - } + formatter.setGroupingUsed(grouping); + + return formatter.format(value); + + } + + public static Byte toByte(String value) { + + if (value != null) { + try { + return Byte.parseByte(value); + } catch (NumberFormatException e) {} + } + + return null; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/operation/ProgressMeter.java b/eagledns/src/main/java/se/unlogic/standardutils/operation/ProgressMeter.java index 41e32caa6c1..db2f448a85d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/operation/ProgressMeter.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/operation/ProgressMeter.java @@ -11,143 +11,143 @@ public class ProgressMeter { - private long start; - private long finish; - private long currentPosition; - private long startTime; - private long endTime; - public ProgressMeter(){}; - - public ProgressMeter(long start, long finish){ - this.start = start; - this.finish = finish; - } - - public ProgressMeter(boolean setStartTime){ - if(setStartTime){ - this.setStartTime(); - } - } - - public ProgressMeter(int start, int finish, int currentPosition){ - this.start = start; - this.finish = finish; - this.currentPosition = currentPosition; - } - - public long getCurrentPosition() { - return currentPosition; - } - - public synchronized void setCurrentPosition(int currentPosition) { - this.currentPosition = currentPosition; - } - - public synchronized void incrementCurrentPosition(){ - this.currentPosition++; - } - - public synchronized void decrementCurrentPosition(){ - this.currentPosition--; - } - - public long getFinish() { - return finish; - } - - public void setFinish(long finish) { - this.finish = finish; - } - - public long getStart() { - return start; - } - - public void setStart(long start) { - this.start = start; - } - - public int getPercentComplete(){ - if(this.finish > this.start){ - return (int)(((float)(this.currentPosition - this.start)/(float)(this.finish - this.start))*100f); - }else if(this.finish < this.start){ - return (int)(((float)(this.start - this.currentPosition)/(float)(this.start - this.finish))*100f); - }else{ - return -1; - } - } - - public int getPercentRemaining(){ - if(this.finish > this.start){ - if(this.finish - this.currentPosition != 0){ - return (int)(((float)(this.finish - this.currentPosition)/(float)(this.finish - this.start))*100f); - }else{ - return 0; - } - }else if(this.finish < this.start){ - if(this.currentPosition - this.finish != 0){ - return (int)(((float)(this.currentPosition - this.finish)/(float)(this.start - this.finish))*100f); - }else{ - return 0; - } - }else{ - return -1; - } - } - - public long getIntervalSize(){ - if(this.finish > this.start){ - return this.finish - this.start; - }else if(this.finish < this.start){ - return this.start - this.finish; - }else{ - return 0; - } - } - - public long getStartTime() { - return startTime; - } - - public void setStartTime() { - this.startTime = System.currentTimeMillis(); - } - - public void setStartTime(long startTime) { - this.startTime = startTime; - } - - public long getEndTime() { - return endTime; - } - - public void setEndTime() { - this.endTime = System.currentTimeMillis(); - } - - public void setEndTime(long endTime) { - this.endTime = endTime; - } - - public long getTimeSpent(){ - if(this.startTime != 0){ - if(this.endTime == 0){ - return System.currentTimeMillis() - this.startTime; - }else{ - return this.endTime - this.startTime; - } - }else{ - return 0; - } - } - - public void incrementCurrentPosition(long value) { - - this.currentPosition += value; - } - - public String getTimeSpentString() { - - return TimeUtils.millisecondsToString(getTimeSpent()); - } + private long start; + private long finish; + private long currentPosition; + private long startTime; + private long endTime; + public ProgressMeter(){}; + + public ProgressMeter(long start, long finish){ + this.start = start; + this.finish = finish; + } + + public ProgressMeter(boolean setStartTime){ + if(setStartTime){ + this.setStartTime(); + } + } + + public ProgressMeter(int start, int finish, int currentPosition){ + this.start = start; + this.finish = finish; + this.currentPosition = currentPosition; + } + + public long getCurrentPosition() { + return currentPosition; + } + + public synchronized void setCurrentPosition(int currentPosition) { + this.currentPosition = currentPosition; + } + + public synchronized void incrementCurrentPosition(){ + this.currentPosition++; + } + + public synchronized void decrementCurrentPosition(){ + this.currentPosition--; + } + + public long getFinish() { + return finish; + } + + public void setFinish(long finish) { + this.finish = finish; + } + + public long getStart() { + return start; + } + + public void setStart(long start) { + this.start = start; + } + + public int getPercentComplete(){ + if(this.finish > this.start){ + return (int)(((float)(this.currentPosition - this.start)/(float)(this.finish - this.start))*100f); + }else if(this.finish < this.start){ + return (int)(((float)(this.start - this.currentPosition)/(float)(this.start - this.finish))*100f); + }else{ + return -1; + } + } + + public int getPercentRemaining(){ + if(this.finish > this.start){ + if(this.finish - this.currentPosition != 0){ + return (int)(((float)(this.finish - this.currentPosition)/(float)(this.finish - this.start))*100f); + }else{ + return 0; + } + }else if(this.finish < this.start){ + if(this.currentPosition - this.finish != 0){ + return (int)(((float)(this.currentPosition - this.finish)/(float)(this.start - this.finish))*100f); + }else{ + return 0; + } + }else{ + return -1; + } + } + + public long getIntervalSize(){ + if(this.finish > this.start){ + return this.finish - this.start; + }else if(this.finish < this.start){ + return this.start - this.finish; + }else{ + return 0; + } + } + + public long getStartTime() { + return startTime; + } + + public void setStartTime() { + this.startTime = System.currentTimeMillis(); + } + + public void setStartTime(long startTime) { + this.startTime = startTime; + } + + public long getEndTime() { + return endTime; + } + + public void setEndTime() { + this.endTime = System.currentTimeMillis(); + } + + public void setEndTime(long endTime) { + this.endTime = endTime; + } + + public long getTimeSpent(){ + if(this.startTime != 0){ + if(this.endTime == 0){ + return System.currentTimeMillis() - this.startTime; + }else{ + return this.endTime - this.startTime; + } + }else{ + return 0; + } + } + + public void incrementCurrentPosition(long value) { + + this.currentPosition += value; + } + + public String getTimeSpentString() { + + return TimeUtils.millisecondsToString(getTimeSpent()); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/BaseStringPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/BaseStringPopulator.java index 92ab82af728..5e8f52bea14 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/BaseStringPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/BaseStringPopulator.java @@ -11,42 +11,42 @@ public abstract class BaseStringPopulator implements BeanStringPopulator { - private final String populatorID; - private final StringFormatValidator formatValidator; + private final String populatorID; + private final StringFormatValidator formatValidator; - public BaseStringPopulator(String populatorID, StringFormatValidator formatValidator) { - super(); - this.populatorID = populatorID; - this.formatValidator = formatValidator; - } + public BaseStringPopulator(String populatorID, StringFormatValidator formatValidator) { + super(); + this.populatorID = populatorID; + this.formatValidator = formatValidator; + } - public BaseStringPopulator(String populatorID) { - super(); - this.populatorID = populatorID; - this.formatValidator = null; - } + public BaseStringPopulator(String populatorID) { + super(); + this.populatorID = populatorID; + this.formatValidator = null; + } - public BaseStringPopulator() { - super(); - this.populatorID = null; - this.formatValidator = null; - } + public BaseStringPopulator() { + super(); + this.populatorID = null; + this.formatValidator = null; + } - public String getPopulatorID() { - return populatorID; - } + public String getPopulatorID() { + return populatorID; + } - public final boolean validateFormat(String value) { + public final boolean validateFormat(String value) { - if(formatValidator == null){ + if(formatValidator == null){ - return this.validateDefaultFormat(value); + return this.validateDefaultFormat(value); - }else{ + }else{ - return this.formatValidator.validateFormat(value); - } - } + return this.formatValidator.validateFormat(value); + } + } - protected abstract boolean validateDefaultFormat(String value); + protected abstract boolean validateDefaultFormat(String value); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulator.java index f6fccac0387..716c647d1b7 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulator.java @@ -20,9 +20,9 @@ */ public interface BeanStringPopulator extends StringFormatValidator{ - T getValue(String value); + T getValue(String value); - Class getType(); + Class getType(); - String getPopulatorID(); + String getPopulatorID(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulatorRegistery.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulatorRegistery.java index cad09969a6d..324e12f1a0d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulatorRegistery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/BeanStringPopulatorRegistery.java @@ -7,34 +7,34 @@ public class BeanStringPopulatorRegistery { - private final static HashMap, BeanStringPopulator> TYPE_POPULATORS = new HashMap, BeanStringPopulator>(); - - static{ - addTypePopulator(new UUIDPopulator()); - addTypePopulator(new BooleanPopulator()); - addTypePopulator(new DoublePopulator()); - addTypePopulator(new FloatPopulator()); - addTypePopulator(new IntegerPopulator()); - addTypePopulator(new LongPopulator()); - addTypePopulator(new PrimitiveBooleanPopulator()); - addTypePopulator(new PrimitiveIntegerPopulator()); - addTypePopulator(new PrimitiveLongPopulator()); - addTypePopulator(new StringPopulator()); - } - - private static void addTypePopulator(BeanStringPopulator typePopulator){ - - TYPE_POPULATORS.put(typePopulator.getType(), typePopulator); - } - - @SuppressWarnings("unchecked") - public static BeanStringPopulator getBeanStringPopulator(Class clazz){ - - return (BeanStringPopulator) TYPE_POPULATORS.get(clazz); - } - - public static Collection> getBeanStringPopulators(){ - - return Collections.unmodifiableCollection(TYPE_POPULATORS.values()); - } + private final static HashMap, BeanStringPopulator> TYPE_POPULATORS = new HashMap, BeanStringPopulator>(); + + static{ + addTypePopulator(new UUIDPopulator()); + addTypePopulator(new BooleanPopulator()); + addTypePopulator(new DoublePopulator()); + addTypePopulator(new FloatPopulator()); + addTypePopulator(new IntegerPopulator()); + addTypePopulator(new LongPopulator()); + addTypePopulator(new PrimitiveBooleanPopulator()); + addTypePopulator(new PrimitiveIntegerPopulator()); + addTypePopulator(new PrimitiveLongPopulator()); + addTypePopulator(new StringPopulator()); + } + + private static void addTypePopulator(BeanStringPopulator typePopulator){ + + TYPE_POPULATORS.put(typePopulator.getType(), typePopulator); + } + + @SuppressWarnings("unchecked") + public static BeanStringPopulator getBeanStringPopulator(Class clazz){ + + return (BeanStringPopulator) TYPE_POPULATORS.get(clazz); + } + + public static Collection> getBeanStringPopulators(){ + + return Collections.unmodifiableCollection(TYPE_POPULATORS.values()); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/BlobPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/BlobPopulator.java index f5b0ccfd18c..1c1de884b10 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/BlobPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/BlobPopulator.java @@ -15,13 +15,13 @@ public class BlobPopulator implements BeanResultSetPopulator { - public static final BlobPopulator POPULATOR = new BlobPopulator(); + public static final BlobPopulator POPULATOR = new BlobPopulator(); - public static BlobPopulator getPopulator() { - return POPULATOR; - } + public static BlobPopulator getPopulator() { + return POPULATOR; + } - public Blob populate(ResultSet rs) throws SQLException { - return rs.getBlob(1); - } + public Blob populate(ResultSet rs) throws SQLException { + return rs.getBlob(1); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/BooleanPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/BooleanPopulator.java index 33b0ea4847b..59f409f9528 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/BooleanPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/BooleanPopulator.java @@ -10,23 +10,23 @@ public class BooleanPopulator extends BaseStringPopulator implements BeanStringPopulator { - public Boolean getValue(String value) { + public Boolean getValue(String value) { - if(value == null || value.equalsIgnoreCase("false")){ - return false; - }else{ - return true; - } - } + if(value == null || value.equalsIgnoreCase("false")){ + return false; + }else{ + return true; + } + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return true; - } + return true; + } - public Class getType() { + public Class getType() { - return Boolean.class; - } + return Boolean.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/CharacterPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/CharacterPopulator.java index 3ef9a8a87cf..b4a95977f5b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/CharacterPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/CharacterPopulator.java @@ -14,36 +14,36 @@ public class CharacterPopulator extends BaseStringPopulator implements BeanResultSetPopulator, BeanStringPopulator { - public CharacterPopulator() { + public CharacterPopulator() { - super(); - } + super(); + } - private static final CharacterPopulator POPULATOR = new CharacterPopulator(); + private static final CharacterPopulator POPULATOR = new CharacterPopulator(); - public Character populate(ResultSet rs) throws SQLException { + public Character populate(ResultSet rs) throws SQLException { - return rs.getString(1).charAt(0); - } + return rs.getString(1).charAt(0); + } - public static CharacterPopulator getPopulator() { + public static CharacterPopulator getPopulator() { - return POPULATOR; - } + return POPULATOR; + } - public Character getValue(String value) { + public Character getValue(String value) { - return value.charAt(0); - } + return value.charAt(0); + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return true; - } + return true; + } - public Class getType() { + public Class getType() { - return Character.class; - } + return Character.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/DatePopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/DatePopulator.java index 8bab6982261..5ca0af6c69b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/DatePopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/DatePopulator.java @@ -16,48 +16,48 @@ public class DatePopulator extends BaseStringPopulator { - private final SimpleDateFormat dateFormat; + private final SimpleDateFormat dateFormat; - public DatePopulator(SimpleDateFormat dateFormat) { + public DatePopulator(SimpleDateFormat dateFormat) { - super(); + super(); - this.dateFormat = dateFormat; - } + this.dateFormat = dateFormat; + } - public DatePopulator(String populatorID, SimpleDateFormat dateFormat) { + public DatePopulator(String populatorID, SimpleDateFormat dateFormat) { - super(populatorID); + super(populatorID); - this.dateFormat = dateFormat; - } + this.dateFormat = dateFormat; + } - public DatePopulator(String populatorID, SimpleDateFormat dateFormat, StringFormatValidator formatValidator) { + public DatePopulator(String populatorID, SimpleDateFormat dateFormat, StringFormatValidator formatValidator) { - super(populatorID,formatValidator); - this.dateFormat = dateFormat; - } + super(populatorID,formatValidator); + this.dateFormat = dateFormat; + } - public Class getType() { + public Class getType() { - return Date.class; - } + return Date.class; + } - public Date getValue(String value) { + public Date getValue(String value) { - try { - java.util.Date utilDate = this.dateFormat.parse(value); - - return new Date(utilDate.getTime()); - - } catch (ParseException e) { - throw new RuntimeException(e); - } - } + try { + java.util.Date utilDate = this.dateFormat.parse(value); - @Override - public boolean validateDefaultFormat(String value) { + return new Date(utilDate.getTime()); - return DateUtils.isValidDate(this.dateFormat, value); - } + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean validateDefaultFormat(String value) { + + return DateUtils.isValidDate(this.dateFormat, value); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/DoublePopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/DoublePopulator.java index 0d7ed4ab290..6e8d3a4b4cc 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/DoublePopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/DoublePopulator.java @@ -16,37 +16,37 @@ public class DoublePopulator extends BaseStringPopulator implements BeanResultSetPopulator, BeanStringPopulator { - public DoublePopulator() { - super(); - } + public DoublePopulator() { + super(); + } - public DoublePopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } + public DoublePopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } - public DoublePopulator(String populatorID) { - super(populatorID); - } + public DoublePopulator(String populatorID) { + super(populatorID); + } - public Double populate(ResultSet rs) throws SQLException { + public Double populate(ResultSet rs) throws SQLException { - return rs.getDouble(1); - } + return rs.getDouble(1); + } - public Double getValue(String value) { + public Double getValue(String value) { - return Double.valueOf(value); - } + return Double.valueOf(value); + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return NumberUtils.isDouble(value); - } + return NumberUtils.isDouble(value); + } - public Class getType() { + public Class getType() { - return Double.class; - } + return Double.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/DummyPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/DummyPopulator.java index cf6e6b1af7e..b73ae4340ed 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/DummyPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/DummyPopulator.java @@ -3,23 +3,23 @@ public class DummyPopulator implements BeanStringPopulator { - public boolean validateFormat(String value) { + public boolean validateFormat(String value) { - return false; - } + return false; + } - public Object getValue(String value) { + public Object getValue(String value) { - return null; - } + return null; + } - public Class getType() { + public Class getType() { - return null; - } + return null; + } - public String getPopulatorID() { + public String getPopulatorID() { - return null; - } + return null; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/EnumPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/EnumPopulator.java index bd0ec2d466c..ae34bec8cdc 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/EnumPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/EnumPopulator.java @@ -20,110 +20,110 @@ public class EnumPopulator> extends BaseStringPopulator implements BeanResultSetPopulator, BeanStringPopulator, QueryParameterPopulator { - protected Class classType; - protected String fieldName; + protected Class classType; + protected String fieldName; - public EnumPopulator(Class classType) { - super(); + public EnumPopulator(Class classType) { + super(); - checkClass(classType); - fieldName = classType.getSimpleName(); - } + checkClass(classType); + fieldName = classType.getSimpleName(); + } - public EnumPopulator(Class classType, String fieldName) { + public EnumPopulator(Class classType, String fieldName) { - checkClass(classType); + checkClass(classType); - if (StringUtils.isEmpty(fieldName)) { - throw new NullPointerException("fieldName can not be null or empty!"); - } else { - this.fieldName = fieldName; - } - } + if (StringUtils.isEmpty(fieldName)) { + throw new NullPointerException("fieldName can not be null or empty!"); + } else { + this.fieldName = fieldName; + } + } - private void checkClass(Class classType) { + private void checkClass(Class classType) { - if (classType == null) { - throw new NullPointerException("Classtype can not be null!"); - } else { - this.classType = classType; - } - } + if (classType == null) { + throw new NullPointerException("Classtype can not be null!"); + } else { + this.classType = classType; + } + } - public EnumType populate(ResultSet rs) throws SQLException { + public EnumType populate(ResultSet rs) throws SQLException { - return EnumUtils.toEnum(classType, rs.getString(1)); - } + return EnumUtils.toEnum(classType, rs.getString(1)); + } - public EnumType getValue(String value) { + public EnumType getValue(String value) { - return EnumUtils.toEnum(classType, value); - } + return EnumUtils.toEnum(classType, value); + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return EnumUtils.isEnum(classType, value); - } + return EnumUtils.isEnum(classType, value); + } - public Class getType() { + public Class getType() { - return classType; - } + return classType; + } - public void populate(PreparedStatementQuery query, int paramIndex, Object bean) throws SQLException { + public void populate(PreparedStatementQuery query, int paramIndex, Object bean) throws SQLException { - if(bean != null){ - - query.setString(paramIndex, bean.toString()); - - }else{ - - query.setString(paramIndex, null); - } - - } + if(bean != null){ - public static > EnumPopulator getGenericInstance(Class type) { + query.setString(paramIndex, bean.toString()); - return new EnumPopulator(type); - } + }else{ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static EnumPopulator getInstanceFromField(Field field){ + query.setString(paramIndex, null); + } - Enum enumInstance = EnumUtils.getInstanceFromField(field); + } - return EnumPopulator.getGenericInstance(enumInstance.getClass()); - } + public static > EnumPopulator getGenericInstance(Class type) { - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static EnumPopulator getInstanceFromListField(Field field){ + return new EnumPopulator(type); + } - Object[] enumValues = ((Class)ReflectionUtils.getGenericType(field)).getEnumConstants(); + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static EnumPopulator getInstanceFromField(Field field){ - Enum enumInstance = (Enum) enumValues[0]; + Enum enumInstance = EnumUtils.getInstanceFromField(field); - return EnumPopulator.getGenericInstance(enumInstance.getClass()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static EnumPopulator getInstanceFromMethod(Method method){ + return EnumPopulator.getGenericInstance(enumInstance.getClass()); + } - Object[] enumValues = method.getParameterTypes()[0].getEnumConstants(); + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static EnumPopulator getInstanceFromListField(Field field){ - Enum enumInstance = (Enum) enumValues[0]; + Object[] enumValues = ((Class)ReflectionUtils.getGenericType(field)).getEnumConstants(); - return EnumPopulator.getGenericInstance(enumInstance.getClass()); - } + Enum enumInstance = (Enum) enumValues[0]; - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static BeanStringPopulator getInstanceFromListMethod(Method method) { + return EnumPopulator.getGenericInstance(enumInstance.getClass()); + } - Object[] enumValues = ((Class)ReflectionUtils.getGenericType(method)).getEnumConstants(); + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static EnumPopulator getInstanceFromMethod(Method method){ - Enum enumInstance = (Enum) enumValues[0]; + Object[] enumValues = method.getParameterTypes()[0].getEnumConstants(); - return EnumPopulator.getGenericInstance(enumInstance.getClass()); - } + Enum enumInstance = (Enum) enumValues[0]; + + return EnumPopulator.getGenericInstance(enumInstance.getClass()); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static BeanStringPopulator getInstanceFromListMethod(Method method) { + + Object[] enumValues = ((Class)ReflectionUtils.getGenericType(method)).getEnumConstants(); + + Enum enumInstance = (Enum) enumValues[0]; + + return EnumPopulator.getGenericInstance(enumInstance.getClass()); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/FloatPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/FloatPopulator.java index 532ef0fa4c5..43e04fdf2fc 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/FloatPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/FloatPopulator.java @@ -12,31 +12,31 @@ public class FloatPopulator extends BaseStringPopulator implements BeanStringPopulator { - public FloatPopulator() { - super(); - } + public FloatPopulator() { + super(); + } - public FloatPopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } + public FloatPopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } - public FloatPopulator(String populatorID) { - super(populatorID); - } + public FloatPopulator(String populatorID) { + super(populatorID); + } - public Float getValue(String value) { + public Float getValue(String value) { - return Float.valueOf(value); - } + return Float.valueOf(value); + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return NumberUtils.isFloat(value); - } + return NumberUtils.isFloat(value); + } - public Class getType() { + public Class getType() { - return Float.class; - } + return Float.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/IntegerPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/IntegerPopulator.java index bff9de53e4c..9482d2bc27f 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/IntegerPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/IntegerPopulator.java @@ -17,49 +17,49 @@ public class IntegerPopulator extends BaseStringPopulator implements BeanResultSetPopulator{ - private static final IntegerPopulator POPULATOR = new IntegerPopulator(); + private static final IntegerPopulator POPULATOR = new IntegerPopulator(); - public static IntegerPopulator getPopulator(){ - return POPULATOR; - } + public static IntegerPopulator getPopulator(){ + return POPULATOR; + } - private int columnIndex = 1; + private int columnIndex = 1; - public IntegerPopulator() { - super(); - } + public IntegerPopulator() { + super(); + } - public IntegerPopulator(int columnIndex) { - super(); + public IntegerPopulator(int columnIndex) { + super(); - this.columnIndex = columnIndex; - } + this.columnIndex = columnIndex; + } - public IntegerPopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } + public IntegerPopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } - public IntegerPopulator(String populatorID) { - super(populatorID); - } + public IntegerPopulator(String populatorID) { + super(populatorID); + } - public Integer populate(ResultSet rs) throws SQLException { - return rs.getInt(columnIndex); - } + public Integer populate(ResultSet rs) throws SQLException { + return rs.getInt(columnIndex); + } - public Integer getValue(String value) { + public Integer getValue(String value) { - return Integer.valueOf(value); - } + return Integer.valueOf(value); + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return NumberUtils.isInt(value); - } + return NumberUtils.isInt(value); + } - public Class getType() { + public Class getType() { - return Integer.class; - } + return Integer.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/LongPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/LongPopulator.java index 1858921b456..c208c2bca7b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/LongPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/LongPopulator.java @@ -12,31 +12,31 @@ public class LongPopulator extends BaseStringPopulator { - public LongPopulator() { - super(); - } + public LongPopulator() { + super(); + } - public LongPopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } + public LongPopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } - public LongPopulator(String populatorID) { - super(populatorID); - } + public LongPopulator(String populatorID) { + super(populatorID); + } - public Long getValue(String value) { + public Long getValue(String value) { - return Long.valueOf(value); - } + return Long.valueOf(value); + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return NumberUtils.isLong(value); - } + return NumberUtils.isLong(value); + } - public Class getType() { + public Class getType() { - return Long.class; - } + return Long.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveBooleanPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveBooleanPopulator.java index 3784330937e..a24379093a1 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveBooleanPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveBooleanPopulator.java @@ -10,23 +10,23 @@ public class PrimitiveBooleanPopulator extends BaseStringPopulator implements BeanStringPopulator { - public Boolean getValue(String value) { + public Boolean getValue(String value) { - if(value == null || value.equalsIgnoreCase("false")){ - return false; - }else{ - return true; - } - } + if(value == null || value.equalsIgnoreCase("false")){ + return false; + }else{ + return true; + } + } - @Override - public boolean validateDefaultFormat(String value) { + @Override + public boolean validateDefaultFormat(String value) { - return true; - } + return true; + } - public Class getType() { + public Class getType() { - return boolean.class; - } + return boolean.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveIntegerPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveIntegerPopulator.java index 1492eb71779..a6a697ea1b0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveIntegerPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveIntegerPopulator.java @@ -11,32 +11,32 @@ public class PrimitiveIntegerPopulator extends IntegerPopulator{ - public PrimitiveIntegerPopulator() { - super(); - } + public PrimitiveIntegerPopulator() { + super(); + } - public PrimitiveIntegerPopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } + public PrimitiveIntegerPopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } - public PrimitiveIntegerPopulator(String populatorID) { - super(populatorID); - } + public PrimitiveIntegerPopulator(String populatorID) { + super(populatorID); + } - @Override - public Class getType() { + @Override + public Class getType() { - return int.class; - } + return int.class; + } - @Override - public Integer getValue(String value) { + @Override + public Integer getValue(String value) { - if(value == null){ + if(value == null){ - return 0; - } + return 0; + } - return super.getValue(value); - } + return super.getValue(value); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveLongPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveLongPopulator.java index bc67da55e57..0e95026df57 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveLongPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/PrimitiveLongPopulator.java @@ -12,31 +12,31 @@ public class PrimitiveLongPopulator extends LongPopulator { - public PrimitiveLongPopulator() { - super(); - } + public PrimitiveLongPopulator() { + super(); + } - public PrimitiveLongPopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } + public PrimitiveLongPopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } - public PrimitiveLongPopulator(String populatorID) { - super(populatorID); - } + public PrimitiveLongPopulator(String populatorID) { + super(populatorID); + } - @Override - public Class getType() { + @Override + public Class getType() { - return long.class; - } + return long.class; + } - @Override - public Long getValue(String value) { + @Override + public Long getValue(String value) { - if(value == null){ - return 0l; - } + if(value == null){ + return 0l; + } - return super.getValue(value); - } + return super.getValue(value); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulator.java index 411d84802f4..dc4dd58150e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulator.java @@ -14,7 +14,7 @@ public interface QueryParameterPopulator { - Class getType(); + Class getType(); - void populate(PreparedStatementQuery query, int paramIndex, Object bean) throws SQLException; + void populate(PreparedStatementQuery query, int paramIndex, Object bean) throws SQLException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulatorRegistery.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulatorRegistery.java index 2f30963eea3..4cf0c359cff 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulatorRegistery.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/QueryParameterPopulatorRegistery.java @@ -7,25 +7,25 @@ public class QueryParameterPopulatorRegistery { - private final static HashMap, QueryParameterPopulator> QUERY_PARAMETER_POPULATORS = new HashMap, QueryParameterPopulator>(); - - static{ - addTypePopulator(new UUIDPopulator()); - } - - private static void addTypePopulator(QueryParameterPopulator queryParameterPopulator){ - - QUERY_PARAMETER_POPULATORS.put(queryParameterPopulator.getType(), queryParameterPopulator); - } - - @SuppressWarnings("unchecked") - public static BeanStringPopulator getQueryParameterPopulator(Class clazz){ - - return (BeanStringPopulator) QUERY_PARAMETER_POPULATORS.get(clazz); - } - - public static Collection> getQueryParameterPopulators(){ - - return Collections.unmodifiableCollection(QUERY_PARAMETER_POPULATORS.values()); - } + private final static HashMap, QueryParameterPopulator> QUERY_PARAMETER_POPULATORS = new HashMap, QueryParameterPopulator>(); + + static{ + addTypePopulator(new UUIDPopulator()); + } + + private static void addTypePopulator(QueryParameterPopulator queryParameterPopulator){ + + QUERY_PARAMETER_POPULATORS.put(queryParameterPopulator.getType(), queryParameterPopulator); + } + + @SuppressWarnings("unchecked") + public static BeanStringPopulator getQueryParameterPopulator(Class clazz){ + + return (BeanStringPopulator) QUERY_PARAMETER_POPULATORS.get(clazz); + } + + public static Collection> getQueryParameterPopulators(){ + + return Collections.unmodifiableCollection(QUERY_PARAMETER_POPULATORS.values()); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/StringEntryPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/StringEntryPopulator.java index c433a457270..a3b4b687aaa 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/StringEntryPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/StringEntryPopulator.java @@ -15,8 +15,8 @@ public class StringEntryPopulator implements BeanResultSetPopulator> { - public SimpleEntry populate(ResultSet rs) throws SQLException { + public SimpleEntry populate(ResultSet rs) throws SQLException { - return new SimpleEntry(rs.getString(1),rs.getString(2)); - } + return new SimpleEntry(rs.getString(1),rs.getString(2)); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/StringPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/StringPopulator.java index e46e8963054..3fe5a7072d7 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/StringPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/StringPopulator.java @@ -14,30 +14,30 @@ public class StringPopulator extends BaseStringPopulator implements BeanResultSetPopulator, BeanStringPopulator{ - public StringPopulator() { - super(); - } + public StringPopulator() { + super(); + } - private static final StringPopulator POPULATOR = new StringPopulator(); + private static final StringPopulator POPULATOR = new StringPopulator(); - public String populate(ResultSet rs) throws SQLException { - return rs.getString(1); - } + public String populate(ResultSet rs) throws SQLException { + return rs.getString(1); + } - public static StringPopulator getPopulator(){ - return POPULATOR; - } + public static StringPopulator getPopulator(){ + return POPULATOR; + } - public String getValue(String value) { - return value; - } + public String getValue(String value) { + return value; + } - @Override - public boolean validateDefaultFormat(String value) { - return true; - } + @Override + public boolean validateDefaultFormat(String value) { + return true; + } - public Class getType() { - return String.class; - } + public Class getType() { + return String.class; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/StringURLPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/StringURLPopulator.java index fb73f9b45db..fbb0275c898 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/StringURLPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/StringURLPopulator.java @@ -13,29 +13,29 @@ public class StringURLPopulator extends BaseStringPopulator implements BeanStringPopulator { - public StringURLPopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } - - public StringURLPopulator(String populatorID) { - super(populatorID); - } - - public StringURLPopulator(){ - super("url"); - } - - public Class getType() { - return String.class; - } - - public String getValue(String value) { - return value; - } - - @Override - public boolean validateDefaultFormat(String value) { - return StringUtils.isValidURL(value); - } + public StringURLPopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } + + public StringURLPopulator(String populatorID) { + super(populatorID); + } + + public StringURLPopulator(){ + super("url"); + } + + public Class getType() { + return String.class; + } + + public String getValue(String value) { + return value; + } + + @Override + public boolean validateDefaultFormat(String value) { + return StringUtils.isValidURL(value); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/TimeStampPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/TimeStampPopulator.java index 75b0e6d88e5..885c22573b2 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/TimeStampPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/TimeStampPopulator.java @@ -19,64 +19,64 @@ public class TimeStampPopulator extends BaseStringPopulator implements BeanResultSetPopulator { - private final DateFormat dateFormat; + private final DateFormat dateFormat; - private static final TimeStampPopulator POPULATOR = new TimeStampPopulator(); - - public TimeStampPopulator(){ - super(); - - this.dateFormat = null; - } - - public TimeStampPopulator(DateFormat dateFormat) { + private static final TimeStampPopulator POPULATOR = new TimeStampPopulator(); - super(); + public TimeStampPopulator(){ + super(); - this.dateFormat = dateFormat; - } + this.dateFormat = null; + } - public TimeStampPopulator(String populatorID, DateFormat dateFormat) { + public TimeStampPopulator(DateFormat dateFormat) { - super(populatorID); + super(); - this.dateFormat = dateFormat; - } + this.dateFormat = dateFormat; + } - public TimeStampPopulator(String populatorID, DateFormat dateFormat, StringFormatValidator formatValidator) { + public TimeStampPopulator(String populatorID, DateFormat dateFormat) { - super(populatorID,formatValidator); - this.dateFormat = dateFormat; - } + super(populatorID); - public Class getType() { + this.dateFormat = dateFormat; + } - return Timestamp.class; - } + public TimeStampPopulator(String populatorID, DateFormat dateFormat, StringFormatValidator formatValidator) { - public Timestamp getValue(String value) { + super(populatorID,formatValidator); + this.dateFormat = dateFormat; + } - try { - return new Timestamp(this.dateFormat.parse(value).getTime()); - } catch (ParseException e) { - throw new RuntimeException(e); - } - } + public Class getType() { - @Override - public boolean validateDefaultFormat(String value) { + return Timestamp.class; + } - return DateUtils.isValidDate(this.dateFormat, value); - } - - public static TimeStampPopulator getPopulator(){ - return POPULATOR; - } + public Timestamp getValue(String value) { - public Timestamp populate(ResultSet rs) throws SQLException { - - return rs.getTimestamp(1); - - - } + try { + return new Timestamp(this.dateFormat.parse(value).getTime()); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + @Override + public boolean validateDefaultFormat(String value) { + + return DateUtils.isValidDate(this.dateFormat, value); + } + + public static TimeStampPopulator getPopulator(){ + return POPULATOR; + } + + public Timestamp populate(ResultSet rs) throws SQLException { + + return rs.getTimestamp(1); + + + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/UUIDPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/UUIDPopulator.java index a59dbf880e9..1c8345375c9 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/UUIDPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/UUIDPopulator.java @@ -17,49 +17,49 @@ public class UUIDPopulator extends BaseStringPopulator implements QueryParameterPopulator { - public UUIDPopulator() { - super(); - } + public UUIDPopulator() { + super(); + } - public UUIDPopulator(String populatorID, StringFormatValidator formatValidator) { - super(populatorID, formatValidator); - } + public UUIDPopulator(String populatorID, StringFormatValidator formatValidator) { + super(populatorID, formatValidator); + } - public UUIDPopulator(String populatorID) { - super(populatorID); - } + public UUIDPopulator(String populatorID) { + super(populatorID); + } - @Override - protected boolean validateDefaultFormat(String value) { + @Override + protected boolean validateDefaultFormat(String value) { - try { - UUID.fromString(value); + try { + UUID.fromString(value); - return true; + return true; - } catch (IllegalArgumentException e) {} + } catch (IllegalArgumentException e) {} - return false; - } + return false; + } - public Class getType() { + public Class getType() { - return UUID.class; - } + return UUID.class; + } - public UUID getValue(String value) { + public UUID getValue(String value) { - return UUID.fromString(value); - } + return UUID.fromString(value); + } - public void populate(PreparedStatementQuery query, int paramIndex, Object uuid) throws SQLException { - - if(uuid == null){ - query.setObject(paramIndex, null); - return; - } - - query.setString(paramIndex, ((UUID) uuid).toString()); - } + public void populate(PreparedStatementQuery query, int paramIndex, Object uuid) throws SQLException { + + if(uuid == null){ + query.setObject(paramIndex, null); + return; + } + + query.setString(paramIndex, ((UUID) uuid).toString()); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/UnableToFindSuitablePopulatorException.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/UnableToFindSuitablePopulatorException.java index 78b28a61aa3..6b9d5c6500c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/UnableToFindSuitablePopulatorException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/UnableToFindSuitablePopulatorException.java @@ -3,21 +3,21 @@ public class UnableToFindSuitablePopulatorException extends Exception { - private static final long serialVersionUID = -214177380194928711L; + private static final long serialVersionUID = -214177380194928711L; - public UnableToFindSuitablePopulatorException(String message, Throwable cause) { + public UnableToFindSuitablePopulatorException(String message, Throwable cause) { - super(message, cause); - } + super(message, cause); + } - public UnableToFindSuitablePopulatorException(String message) { + public UnableToFindSuitablePopulatorException(String message) { - super(message); - } + super(message); + } - public UnableToFindSuitablePopulatorException(Throwable cause) { + public UnableToFindSuitablePopulatorException(Throwable cause) { - super(cause); - } + super(cause); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/AnnotatedResultSetPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/AnnotatedResultSetPopulator.java index 05277d32d9b..0a545eaf39c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/AnnotatedResultSetPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/AnnotatedResultSetPopulator.java @@ -36,168 +36,168 @@ public class AnnotatedResultSetPopulator implements BeanResultSetPopulator{ - protected Class beanClass; - protected HashMap resultSetFieldMap = new HashMap(); + protected Class beanClass; + protected HashMap resultSetFieldMap = new HashMap(); - public AnnotatedResultSetPopulator(Class beanClass) throws UnsupportedFieldTypeException{ - this(beanClass, (List>)null); - } + public AnnotatedResultSetPopulator(Class beanClass) throws UnsupportedFieldTypeException{ + this(beanClass, (List>)null); + } - public AnnotatedResultSetPopulator(Class beanClass, BeanStringPopulator... populators) throws UnsupportedFieldTypeException{ - this(beanClass,Arrays.asList(populators)); - } + public AnnotatedResultSetPopulator(Class beanClass, BeanStringPopulator... populators) throws UnsupportedFieldTypeException{ + this(beanClass,Arrays.asList(populators)); + } - @SuppressWarnings("unchecked") - public AnnotatedResultSetPopulator(Class beanClass, List> populators) throws UnsupportedFieldTypeException{ + @SuppressWarnings("unchecked") + public AnnotatedResultSetPopulator(Class beanClass, List> populators) throws UnsupportedFieldTypeException{ - this.beanClass = beanClass; + this.beanClass = beanClass; - //cache fields - List fields = ReflectionUtils.getFields(beanClass); + //cache fields + List fields = ReflectionUtils.getFields(beanClass); - for(Field field : fields){ + for(Field field : fields){ - DAOManaged annotation = field.getAnnotation(DAOManaged.class); + DAOManaged annotation = field.getAnnotation(DAOManaged.class); - if(annotation != null && (!field.isAnnotationPresent(OneToOne.class) && !field.isAnnotationPresent(OneToMany.class) && !field.isAnnotationPresent(ManyToOne.class) && !field.isAnnotationPresent(ManyToMany.class) )){ + if(annotation != null && (!field.isAnnotationPresent(OneToOne.class) && !field.isAnnotationPresent(OneToMany.class) && !field.isAnnotationPresent(ManyToOne.class) && !field.isAnnotationPresent(ManyToMany.class) )){ - if(Modifier.isFinal(field.getModifiers())){ + if(Modifier.isFinal(field.getModifiers())){ - throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in class " + beanClass + " is final!", field, annotation.getClass(), beanClass); + throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in class " + beanClass + " is final!", field, annotation.getClass(), beanClass); - } + } - Method resultSetColumnNameMethod = ResultSetMethods.getColumnNameMethod(field.getType()); + Method resultSetColumnNameMethod = ResultSetMethods.getColumnNameMethod(field.getType()); - BeanStringPopulator typePopulator = null; + BeanStringPopulator typePopulator = null; - if(resultSetColumnNameMethod == null){ + if(resultSetColumnNameMethod == null){ - if(populators != null){ - typePopulator = this.getPopulator(populators, field, annotation); - } - - if(typePopulator == null){ - - typePopulator = BeanStringPopulatorRegistery.getBeanStringPopulator(field.getType()); - } - - if(typePopulator == null){ - - if(field.getType().isEnum()){ + if(populators != null){ + typePopulator = this.getPopulator(populators, field, annotation); + } - typePopulator = EnumPopulator.getInstanceFromField(field); + if(typePopulator == null){ - }else if(List.class.isAssignableFrom(field.getType()) && ReflectionUtils.getGenericlyTypeCount(field) == 1 && ((Class)ReflectionUtils.getGenericType(field)).isEnum()){ + typePopulator = BeanStringPopulatorRegistery.getBeanStringPopulator(field.getType()); + } - typePopulator = EnumPopulator.getInstanceFromListField(field); - } - } + if(typePopulator == null){ - if(typePopulator == null){ - throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in class " + beanClass + " is of unsupported type " + field.getType(), field, annotation.annotationType() , beanClass); - } - } + if(field.getType().isEnum()){ - ReflectionUtils.fixFieldAccess(field); + typePopulator = EnumPopulator.getInstanceFromField(field); - Method resultSetColumnIndexMethod = ResultSetMethods.getColumnIndexMethod(field.getType()); + }else if(List.class.isAssignableFrom(field.getType()) && ReflectionUtils.getGenericlyTypeCount(field) == 1 && ((Class)ReflectionUtils.getGenericType(field)).isEnum()){ - if(!StringUtils.isEmpty(annotation.columnName())){ + typePopulator = EnumPopulator.getInstanceFromListField(field); + } + } - this.resultSetFieldMap.put(field,new ResultSetField(field,resultSetColumnNameMethod,resultSetColumnIndexMethod,annotation.columnName(),typePopulator)); + if(typePopulator == null){ + throw new UnsupportedFieldTypeException("The annotated field " + field.getName() + " in class " + beanClass + " is of unsupported type " + field.getType(), field, annotation.annotationType() , beanClass); + } + } - }else{ + ReflectionUtils.fixFieldAccess(field); - this.resultSetFieldMap.put(field,new ResultSetField(field,resultSetColumnNameMethod,resultSetColumnIndexMethod,field.getName(),typePopulator)); - } - } - } + Method resultSetColumnIndexMethod = ResultSetMethods.getColumnIndexMethod(field.getType()); - if(this.resultSetFieldMap.isEmpty()){ - throw new NoAnnotatedFieldsFoundException(beanClass,DAOManaged.class); - } - } + if(!StringUtils.isEmpty(annotation.columnName())){ - private BeanStringPopulator getPopulator(List> populators, Field field, DAOManaged annotation) { + this.resultSetFieldMap.put(field,new ResultSetField(field,resultSetColumnNameMethod,resultSetColumnIndexMethod,annotation.columnName(),typePopulator)); - String populatorID = annotation.populatorID(); + }else{ - Object clazz = field.getType(); + this.resultSetFieldMap.put(field,new ResultSetField(field,resultSetColumnNameMethod,resultSetColumnIndexMethod,field.getName(),typePopulator)); + } + } + } - for(BeanStringPopulator populator : populators){ + if(this.resultSetFieldMap.isEmpty()){ + throw new NoAnnotatedFieldsFoundException(beanClass,DAOManaged.class); + } + } - if(clazz.equals(populator.getType())){ + private BeanStringPopulator getPopulator(List> populators, Field field, DAOManaged annotation) { - if((StringUtils.isEmpty(populatorID) && populator.getPopulatorID() == null) || populatorID.equals(populator.getPopulatorID())){ + String populatorID = annotation.populatorID(); - return populator; - } - } - } + Object clazz = field.getType(); - return null; - } + for(BeanStringPopulator populator : populators){ - public T populate(ResultSet rs) throws SQLException, BeanResultSetPopulationException { + if(clazz.equals(populator.getType())){ - ResultSetField currentField = null; + if((StringUtils.isEmpty(populatorID) && populator.getPopulatorID() == null) || populatorID.equals(populator.getPopulatorID())){ - try { - T bean = beanClass.newInstance(); + return populator; + } + } + } - for(ResultSetField resultSetField : this.resultSetFieldMap.values()){ + return null; + } - currentField = resultSetField; + public T populate(ResultSet rs) throws SQLException, BeanResultSetPopulationException { - if(currentField.getResultSetColumnNameMethod() != null){ + ResultSetField currentField = null; - Object value = resultSetField.getResultSetColumnNameMethod().invoke(rs, resultSetField.getAlias()); + try { + T bean = beanClass.newInstance(); - if(rs.wasNull() && !resultSetField.getBeanField().getType().isPrimitive()){ + for(ResultSetField resultSetField : this.resultSetFieldMap.values()){ - resultSetField.getBeanField().set(bean, null); + currentField = resultSetField; - }else{ + if(currentField.getResultSetColumnNameMethod() != null){ - resultSetField.getBeanField().set(bean, value); - } + Object value = resultSetField.getResultSetColumnNameMethod().invoke(rs, resultSetField.getAlias()); - }else{ + if(rs.wasNull() && !resultSetField.getBeanField().getType().isPrimitive()){ - String value = rs.getString(currentField.getAlias()); + resultSetField.getBeanField().set(bean, null); - if(value != null || currentField.getBeanStringPopulator().getType().isPrimitive()){ + }else{ - resultSetField.getBeanField().set(bean, currentField.getBeanStringPopulator().getValue(value)); - }else{ - resultSetField.getBeanField().set(bean, null); - } - } - } + resultSetField.getBeanField().set(bean, value); + } - return bean; + }else{ - } catch (InstantiationException e) { + String value = rs.getString(currentField.getAlias()); - throw new BeanResultSetPopulationException(currentField,e); + if(value != null || currentField.getBeanStringPopulator().getType().isPrimitive()){ - } catch (IllegalAccessException e) { + resultSetField.getBeanField().set(bean, currentField.getBeanStringPopulator().getValue(value)); + }else{ + resultSetField.getBeanField().set(bean, null); + } + } + } - throw new BeanResultSetPopulationException(currentField,e); + return bean; - } catch (IllegalArgumentException e) { + } catch (InstantiationException e) { - throw new BeanResultSetPopulationException(currentField,e); + throw new BeanResultSetPopulationException(currentField,e); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException e) { - throw new BeanResultSetPopulationException(currentField,e); - } - } + throw new BeanResultSetPopulationException(currentField,e); - public ResultSetField getResultSetField(Field field){ + } catch (IllegalArgumentException e) { - return this.resultSetFieldMap.get(field); - } + throw new BeanResultSetPopulationException(currentField,e); + + } catch (InvocationTargetException e) { + + throw new BeanResultSetPopulationException(currentField,e); + } + } + + public ResultSetField getResultSetField(Field field){ + + return this.resultSetFieldMap.get(field); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/BeanResultSetPopulationException.java b/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/BeanResultSetPopulationException.java index 6ecfc4c7f1b..833b763baaf 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/BeanResultSetPopulationException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/populators/annotated/BeanResultSetPopulationException.java @@ -12,15 +12,15 @@ public class BeanResultSetPopulationException extends RuntimeException { - private static final long serialVersionUID = 3781653780279983974L; - private final ResultSetField resultSetField; + private static final long serialVersionUID = 3781653780279983974L; + private final ResultSetField resultSetField; - public BeanResultSetPopulationException(ResultSetField resultSetField, Exception e) { - super(e); - this.resultSetField = resultSetField; - } + public BeanResultSetPopulationException(ResultSetField resultSetField, Exception e) { + super(e); + this.resultSetField = resultSetField; + } - public ResultSetField getResultSetField() { - return resultSetField; - } + public ResultSetField getResultSetField() { + return resultSetField; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/random/RandomUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/random/RandomUtils.java index a6a4e158284..1de879aeb6e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/random/RandomUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/random/RandomUtils.java @@ -11,38 +11,38 @@ public class RandomUtils { - private static final Random RANDOM = new Random(); + private static final Random RANDOM = new Random(); - public static String getRandomString(int minLength, int maxLength){ + public static String getRandomString(int minLength, int maxLength){ - int length; + int length; - if(minLength == maxLength){ + if(minLength == maxLength){ - length = minLength; + length = minLength; - }else{ + }else{ - length = RANDOM.nextInt(maxLength - minLength) + minLength; - } + length = RANDOM.nextInt(maxLength - minLength) + minLength; + } - char[] randomString = new char[length]; + char[] randomString = new char[length]; - for (int x = 0; x < length; x++) { - int randDecimalAsciiVal = RANDOM.nextInt(25) + 97; - randomString[x] = (char) randDecimalAsciiVal; - } + for (int x = 0; x < length; x++) { + int randDecimalAsciiVal = RANDOM.nextInt(25) + 97; + randomString[x] = (char) randDecimalAsciiVal; + } - return new String(randomString); - } + return new String(randomString); + } - public static int getRandomInt(int min, int max) { + public static int getRandomInt(int min, int max) { - return RANDOM.nextInt(max) + min; - } + return RANDOM.nextInt(max) + min; + } - public static boolean getRandomBoolean() { + public static boolean getRandomBoolean() { - return getRandomInt(0, 2) == 1; - } + return getRandomInt(0, 2) == 1; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/readwrite/ReadWriteUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/readwrite/ReadWriteUtils.java index 83ae42cb4a3..90c7c37f3b6 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/readwrite/ReadWriteUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/readwrite/ReadWriteUtils.java @@ -14,36 +14,36 @@ public class ReadWriteUtils { - public static void transfer(Reader reader, Writer writer) throws IOException { + public static void transfer(Reader reader, Writer writer) throws IOException { - char[] buf = new char[8192]; - int count = 0; + char[] buf = new char[8192]; + int count = 0; - while ((count = reader.read(buf)) >= 0) { + while ((count = reader.read(buf)) >= 0) { - writer.write(buf, 0, count); - } - writer.flush(); - } + writer.write(buf, 0, count); + } + writer.flush(); + } - public static void closeReader(Reader reader){ + public static void closeReader(Reader reader){ - if(reader != null){ + if(reader != null){ - try { - reader.close(); - } catch (IOException e) {} - } - } + try { + reader.close(); + } catch (IOException e) {} + } + } - public static void closeWriter(Writer writer){ + public static void closeWriter(Writer writer){ - if(writer != null){ + if(writer != null){ - try { - writer.close(); - } catch (IOException e) {} - } - } + try { + writer.close(); + } catch (IOException e) {} + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/references/WeakReferenceUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/references/WeakReferenceUtils.java index ca4bf5adfb7..c016627415b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/references/WeakReferenceUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/references/WeakReferenceUtils.java @@ -5,13 +5,13 @@ public class WeakReferenceUtils { - public static T getReferenceValue(WeakReference weakReference){ - - if(weakReference == null){ - - return null; - } - - return weakReference.get(); - } + public static T getReferenceValue(WeakReference weakReference){ + + if(weakReference == null){ + + return null; + } + + return weakReference.get(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/reflection/MethodNotFoundException.java b/eagledns/src/main/java/se/unlogic/standardutils/reflection/MethodNotFoundException.java index bf3afde1479..b057d4c3dc6 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/reflection/MethodNotFoundException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/reflection/MethodNotFoundException.java @@ -3,25 +3,25 @@ public class MethodNotFoundException extends Exception { - private static final long serialVersionUID = -8580739778092215878L; + private static final long serialVersionUID = -8580739778092215878L; - public MethodNotFoundException() { + public MethodNotFoundException() { - super(); - } + super(); + } - public MethodNotFoundException(String message, Throwable cause) { + public MethodNotFoundException(String message, Throwable cause) { - super(message, cause); - } + super(message, cause); + } - public MethodNotFoundException(String message) { + public MethodNotFoundException(String message) { - super(message); - } + super(message); + } - public MethodNotFoundException(Throwable cause) { + public MethodNotFoundException(Throwable cause) { - super(cause); - } + super(cause); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/reflection/ReflectionUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/reflection/ReflectionUtils.java index 99c9fbe91e0..1713574dd62 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/reflection/ReflectionUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/reflection/ReflectionUtils.java @@ -24,256 +24,256 @@ public class ReflectionUtils { - public static Object getInstance(String className) throws NoClassDefFoundError, ClassNotFoundException, InstantiationException, IllegalAccessException { - return Class.forName(className).newInstance(); - } + public static Object getInstance(String className) throws NoClassDefFoundError, ClassNotFoundException, InstantiationException, IllegalAccessException { + return Class.forName(className).newInstance(); + } - public static boolean isGenericlyTyped(Field field) { + public static boolean isGenericlyTyped(Field field) { - if (field.getGenericType() instanceof ParameterizedType) { + if (field.getGenericType() instanceof ParameterizedType) { - return true; - } + return true; + } - return false; - } + return false; + } - public static int getGenericlyTypeCount(Field field) { + public static int getGenericlyTypeCount(Field field) { - if (field.getGenericType() instanceof ParameterizedType) { + if (field.getGenericType() instanceof ParameterizedType) { - ParameterizedType type = (ParameterizedType) field.getGenericType(); + ParameterizedType type = (ParameterizedType) field.getGenericType(); - return type.getActualTypeArguments().length; - } + return type.getActualTypeArguments().length; + } - return 0; - } + return 0; + } - public static int getGenericlyTypeCount(Method method) { + public static int getGenericlyTypeCount(Method method) { - return method.getGenericParameterTypes().length; - } - - public static boolean checkGenericTypes(Field field, Class... classes) { + return method.getGenericParameterTypes().length; + } - if (field.getGenericType() instanceof ParameterizedType) { + public static boolean checkGenericTypes(Field field, Class... classes) { - ParameterizedType type = (ParameterizedType) field.getGenericType(); + if (field.getGenericType() instanceof ParameterizedType) { - if (type.getActualTypeArguments().length != classes.length) { - return false; - } - - for (int i = 0; i < classes.length; i++) { - - if (!type.getActualTypeArguments()[i].equals(classes[i])) { - return false; - } - } - - return true; - } - - return false; - } - - public static Type getGenericType(Field field) { - - Type type = ((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]; - - if(type instanceof WildcardType){ - - //TODO do a little bit more research on this part... - return ((WildcardType)type).getUpperBounds()[0]; - - }else{ - - return type; - } - } - - public static Object getGenericType(Method method) { - - return method.getGenericParameterTypes()[0]; - } - - public static void fixFieldAccess(Field field) { - - if(!field.isAccessible()){ - field.setAccessible(true); - } - } - - public static void fixMethodAccess(Method method) { - - if(!method.isAccessible()){ - method.setAccessible(true); - } - } - - public static Field getField(Class bean, String fieldName) { - - - List fields = getFields(bean); - - for(Field field : fields){ - - if(field.getName().equals(fieldName)){ - - return field; - } - } - - throw new RuntimeException(new NoSuchFieldError(fieldName)); - } - - public static boolean isAvailable(String classname) { - try { - Class.forName(classname); - return true; - } catch (ClassNotFoundException cnfe) { - return false; - } - } - - public static List getFields(Class clazz){ - - ArrayList fields = new ArrayList(); - - fields.addAll(Arrays.asList(clazz.getDeclaredFields())); - - clazz = clazz.getSuperclass(); - - while(clazz != Object.class){ - - fields.addAll(Arrays.asList(clazz.getDeclaredFields())); - - clazz = clazz.getSuperclass(); - } - - return fields; - } - - public static List getMethods(Class clazz){ - - ArrayList methods = new ArrayList(); - - methods.addAll(Arrays.asList(clazz.getDeclaredMethods())); - - clazz = clazz.getSuperclass(); - - while(clazz != Object.class){ - - methods.addAll(Arrays.asList(clazz.getDeclaredMethods())); - - clazz = clazz.getSuperclass(); - } - - return methods; - } - - public static Method getMethod(Class clazz, String methodName, Class returnType, Class... inputParams) { - - if(inputParams == null){ - - inputParams = new Class[0]; - } - - Method[] methods = clazz.getDeclaredMethods(); - - for(Method method : methods){ - - if(method.getName().equals(methodName) && returnType.isAssignableFrom(method.getReturnType()) && Arrays.equals(inputParams, method.getParameterTypes())){ - - return method; - } - } - - return null; - } - - - public static void setFieldValue(Field field, Object value, Object target) throws IllegalArgumentException, IllegalAccessException { - - boolean declaredAccessible = field.isAccessible(); - - if (!declaredAccessible) { - field.setAccessible(true); - } - - field.set(target, value); - - if (!declaredAccessible) { - field.setAccessible(false); - } - } - - public static void setMethodValue(Method method, Object value, Object target) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { - - boolean declaredAccessible = method.isAccessible(); - - if (!declaredAccessible) { - method.setAccessible(true); - } - - method.invoke(target, value); - - if (!declaredAccessible) { - method.setAccessible(false); - } - } - - public static boolean setSetterMethod(Object target, String methodName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, MethodNotFoundException, UnableToFindSuitablePopulatorException { - - if(!methodName.startsWith("set")){ - - methodName = "set" + StringUtils.toFirstLetterUppercase(methodName); - } - - Method method = getMethod(target.getClass(),methodName,1); - - if(method == null){ - - throw new MethodNotFoundException("Unable to find setter method " + methodName + " with correct signature"); - } - - if(value == null || method.getParameterTypes()[0].equals(String.class)){ - - setMethodValue(method,value,target); - } - - BeanStringPopulator populator = BeanStringPopulatorRegistery.getBeanStringPopulator(method.getParameterTypes()[0]); - - if(populator == null){ - - throw new UnableToFindSuitablePopulatorException("Unable to find BeanStringPopulator for " + method.getParameterTypes()[0]); - } - - setMethodValue(method,populator.getValue(value),target); - - return true; - } - - public static Method getMethod(Class clazz, String methodName, int argumentCount) { - - List methods = getMethods(clazz); - - for(Method method : methods){ - - if(!method.getName().equalsIgnoreCase(methodName)){ - - continue; - } - - if(method.getParameterTypes().length != argumentCount){ - - continue; - } - - return method; - } - - return null; - } + ParameterizedType type = (ParameterizedType) field.getGenericType(); + + if (type.getActualTypeArguments().length != classes.length) { + return false; + } + + for (int i = 0; i < classes.length; i++) { + + if (!type.getActualTypeArguments()[i].equals(classes[i])) { + return false; + } + } + + return true; + } + + return false; + } + + public static Type getGenericType(Field field) { + + Type type = ((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]; + + if(type instanceof WildcardType){ + + //TODO do a little bit more research on this part... + return ((WildcardType)type).getUpperBounds()[0]; + + }else{ + + return type; + } + } + + public static Object getGenericType(Method method) { + + return method.getGenericParameterTypes()[0]; + } + + public static void fixFieldAccess(Field field) { + + if(!field.isAccessible()){ + field.setAccessible(true); + } + } + + public static void fixMethodAccess(Method method) { + + if(!method.isAccessible()){ + method.setAccessible(true); + } + } + + public static Field getField(Class bean, String fieldName) { + + + List fields = getFields(bean); + + for(Field field : fields){ + + if(field.getName().equals(fieldName)){ + + return field; + } + } + + throw new RuntimeException(new NoSuchFieldError(fieldName)); + } + + public static boolean isAvailable(String classname) { + try { + Class.forName(classname); + return true; + } catch (ClassNotFoundException cnfe) { + return false; + } + } + + public static List getFields(Class clazz){ + + ArrayList fields = new ArrayList(); + + fields.addAll(Arrays.asList(clazz.getDeclaredFields())); + + clazz = clazz.getSuperclass(); + + while(clazz != Object.class){ + + fields.addAll(Arrays.asList(clazz.getDeclaredFields())); + + clazz = clazz.getSuperclass(); + } + + return fields; + } + + public static List getMethods(Class clazz){ + + ArrayList methods = new ArrayList(); + + methods.addAll(Arrays.asList(clazz.getDeclaredMethods())); + + clazz = clazz.getSuperclass(); + + while(clazz != Object.class){ + + methods.addAll(Arrays.asList(clazz.getDeclaredMethods())); + + clazz = clazz.getSuperclass(); + } + + return methods; + } + + public static Method getMethod(Class clazz, String methodName, Class returnType, Class... inputParams) { + + if(inputParams == null){ + + inputParams = new Class[0]; + } + + Method[] methods = clazz.getDeclaredMethods(); + + for(Method method : methods){ + + if(method.getName().equals(methodName) && returnType.isAssignableFrom(method.getReturnType()) && Arrays.equals(inputParams, method.getParameterTypes())){ + + return method; + } + } + + return null; + } + + + public static void setFieldValue(Field field, Object value, Object target) throws IllegalArgumentException, IllegalAccessException { + + boolean declaredAccessible = field.isAccessible(); + + if (!declaredAccessible) { + field.setAccessible(true); + } + + field.set(target, value); + + if (!declaredAccessible) { + field.setAccessible(false); + } + } + + public static void setMethodValue(Method method, Object value, Object target) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { + + boolean declaredAccessible = method.isAccessible(); + + if (!declaredAccessible) { + method.setAccessible(true); + } + + method.invoke(target, value); + + if (!declaredAccessible) { + method.setAccessible(false); + } + } + + public static boolean setSetterMethod(Object target, String methodName, String value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, MethodNotFoundException, UnableToFindSuitablePopulatorException { + + if(!methodName.startsWith("set")){ + + methodName = "set" + StringUtils.toFirstLetterUppercase(methodName); + } + + Method method = getMethod(target.getClass(),methodName,1); + + if(method == null){ + + throw new MethodNotFoundException("Unable to find setter method " + methodName + " with correct signature"); + } + + if(value == null || method.getParameterTypes()[0].equals(String.class)){ + + setMethodValue(method,value,target); + } + + BeanStringPopulator populator = BeanStringPopulatorRegistery.getBeanStringPopulator(method.getParameterTypes()[0]); + + if(populator == null){ + + throw new UnableToFindSuitablePopulatorException("Unable to find BeanStringPopulator for " + method.getParameterTypes()[0]); + } + + setMethodValue(method,populator.getValue(value),target); + + return true; + } + + public static Method getMethod(Class clazz, String methodName, int argumentCount) { + + List methods = getMethods(clazz); + + for(Method method : methods){ + + if(!method.getName().equalsIgnoreCase(methodName)){ + + continue; + } + + if(method.getParameterTypes().length != argumentCount){ + + continue; + } + + return method; + } + + return null; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/rmi/PasswordLogin.java b/eagledns/src/main/java/se/unlogic/standardutils/rmi/PasswordLogin.java index f488d3a5d85..e5c00608b6c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/rmi/PasswordLogin.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/rmi/PasswordLogin.java @@ -14,5 +14,5 @@ public interface PasswordLogin extends Remote{ - T login(String password) throws RemoteException; + T login(String password) throws RemoteException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/rmi/RMIUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/rmi/RMIUtils.java index 42c9e4a9dd6..82a3ebfb37d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/rmi/RMIUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/rmi/RMIUtils.java @@ -6,12 +6,12 @@ public class RMIUtils { - public static String getClientHost(){ - - try { - return UnicastRemoteObject.getClientHost(); - } catch (ServerNotActiveException e) { - throw new RuntimeException(e); - } - } + public static String getClientHost(){ + + try { + return UnicastRemoteObject.getClientHost(); + } catch (ServerNotActiveException e) { + throw new RuntimeException(e); + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/rmi/TimeoutRMISocketFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/rmi/TimeoutRMISocketFactory.java index 355c8b986e0..e7a569c8e09 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/rmi/TimeoutRMISocketFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/rmi/TimeoutRMISocketFactory.java @@ -8,29 +8,29 @@ public class TimeoutRMISocketFactory extends RMISocketFactory{ - protected int readTimeout; - protected int connectionTimeout; - - public TimeoutRMISocketFactory(int readTimeout, int connectionTimeout) { - - super(); - this.readTimeout = readTimeout; - this.connectionTimeout = connectionTimeout; - } - - @Override - public Socket createSocket(String host, int port) throws IOException { - - Socket socket = new Socket(); - socket.setSoTimeout(readTimeout); - socket.setSoLinger(false, 0); - socket.connect(new InetSocketAddress(host, port), connectionTimeout); - return socket; - } - - @Override - public ServerSocket createServerSocket(int port) throws IOException { - - return new ServerSocket(port); - } -} \ No newline at end of file + protected int readTimeout; + protected int connectionTimeout; + + public TimeoutRMISocketFactory(int readTimeout, int connectionTimeout) { + + super(); + this.readTimeout = readTimeout; + this.connectionTimeout = connectionTimeout; + } + + @Override + public Socket createSocket(String host, int port) throws IOException { + + Socket socket = new Socket(); + socket.setSoTimeout(readTimeout); + socket.setSoLinger(false, 0); + socket.connect(new InetSocketAddress(host, port), connectionTimeout); + return socket; + } + + @Override + public ServerSocket createServerSocket(int port) throws IOException { + + return new ServerSocket(port); + } +} diff --git a/eagledns/src/main/java/se/unlogic/standardutils/settings/SettingNode.java b/eagledns/src/main/java/se/unlogic/standardutils/settings/SettingNode.java index 78c2cd7b92e..58169f43fbe 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/settings/SettingNode.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/settings/SettingNode.java @@ -11,30 +11,30 @@ public interface SettingNode { - SettingNode getSetting(String expression); - - List getSettings(String expression); - - Integer getInteger(String expression); - - List getIntegers(String expression); - - int getInt(String expression); - - Double getDouble(String expression); - - List getDoubles(String expression); - - Long getLong(String expression); - - List getLongs(String expression); - - String getString(String expression); - - List getStrings(String expression); - - Boolean getBoolean(String expression); - - boolean getPrimitiveBoolean(String expression); + SettingNode getSetting(String expression); + + List getSettings(String expression); + + Integer getInteger(String expression); + + List getIntegers(String expression); + + int getInt(String expression); + + Double getDouble(String expression); + + List getDoubles(String expression); + + Long getLong(String expression); + + List getLongs(String expression); + + String getString(String expression); + + List getStrings(String expression); + + Boolean getBoolean(String expression); + + boolean getPrimitiveBoolean(String expression); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/settings/XMLSettingNode.java b/eagledns/src/main/java/se/unlogic/standardutils/settings/XMLSettingNode.java index 180ccc8ae03..0f511b6f205 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/settings/XMLSettingNode.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/settings/XMLSettingNode.java @@ -26,251 +26,251 @@ public class XMLSettingNode implements SettingNode { - private final Element element; - private final XPath xpath; + private final Element element; + private final XPath xpath; - public XMLSettingNode(String path) throws SAXException, IOException, ParserConfigurationException { + public XMLSettingNode(String path) throws SAXException, IOException, ParserConfigurationException { - Document doc = XMLUtils.parseXmlFile(path, false,false); - this.element = doc.getDocumentElement(); + Document doc = XMLUtils.parseXmlFile(path, false,false); + this.element = doc.getDocumentElement(); - this.xpath = XPathFactory.newInstance().newXPath(); + this.xpath = XPathFactory.newInstance().newXPath(); - } + } - public XMLSettingNode(Document doc) { + public XMLSettingNode(Document doc) { - this.element = doc.getDocumentElement(); + this.element = doc.getDocumentElement(); - this.xpath = XPathFactory.newInstance().newXPath(); - } + this.xpath = XPathFactory.newInstance().newXPath(); + } - public XMLSettingNode(Element element) { + public XMLSettingNode(Element element) { - this.element = element; + this.element = element; - this.xpath = XPathFactory.newInstance().newXPath(); + this.xpath = XPathFactory.newInstance().newXPath(); - } + } - public XMLSettingNode(File configurationFile) throws SAXException, IOException, ParserConfigurationException { + public XMLSettingNode(File configurationFile) throws SAXException, IOException, ParserConfigurationException { - Document doc = XMLUtils.parseXmlFile(configurationFile, false); - this.element = doc.getDocumentElement(); + Document doc = XMLUtils.parseXmlFile(configurationFile, false); + this.element = doc.getDocumentElement(); - this.xpath = XPathFactory.newInstance().newXPath(); - } + this.xpath = XPathFactory.newInstance().newXPath(); + } - public Boolean getBoolean(String expression) { + public Boolean getBoolean(String expression) { - return Boolean.valueOf(this.getString(expression)); + return Boolean.valueOf(this.getString(expression)); - } + } - public boolean getPrimitiveBoolean(String expression) { + public boolean getPrimitiveBoolean(String expression) { - return Boolean.parseBoolean(this.getString(expression)); + return Boolean.parseBoolean(this.getString(expression)); - } + } - public Double getDouble(String expression) { + public Double getDouble(String expression) { - String value = this.getString(expression); + String value = this.getString(expression); - if(value != null){ - return NumberUtils.toDouble(value); - } + if(value != null){ + return NumberUtils.toDouble(value); + } - return null; + return null; - } + } - public List getDoubles(String expression) { + public List getDoubles(String expression) { - NodeList nodes = this.getNodeList(expression); + NodeList nodes = this.getNodeList(expression); - List doubles = new ArrayList(); + List doubles = new ArrayList(); - for (int i = 0; i < nodes.getLength(); i++) { + for (int i = 0; i < nodes.getLength(); i++) { - String value = nodes.item(i).getTextContent(); + String value = nodes.item(i).getTextContent(); - if(value != null){ - Double numberValue = NumberUtils.toDouble(value); + if(value != null){ + Double numberValue = NumberUtils.toDouble(value); - if(numberValue != null){ - doubles.add(numberValue); - } - } - } + if(numberValue != null){ + doubles.add(numberValue); + } + } + } - return doubles; + return doubles; - } + } - public int getInt(String expression) { + public int getInt(String expression) { - String value = this.getString(expression); + String value = this.getString(expression); - if(value != null && NumberUtils.isInt(value)){ - return NumberUtils.toInt(value); - } + if(value != null && NumberUtils.isInt(value)){ + return NumberUtils.toInt(value); + } - return 0; + return 0; - } + } - public Integer getInteger(String expression) { + public Integer getInteger(String expression) { - String value = this.getString(expression); + String value = this.getString(expression); - if(value != null){ - return NumberUtils.toInt(value); - } + if(value != null){ + return NumberUtils.toInt(value); + } - return null; + return null; - } + } - public List getIntegers(String expression) { + public List getIntegers(String expression) { - NodeList nodes = this.getNodeList(expression); + NodeList nodes = this.getNodeList(expression); - List integers = new ArrayList(); + List integers = new ArrayList(); - for (int i = 0; i < nodes.getLength(); i++) { + for (int i = 0; i < nodes.getLength(); i++) { - String value = nodes.item(i).getTextContent(); + String value = nodes.item(i).getTextContent(); - if(value != null){ - Integer numberValue = NumberUtils.toInt(value); + if(value != null){ + Integer numberValue = NumberUtils.toInt(value); - if(numberValue != null){ - integers.add(numberValue); - } - } - } + if(numberValue != null){ + integers.add(numberValue); + } + } + } - return integers; + return integers; - } + } - public Long getLong(String expression) { + public Long getLong(String expression) { - String value = this.getString(expression); + String value = this.getString(expression); - if(value != null){ - return NumberUtils.toLong(value); - } + if(value != null){ + return NumberUtils.toLong(value); + } - return null; + return null; - } + } - public List getLongs(String expression) { + public List getLongs(String expression) { - NodeList nodes = this.getNodeList(expression); + NodeList nodes = this.getNodeList(expression); - List longs = new ArrayList(); + List longs = new ArrayList(); - for (int i = 0; i < nodes.getLength(); i++) { + for (int i = 0; i < nodes.getLength(); i++) { - String value = nodes.item(i).getTextContent(); + String value = nodes.item(i).getTextContent(); - if(value != null){ - Long numberValue = NumberUtils.toLong(value); + if(value != null){ + Long numberValue = NumberUtils.toLong(value); - if(numberValue != null){ - longs.add(numberValue); - } - } - } + if(numberValue != null){ + longs.add(numberValue); + } + } + } - return longs; + return longs; - } + } - public XMLSettingNode getSetting(String expression) { + public XMLSettingNode getSetting(String expression) { - Element element = this.getElement(expression); + Element element = this.getElement(expression); - if(element == null){ - - return null; - } - - return new XMLSettingNode(element); + if(element == null){ - } + return null; + } - public List getSettings(String expression) { + return new XMLSettingNode(element); - NodeList nodes = this.getNodeList(expression); + } - List settingNodes = new ArrayList(); + public List getSettings(String expression) { - for(int i = 0; i < nodes.getLength(); i++){ + NodeList nodes = this.getNodeList(expression); - settingNodes.add(new XMLSettingNode((Element)nodes.item(i))); + List settingNodes = new ArrayList(); - } + for(int i = 0; i < nodes.getLength(); i++){ - return settingNodes; + settingNodes.add(new XMLSettingNode((Element)nodes.item(i))); - } + } - public String getString(String expression) { + return settingNodes; - try { - return this.xpath.evaluate(expression, this.element); - } catch (XPathExpressionException e) { - return null; - } + } - } + public String getString(String expression) { - public List getStrings(String expression) { + try { + return this.xpath.evaluate(expression, this.element); + } catch (XPathExpressionException e) { + return null; + } - NodeList nodes = this.getNodeList(expression); + } - if(nodes != null && nodes.getLength() > 0){ + public List getStrings(String expression) { - List strings = new ArrayList(); - - for (int i = 0; i < nodes.getLength(); i++) { + NodeList nodes = this.getNodeList(expression); - strings.add(nodes.item(i).getTextContent()); + if(nodes != null && nodes.getLength() > 0){ - } - - return strings; - } - - return null; - } + List strings = new ArrayList(); - private NodeList getNodeList(String expression){ + for (int i = 0; i < nodes.getLength(); i++) { - try { - return (NodeList) this.xpath.evaluate(expression, this.element, XPathConstants.NODESET); - } catch(XPathExpressionException e) { - return null; - } + strings.add(nodes.item(i).getTextContent()); - } + } - private Element getElement(String expression){ + return strings; + } - try { - return (Element) this.xpath.evaluate(expression, this.element, XPathConstants.NODE); - } catch(XPathExpressionException e) { - return null; - } - } + return null; + } - public String getElementName(){ - - return element.getTagName(); - } + private NodeList getNodeList(String expression){ + + try { + return (NodeList) this.xpath.evaluate(expression, this.element, XPathConstants.NODESET); + } catch(XPathExpressionException e) { + return null; + } + + } + + private Element getElement(String expression){ + + try { + return (Element) this.xpath.evaluate(expression, this.element, XPathConstants.NODE); + } catch(XPathExpressionException e) { + return null; + } + } + + public String getElementName(){ + + return element.getTagName(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/streams/StreamUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/streams/StreamUtils.java index ebbbf6a55b0..116f098ad2e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/streams/StreamUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/streams/StreamUtils.java @@ -15,43 +15,43 @@ public class StreamUtils { - public static byte[] toByteArray(InputStream inputStream) throws IOException{ + public static byte[] toByteArray(InputStream inputStream) throws IOException{ - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - transfer(inputStream, outputStream); + transfer(inputStream, outputStream); - return outputStream.toByteArray(); - } + return outputStream.toByteArray(); + } - public static void transfer(InputStream inputStream, OutputStream outputStream) throws IOException{ + public static void transfer(InputStream inputStream, OutputStream outputStream) throws IOException{ - byte[] buf = new byte[8192]; - int count = 0; + byte[] buf = new byte[8192]; + int count = 0; - while ((count = inputStream.read(buf)) >= 0) { + while ((count = inputStream.read(buf)) >= 0) { - outputStream.write(buf, 0, count); - } - } + outputStream.write(buf, 0, count); + } + } - public static void closeStream(InputStream stream){ + public static void closeStream(InputStream stream){ - if(stream != null){ + if(stream != null){ - try { - stream.close(); - } catch (IOException e) {} - } - } + try { + stream.close(); + } catch (IOException e) {} + } + } - public static void closeStream(OutputStream stream){ + public static void closeStream(OutputStream stream){ - if(stream != null){ + if(stream != null){ - try { - stream.close(); - } catch (IOException e) {} - } - } + try { + stream.close(); + } catch (IOException e) {} + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/AnnotatedBeanTagSourceFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/string/AnnotatedBeanTagSourceFactory.java index 206c4e5187f..b75984b2642 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/AnnotatedBeanTagSourceFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/AnnotatedBeanTagSourceFactory.java @@ -9,46 +9,46 @@ public class AnnotatedBeanTagSourceFactory extends BeanTagSourceFactory { - public AnnotatedBeanTagSourceFactory(Class beanClass, String defaultPrefix) { - - super(beanClass); - - List fields = ReflectionUtils.getFields(beanClass); - - for(Field field : fields){ - - StringTag stringTag = field.getAnnotation(StringTag.class); - - if(stringTag != null){ - - if(StringUtils.isEmpty(stringTag.name())){ - - addFieldMapping(defaultPrefix + field.getName(), field); - - }else{ - - addFieldMapping(defaultPrefix + stringTag.name(), field); - } - } - } - - List methods = ReflectionUtils.getMethods(beanClass); - - for(Method method : methods){ - - StringTag stringTag = method.getAnnotation(StringTag.class); - - if(stringTag != null){ - - if(StringUtils.isEmpty(stringTag.name())){ - - addMethodMapping(defaultPrefix + method.getName(), method); - - }else{ - - addMethodMapping(defaultPrefix + stringTag.name(), method); - } - } - } - } + public AnnotatedBeanTagSourceFactory(Class beanClass, String defaultPrefix) { + + super(beanClass); + + List fields = ReflectionUtils.getFields(beanClass); + + for(Field field : fields){ + + StringTag stringTag = field.getAnnotation(StringTag.class); + + if(stringTag != null){ + + if(StringUtils.isEmpty(stringTag.name())){ + + addFieldMapping(defaultPrefix + field.getName(), field); + + }else{ + + addFieldMapping(defaultPrefix + stringTag.name(), field); + } + } + } + + List methods = ReflectionUtils.getMethods(beanClass); + + for(Method method : methods){ + + StringTag stringTag = method.getAnnotation(StringTag.class); + + if(stringTag != null){ + + if(StringUtils.isEmpty(stringTag.name())){ + + addMethodMapping(defaultPrefix + method.getName(), method); + + }else{ + + addMethodMapping(defaultPrefix + stringTag.name(), method); + } + } + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSource.java b/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSource.java index a77870b1bd7..00ae6743e05 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSource.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSource.java @@ -16,79 +16,79 @@ public class BeanTagSource implements TagSource{ - private final T bean; - private final Set tagSet; - private final HashMap tagMethodMap; - private final HashMap tagFieldMap; + private final T bean; + private final Set tagSet; + private final HashMap tagMethodMap; + private final HashMap tagFieldMap; - public BeanTagSource(T bean, HashMap tagMethodMap, HashMap tagFieldMap, Set tagSet) { + public BeanTagSource(T bean, HashMap tagMethodMap, HashMap tagFieldMap, Set tagSet) { - super(); - this.bean = bean; - this.tagMethodMap = tagMethodMap; - this.tagFieldMap = tagFieldMap; - this.tagSet = tagSet; - } + super(); + this.bean = bean; + this.tagMethodMap = tagMethodMap; + this.tagFieldMap = tagFieldMap; + this.tagSet = tagSet; + } - public String getTagValue(String tag) { + public String getTagValue(String tag) { - Field field = this.tagFieldMap.get(tag); + Field field = this.tagFieldMap.get(tag); - if(field != null){ + if(field != null){ - try { - Object value = field.get(bean); + try { + Object value = field.get(bean); - if(value != null){ + if(value != null){ - return value.toString(); - } + return value.toString(); + } - return null; + return null; - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - Method method = tagMethodMap.get(tag); + Method method = tagMethodMap.get(tag); - if(method != null){ + if(method != null){ - try { - Object value = method.invoke(bean); + try { + Object value = method.invoke(bean); - if(value != null){ + if(value != null){ - return value.toString(); - } + return value.toString(); + } - return null; + return null; - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (InvocationTargetException e) { + } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - return null; - } + return null; + } - public Set getTags() { + public Set getTags() { - return this.tagSet; - } + return this.tagSet; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSourceFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSourceFactory.java index ffeb6f9db58..2412b257556 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSourceFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/BeanTagSourceFactory.java @@ -19,101 +19,101 @@ public class BeanTagSourceFactory implements TagSourceFactory{ - private Class beanClass; - private HashMap tagMethodMap = new HashMap(); - private HashMap tagFieldMap = new HashMap(); - private HashSet tagsSet = new HashSet(); + private Class beanClass; + private HashMap tagMethodMap = new HashMap(); + private HashMap tagFieldMap = new HashMap(); + private HashSet tagsSet = new HashSet(); - public BeanTagSourceFactory(Class beanClass) { + public BeanTagSourceFactory(Class beanClass) { - this.beanClass = beanClass; - } + this.beanClass = beanClass; + } - public void addMethodMapping(String tag, String methodName) throws NoSuchMethodException{ + public void addMethodMapping(String tag, String methodName) throws NoSuchMethodException{ - Method method = ReflectionUtils.getMethod(beanClass, methodName, Object.class); + Method method = ReflectionUtils.getMethod(beanClass, methodName, Object.class); - if(method == null){ + if(method == null){ - throw new NoSuchMethodException("Method " + methodName + " with no input parameters not found in " + beanClass); - } + throw new NoSuchMethodException("Method " + methodName + " with no input parameters not found in " + beanClass); + } - addMethodMapping(tag, method); - } + addMethodMapping(tag, method); + } - protected void addMethodMapping(String tag, Method method){ + protected void addMethodMapping(String tag, Method method){ - if(!method.isAccessible()){ + if(!method.isAccessible()){ - ReflectionUtils.fixMethodAccess(method); - } + ReflectionUtils.fixMethodAccess(method); + } - tagMethodMap.put(tag, method); - this.tagsSet.add(tag); - } + tagMethodMap.put(tag, method); + this.tagsSet.add(tag); + } - public void addFieldMapping(String tag, String fieldName) throws NoSuchFieldException{ + public void addFieldMapping(String tag, String fieldName) throws NoSuchFieldException{ - Field field = ReflectionUtils.getField(beanClass, fieldName); + Field field = ReflectionUtils.getField(beanClass, fieldName); - if(field == null){ + if(field == null){ - throw new NoSuchFieldException("Field " + fieldName + " not found in " + beanClass); - } + throw new NoSuchFieldException("Field " + fieldName + " not found in " + beanClass); + } - addFieldMapping(tag, field); - } + addFieldMapping(tag, field); + } - protected void addFieldMapping(String tag, Field field){ + protected void addFieldMapping(String tag, Field field){ - if(!field.isAccessible()){ + if(!field.isAccessible()){ - ReflectionUtils.fixFieldAccess(field); - } + ReflectionUtils.fixFieldAccess(field); + } - tagFieldMap.put(tag, field); - this.tagsSet.add(tag); - } + tagFieldMap.put(tag, field); + this.tagsSet.add(tag); + } - public void addAllFields(String fieldPrefix, String... excludedFields){ + public void addAllFields(String fieldPrefix, String... excludedFields){ - List exclusionList = null; + List exclusionList = null; - if(excludedFields != null){ + if(excludedFields != null){ - exclusionList = Arrays.asList(excludedFields); - } + exclusionList = Arrays.asList(excludedFields); + } - List fields = ReflectionUtils.getFields(beanClass); + List fields = ReflectionUtils.getFields(beanClass); - for(Field field : fields){ + for(Field field : fields){ - if(exclusionList == null || !exclusionList.contains(field.getName())){ + if(exclusionList == null || !exclusionList.contains(field.getName())){ - if(!field.isAccessible()){ + if(!field.isAccessible()){ - ReflectionUtils.fixFieldAccess(field); - } + ReflectionUtils.fixFieldAccess(field); + } - this.tagFieldMap.put(fieldPrefix + field.getName(), field); - this.tagsSet.add(fieldPrefix + field.getName()); - } - } - } + this.tagFieldMap.put(fieldPrefix + field.getName(), field); + this.tagsSet.add(fieldPrefix + field.getName()); + } + } + } - public BeanTagSource getTagSource(X bean){ + public BeanTagSource getTagSource(X bean){ - return new BeanTagSource(bean, tagMethodMap, tagFieldMap, tagsSet); - } + return new BeanTagSource(bean, tagMethodMap, tagFieldMap, tagsSet); + } - public HashSet getTagsSet() { - return new HashSet(tagsSet); - } + public HashSet getTagsSet() { + return new HashSet(tagsSet); + } - public String getAvailableTags(){ + public String getAvailableTags(){ - return StringUtils.toCommaSeparatedString(this.tagsSet); - } + return StringUtils.toCommaSeparatedString(this.tagsSet); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/DummyStringyfier.java b/eagledns/src/main/java/se/unlogic/standardutils/string/DummyStringyfier.java index 2b01b7f0819..dac20692400 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/DummyStringyfier.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/DummyStringyfier.java @@ -4,8 +4,8 @@ public final class DummyStringyfier implements Stringyfier { - public String format(Object bean) { + public String format(Object bean) { - throw new RuntimeException("This is a dummy class and this method should never be called!"); - } + throw new RuntimeException("This is a dummy class and this method should never be called!"); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/MapTagSource.java b/eagledns/src/main/java/se/unlogic/standardutils/string/MapTagSource.java index aae8c9333b8..eff60f65304 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/MapTagSource.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/MapTagSource.java @@ -6,31 +6,31 @@ public class MapTagSource implements TagSource { - protected HashMap tagMap; - - public MapTagSource(){ - - tagMap = new HashMap(); - } - - public MapTagSource(HashMap tagMap) { - - super(); - this.tagMap = tagMap; - } - - public void addTag(String tag, String value){ - - tagMap.put(tag, value); - } - - public Set getTags() { - - return tagMap.keySet(); - } - - public String getTagValue(String tag) { - - return tagMap.get(tag); - } + protected HashMap tagMap; + + public MapTagSource(){ + + tagMap = new HashMap(); + } + + public MapTagSource(HashMap tagMap) { + + super(); + this.tagMap = tagMap; + } + + public void addTag(String tag, String value){ + + tagMap.put(tag, value); + } + + public Set getTags() { + + return tagMap.keySet(); + } + + public String getTagValue(String tag) { + + return tagMap.get(tag); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSource.java b/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSource.java index 04fa4f46a8a..6b246e67f7f 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSource.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSource.java @@ -6,28 +6,28 @@ public class SingleTagSource implements TagSource { - protected Set tags; - protected String value; - - protected SingleTagSource(Set tags, String value) { - - this.tags = tags; - this.value = value; - } - - public SingleTagSource(String tag, String value){ - - this.tags = Collections.singleton(tag); - this.value = value; - } - - public Set getTags() { - - return tags; - } - - public String getTagValue(String tag) { - - return value; - } + protected Set tags; + protected String value; + + protected SingleTagSource(Set tags, String value) { + + this.tags = tags; + this.value = value; + } + + public SingleTagSource(String tag, String value){ + + this.tags = Collections.singleton(tag); + this.value = value; + } + + public Set getTags() { + + return tags; + } + + public String getTagValue(String tag) { + + return value; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSourceFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSourceFactory.java index e148a1876f5..7d99b214f1c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSourceFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/SingleTagSourceFactory.java @@ -6,27 +6,27 @@ public class SingleTagSourceFactory implements TagSourceFactory{ - protected Set tags; - protected String tag; - - public SingleTagSourceFactory(String tag){ - - this.tags = Collections.singleton(tag); - this.tag = tag; - } + protected Set tags; + protected String tag; - public TagSource getTagSource(X value) { + public SingleTagSourceFactory(String tag){ - return new SingleTagSource(tags, value.toString()); - } + this.tags = Collections.singleton(tag); + this.tag = tag; + } - public Set getTagsSet() { + public TagSource getTagSource(X value) { - return tags; - } + return new SingleTagSource(tags, value.toString()); + } - public String getAvailableTags() { + public Set getTagsSet() { - return tag; - } + return tags; + } + + public String getAvailableTags() { + + return tag; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/StringTag.java b/eagledns/src/main/java/se/unlogic/standardutils/string/StringTag.java index e34a91e420c..ed797d923f5 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/StringTag.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/StringTag.java @@ -10,6 +10,6 @@ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.METHOD}) public @interface StringTag { - String name() default ""; - //Class valueFormatter() default DummyStringyfier.class; + String name() default ""; + //Class valueFormatter() default DummyStringyfier.class; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/StringUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/string/StringUtils.java index 75ae020d04d..f15816dc6da 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/StringUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/StringUtils.java @@ -31,289 +31,289 @@ public class StringUtils { - private static Properties LATIN1_ESCAPE_CHARACTERS = null; - - static { - LATIN1_ESCAPE_CHARACTERS = new Properties(); - - InputStream inputStream = StringUtils.class.getResourceAsStream("latin-1-escaped-character-set.properties"); - - try { - LATIN1_ESCAPE_CHARACTERS.load(inputStream); - } catch (InvalidPropertiesFormatException e) { - throw new RuntimeException(e); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - StreamUtils.closeStream(inputStream); - } - } - - /** - * Unescapes escaped HTML characters - * - * Based on a fixed set of escaped HTML characters from the latin-1 set - * - * @param sequence - * - the secuence of characters to unescape characters in - * @return - a sequenced without escaped HTML characters - */ - public static String unEscapeHTML(String sequence) { + private static Properties LATIN1_ESCAPE_CHARACTERS = null; + + static { + LATIN1_ESCAPE_CHARACTERS = new Properties(); + + InputStream inputStream = StringUtils.class.getResourceAsStream("latin-1-escaped-character-set.properties"); + + try { + LATIN1_ESCAPE_CHARACTERS.load(inputStream); + } catch (InvalidPropertiesFormatException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + StreamUtils.closeStream(inputStream); + } + } + + /** + * Unescapes escaped HTML characters + * + * Based on a fixed set of escaped HTML characters from the latin-1 set + * + * @param sequence + * - the secuence of characters to unescape characters in + * @return - a sequenced without escaped HTML characters + */ + public static String unEscapeHTML(String sequence) { - return replaceCharacters(sequence, LATIN1_ESCAPE_CHARACTERS); - } + return replaceCharacters(sequence, LATIN1_ESCAPE_CHARACTERS); + } - /** - * Replaces characters in a character sequence - * - * @param sequence - * - the secuence of characters to replace characters in - * @param characterSet - * - a set of key=value character mappings, e.g. #=#. Occurences of key, e.g. "#" will be replaced by value, e.g. "#" - * - * @return - a sequenced with replaced characters - */ - public static String replaceCharacters(String sequence, Properties characterSet) { + /** + * Replaces characters in a character sequence + * + * @param sequence + * - the secuence of characters to replace characters in + * @param characterSet + * - a set of key=value character mappings, e.g. #=#. Occurences of key, e.g. "#" will be replaced by value, e.g. "#" + * + * @return - a sequenced with replaced characters + */ + public static String replaceCharacters(String sequence, Properties characterSet) { - if (characterSet == null) { - characterSet = LATIN1_ESCAPE_CHARACTERS; - } + if (characterSet == null) { + characterSet = LATIN1_ESCAPE_CHARACTERS; + } - for (Entry entry : characterSet.entrySet()) { - sequence = sequence.replaceAll(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); - } + for (Entry entry : characterSet.entrySet()) { + sequence = sequence.replaceAll(String.valueOf(entry.getKey()), String.valueOf(entry.getValue())); + } - return sequence; - } + return sequence; + } - public static String removeHTMLTags(String sequence) { - - return sequence.replaceAll("\\<.*?>", ""); - } - - public static String parseUTF8(String encodedString) { + public static String removeHTMLTags(String sequence) { + + return sequence.replaceAll("\\<.*?>", ""); + } + + public static String parseUTF8(String encodedString) { - return new String(encodedString.getBytes(), StandardCharsets.UTF_8); - } - - //TODO move - public static boolean isValidUUID(String uuidstring) { - - try { - UUID.fromString(uuidstring); - return true; - } catch (IllegalArgumentException e) { - return false; - } - } - - //TODO move - public static boolean isValidURL(String urlstring) { - - try { - new URL(urlstring); - return true; - } catch (MalformedURLException e) { - return false; - } - } - - public static String toQuotedCommaSeparatedString(List list) { - - String arrayString = Arrays.deepToString(list.toArray()); - arrayString = arrayString.substring(1, arrayString.length() - 1); - arrayString = "\"" + arrayString.replaceAll(", ", "\", \"") + "\""; - return arrayString; - } - - public static String toQuotedCommaSeparatedString(Object[] array) { - - String arrayString = Arrays.deepToString(array); - arrayString = arrayString.substring(1, arrayString.length() - 1); - arrayString = "\"" + arrayString.replaceAll(", ", "\", \"") + "\""; - return arrayString; - } - - public static String toCommaSeparatedString(Collection list) { + return new String(encodedString.getBytes(), StandardCharsets.UTF_8); + } + + //TODO move + public static boolean isValidUUID(String uuidstring) { + + try { + UUID.fromString(uuidstring); + return true; + } catch (IllegalArgumentException e) { + return false; + } + } + + //TODO move + public static boolean isValidURL(String urlstring) { + + try { + new URL(urlstring); + return true; + } catch (MalformedURLException e) { + return false; + } + } + + public static String toQuotedCommaSeparatedString(List list) { + + String arrayString = Arrays.deepToString(list.toArray()); + arrayString = arrayString.substring(1, arrayString.length() - 1); + arrayString = "\"" + arrayString.replaceAll(", ", "\", \"") + "\""; + return arrayString; + } + + public static String toQuotedCommaSeparatedString(Object[] array) { + + String arrayString = Arrays.deepToString(array); + arrayString = arrayString.substring(1, arrayString.length() - 1); + arrayString = "\"" + arrayString.replaceAll(", ", "\", \"") + "\""; + return arrayString; + } + + public static String toCommaSeparatedString(Collection list) { - String arrayString = Arrays.deepToString(list.toArray()); - return arrayString.substring(1, arrayString.length() - 1); - } + String arrayString = Arrays.deepToString(list.toArray()); + return arrayString.substring(1, arrayString.length() - 1); + } - public static String toCommaSeparatedString(Object[] array) { + public static String toCommaSeparatedString(Object[] array) { - String arrayString = Arrays.deepToString(array); - return arrayString.substring(1, arrayString.length() - 1); - } + String arrayString = Arrays.deepToString(array); + return arrayString.substring(1, arrayString.length() - 1); + } - public static String toCommaSeparatedString(List list, Field field) throws IllegalArgumentException, IllegalAccessException { + public static String toCommaSeparatedString(List list, Field field) throws IllegalArgumentException, IllegalAccessException { - ReflectionUtils.fixFieldAccess(field); + ReflectionUtils.fixFieldAccess(field); - StringBuilder arrayString = new StringBuilder(); + StringBuilder arrayString = new StringBuilder(); - for (int i = 0; i < list.size(); i++) { + for (int i = 0; i < list.size(); i++) { - Object value = field.get(list.get(i)); + Object value = field.get(list.get(i)); - arrayString.append(value + ","); + arrayString.append(value + ","); - } + } - return arrayString.substring(0, arrayString.length() - 1); + return arrayString.substring(0, arrayString.length() - 1); - } + } - public static String readFileAsString(String filePath) throws java.io.IOException { + public static String readFileAsString(String filePath) throws java.io.IOException { - StringBuffer fileData = new StringBuffer(1000); - BufferedReader reader = new BufferedReader(new FileReader(filePath)); - char[] buf = new char[1024]; - int numRead = 0; - while ((numRead = reader.read(buf)) != -1) { - fileData.append(buf, 0, numRead); - } - reader.close(); - return fileData.toString(); - } + StringBuffer fileData = new StringBuffer(1000); + BufferedReader reader = new BufferedReader(new FileReader(filePath)); + char[] buf = new char[1024]; + int numRead = 0; + while ((numRead = reader.read(buf)) != -1) { + fileData.append(buf, 0, numRead); + } + reader.close(); + return fileData.toString(); + } - public static String readFileAsString(File file) throws java.io.IOException { + public static String readFileAsString(File file) throws java.io.IOException { - StringBuffer fileData = new StringBuffer(1000); - BufferedReader reader = new BufferedReader(new FileReader(file)); - char[] buf = new char[1024]; - int numRead = 0; - while ((numRead = reader.read(buf)) != -1) { - fileData.append(buf, 0, numRead); - } - reader.close(); - return fileData.toString(); - } + StringBuffer fileData = new StringBuffer(1000); + BufferedReader reader = new BufferedReader(new FileReader(file)); + char[] buf = new char[1024]; + int numRead = 0; + while ((numRead = reader.read(buf)) != -1) { + fileData.append(buf, 0, numRead); + } + reader.close(); + return fileData.toString(); + } - public static String readStreamAsString(InputStream inputStream) throws java.io.IOException { + public static String readStreamAsString(InputStream inputStream) throws java.io.IOException { - StringBuilder fileData = new StringBuilder(1000); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - char[] buf = new char[1024]; - int numRead = 0; - while ((numRead = reader.read(buf)) != -1) { - fileData.append(buf, 0, numRead); - } - reader.close(); - return fileData.toString(); - } + StringBuilder fileData = new StringBuilder(1000); + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + char[] buf = new char[1024]; + int numRead = 0; + while ((numRead = reader.read(buf)) != -1) { + fileData.append(buf, 0, numRead); + } + reader.close(); + return fileData.toString(); + } - public static boolean isEmpty(String string) { + public static boolean isEmpty(String string) { - if (string == null) { - return true; - } else if (string.trim().length() == 0) { - return true; - } else { - return false; - } - } + if (string == null) { + return true; + } else if (string.trim().length() == 0) { + return true; + } else { + return false; + } + } - public static String substring(String string, int maxChars, String suffix) { + public static String substring(String string, int maxChars, String suffix) { - if (string.length() > maxChars) { - return string.substring(0, maxChars - 1) + suffix; - } + if (string.length() > maxChars) { + return string.substring(0, maxChars - 1) + suffix; + } - return string; - } + return string; + } - public static String toLogFormat(String string, int maxLength) { + public static String toLogFormat(String string, int maxLength) { - if (string != null) { + if (string != null) { - String returnString = substring(string, maxLength, "..."); + String returnString = substring(string, maxLength, "..."); - return returnString.replace("\n", " ").replace("\r", " ").replace("\t", " "); - } + return returnString.replace("\n", " ").replace("\r", " ").replace("\t", " "); + } - return string; - } + return string; + } - public static String toSentenceCase(String string) { + public static String toSentenceCase(String string) { - return string.substring(0, 1).toUpperCase() + string.toLowerCase().substring(1); - } + return string.substring(0, 1).toUpperCase() + string.toLowerCase().substring(1); + } - public static String toFirstLetterUppercase(String string) { + public static String toFirstLetterUppercase(String string) { - return string.substring(0, 1).toUpperCase() + string.substring(1); - } + return string.substring(0, 1).toUpperCase() + string.substring(1); + } - public static String toFirstLetterLowercase(String string) { + public static String toFirstLetterLowercase(String string) { - return string.substring(0, 1).toLowerCase() + string.substring(1); - } - - public static String repeatString(String string, int repetitionCount) { + return string.substring(0, 1).toLowerCase() + string.substring(1); + } - StringBuilder stringBuilder = new StringBuilder(); + public static String repeatString(String string, int repetitionCount) { - repeatString(string, repetitionCount, stringBuilder); - - return stringBuilder.toString(); - } + StringBuilder stringBuilder = new StringBuilder(); - public static void repeatString(String string, int repetitionCount, StringBuilder stringBuilder) { - - if (repetitionCount >= 1) { - - for (int i = 1; i <= repetitionCount; i++) { - - stringBuilder.append(string); - } - } - } - - /** - * Takes a string and splits it on linebreaks (\n) and also removes any linebreak (\n) and carriage return (\r) characters from the string segments - * - * @param string the string to be split - * @return String array containing the split segments of the string - */ - public static ArrayList splitOnLineBreak(String string, boolean removeDuplicates){ - - if(!StringUtils.isEmpty(string)){ - - ArrayList stringList = new ArrayList(); + repeatString(string, repetitionCount, stringBuilder); - String[] lines = string.split("\n"); + return stringBuilder.toString(); + } - for(String line : lines){ + public static void repeatString(String string, int repetitionCount, StringBuilder stringBuilder) { - line = line.replace("\n", ""); - line = line.replace("\r", ""); + if (repetitionCount >= 1) { - if(!StringUtils.isEmpty(line) && (!removeDuplicates || !stringList.contains(line))){ + for (int i = 1; i <= repetitionCount; i++) { - stringList.add(line); - } - } + stringBuilder.append(string); + } + } + } - if(!stringList.isEmpty()){ + /** + * Takes a string and splits it on linebreaks (\n) and also removes any linebreak (\n) and carriage return (\r) characters from the string segments + * + * @param string the string to be split + * @return String array containing the split segments of the string + */ + public static ArrayList splitOnLineBreak(String string, boolean removeDuplicates){ - return stringList; - } - } + if(!StringUtils.isEmpty(string)){ - return null; - } - - public static int countOccurrences(String string, String snippet) { - - int count = 0; - int index = 0; - - while ((index = string.indexOf(snippet, index)) != -1) { - ++index; - ++count; - } - - return count; - } + ArrayList stringList = new ArrayList(); + + String[] lines = string.split("\n"); + + for(String line : lines){ + + line = line.replace("\n", ""); + line = line.replace("\r", ""); + + if(!StringUtils.isEmpty(line) && (!removeDuplicates || !stringList.contains(line))){ + + stringList.add(line); + } + } + + if(!stringList.isEmpty()){ + + return stringList; + } + } + + return null; + } + + public static int countOccurrences(String string, String snippet) { + + int count = 0; + int index = 0; + + while ((index = string.indexOf(snippet, index)) != -1) { + ++index; + ++count; + } + + return count; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/Stringyfier.java b/eagledns/src/main/java/se/unlogic/standardutils/string/Stringyfier.java index 9d3ed28c175..1a0408c2516 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/Stringyfier.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/Stringyfier.java @@ -3,5 +3,5 @@ public interface Stringyfier { - String format(Object bean); + String format(Object bean); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/TagReplacer.java b/eagledns/src/main/java/se/unlogic/standardutils/string/TagReplacer.java index 68e5dca0c99..96fccd2e2d0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/TagReplacer.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/TagReplacer.java @@ -14,63 +14,63 @@ public class TagReplacer { - private List tagSources; + private List tagSources; - public TagReplacer() { - - tagSources = new ArrayList(); - } + public TagReplacer() { - public TagReplacer(List tagSources) { - super(); - this.tagSources = new ArrayList(tagSources); - } + tagSources = new ArrayList(); + } - public TagReplacer(TagSource... tagSources) { - super(); - this.tagSources = new ArrayList(Arrays.asList(tagSources)); - } + public TagReplacer(List tagSources) { + super(); + this.tagSources = new ArrayList(tagSources); + } - public boolean addTagSource(TagSource o) { + public TagReplacer(TagSource... tagSources) { + super(); + this.tagSources = new ArrayList(Arrays.asList(tagSources)); + } - if(tagSources == null){ - - tagSources = new ArrayList(); - } - - return tagSources.add(o); - } + public boolean addTagSource(TagSource o) { - public boolean removeTagSource(TagSource o) { + if(tagSources == null){ - if(tagSources == null){ - - return false; - } - - return tagSources.remove(o); - } + tagSources = new ArrayList(); + } - public String replace(String source){ + return tagSources.add(o); + } - for(TagSource tagSource : tagSources){ + public boolean removeTagSource(TagSource o) { - for(String tag : tagSource.getTags()){ + if(tagSources == null){ - if(source.contains(tag)){ + return false; + } - String value = tagSource.getTagValue(tag); + return tagSources.remove(o); + } - if(value == null){ + public String replace(String source){ - value = ""; - } + for(TagSource tagSource : tagSources){ - source = source.replace(tag, value); - } - } - } + for(String tag : tagSource.getTags()){ - return source; - } + if(source.contains(tag)){ + + String value = tagSource.getTagValue(tag); + + if(value == null){ + + value = ""; + } + + source = source.replace(tag, value); + } + } + } + + return source; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/TagSource.java b/eagledns/src/main/java/se/unlogic/standardutils/string/TagSource.java index 03d3ab01697..ea1caf87d1d 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/TagSource.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/TagSource.java @@ -12,7 +12,7 @@ public interface TagSource { - Set getTags(); - - String getTagValue(String tag); + Set getTags(); + + String getTagValue(String tag); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/string/TagSourceFactory.java b/eagledns/src/main/java/se/unlogic/standardutils/string/TagSourceFactory.java index c1f1bd0aa25..e7bc55823a1 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/string/TagSourceFactory.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/string/TagSourceFactory.java @@ -4,12 +4,12 @@ public interface TagSourceFactory { - TagSource getTagSource(X bean); + TagSource getTagSource(X bean); - Set getTagsSet(); + Set getTagsSet(); - /** - * @return a comma separated {@link String} of all available tags - */ - String getAvailableTags(); + /** + * @return a comma separated {@link String} of all available tags + */ + String getAvailableTags(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/ExecutionController.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/ExecutionController.java index e430d17332d..d1f2b72c83c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/ExecutionController.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/ExecutionController.java @@ -12,21 +12,21 @@ public interface ExecutionController { - void start() throws RejectedExecutionException; - - void abort(); - - int getRemainingTaskCount(); - - void awaitExecution() throws InterruptedException; - - void awaitExecution(long timeout) throws InterruptedException; - - boolean isStarted(); - - boolean isAborted(); - - boolean isFinished(); - - Task getTaskGroup(); + void start() throws RejectedExecutionException; + + void abort(); + + int getRemainingTaskCount(); + + void awaitExecution() throws InterruptedException; + + void awaitExecution(long timeout) throws InterruptedException; + + boolean isStarted(); + + boolean isAborted(); + + boolean isFinished(); + + Task getTaskGroup(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/ExtendedThreadPoolExecutor.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/ExtendedThreadPoolExecutor.java index 3d6afcef8d7..5096d7c072a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/ExtendedThreadPoolExecutor.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/ExtendedThreadPoolExecutor.java @@ -18,84 +18,84 @@ public class ExtendedThreadPoolExecutor extends ThreadPoolExecutor { - private boolean isPaused; - private final ReentrantLock pauseLock = new ReentrantLock(); - private final Condition unpaused = pauseLock.newCondition(); - private final ConcurrentLinkedQueue listeners = new ConcurrentLinkedQueue(); - - public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); - } - - public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); - } - - public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); - } - - public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); - } - - @Override - protected void beforeExecute(Thread t, Runnable r) { - super.beforeExecute(t, r); - pauseLock.lock(); - try { - while (isPaused) { - unpaused.await(); - } - } catch (InterruptedException ie) { - t.interrupt(); - } finally { - pauseLock.unlock(); - } - - for(ThreadPoolListener listerner : this.listeners){ - - listerner.beforeExecute(t,r); - } - } - - public void pause() { - pauseLock.lock(); - try { - isPaused = true; - } finally { - pauseLock.unlock(); - } - } - - public void resume() { - pauseLock.lock(); - try { - isPaused = false; - unpaused.signalAll(); - } finally { - pauseLock.unlock(); - } - } - - @Override - protected void afterExecute(Runnable r, Throwable t) { - - super.afterExecute(r, t); - - for(ThreadPoolListener listerner : this.listeners){ - - listerner.afterExecute(t,r); - } - } - - public boolean addListener(ThreadPoolListener listener) { - - return listeners.add(listener); - } - - public boolean remove(ThreadPoolListener listener) { - - return listeners.remove(listener); - } + private boolean isPaused; + private final ReentrantLock pauseLock = new ReentrantLock(); + private final Condition unpaused = pauseLock.newCondition(); + private final ConcurrentLinkedQueue listeners = new ConcurrentLinkedQueue(); + + public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, RejectedExecutionHandler handler) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); + } + + public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); + } + + public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue, ThreadFactory threadFactory) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); + } + + public ExtendedThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); + } + + @Override + protected void beforeExecute(Thread t, Runnable r) { + super.beforeExecute(t, r); + pauseLock.lock(); + try { + while (isPaused) { + unpaused.await(); + } + } catch (InterruptedException ie) { + t.interrupt(); + } finally { + pauseLock.unlock(); + } + + for(ThreadPoolListener listerner : this.listeners){ + + listerner.beforeExecute(t,r); + } + } + + public void pause() { + pauseLock.lock(); + try { + isPaused = true; + } finally { + pauseLock.unlock(); + } + } + + public void resume() { + pauseLock.lock(); + try { + isPaused = false; + unpaused.signalAll(); + } finally { + pauseLock.unlock(); + } + } + + @Override + protected void afterExecute(Runnable r, Throwable t) { + + super.afterExecute(r, t); + + for(ThreadPoolListener listerner : this.listeners){ + + listerner.afterExecute(t,r); + } + } + + public boolean addListener(ThreadPoolListener listener) { + + return listeners.add(listener); + } + + public boolean remove(ThreadPoolListener listener) { + + return listeners.remove(listener); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKey.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKey.java index f1b71d020a1..8aa99440c38 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKey.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKey.java @@ -9,45 +9,45 @@ public class MutexKey { - private final T value; + private final T value; - public MutexKey(T value) { - super(); - this.value = value; - } + public MutexKey(T value) { + super(); + this.value = value; + } - public T getValue() { - return value; - } + public T getValue() { + return value; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((value == null) ? 0 : value.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } - MutexKey other = (MutexKey) obj; - if (value == null) { - if (other.value != null) { - return false; - } - } else if (!value.equals(other.value)) { - return false; - } - return true; - } + MutexKey other = (MutexKey) obj; + if (value == null) { + if (other.value != null) { + return false; + } + } else if (!value.equals(other.value)) { + return false; + } + return true; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKeyProvider.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKeyProvider.java index 6ea4e19c3e3..7d84915ff39 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKeyProvider.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/MutexKeyProvider.java @@ -12,37 +12,37 @@ public class MutexKeyProvider { - private final WeakHashMap, WeakReference>> keyMap = new WeakHashMap, WeakReference>>(); + private final WeakHashMap, WeakReference>> keyMap = new WeakHashMap, WeakReference>>(); - public MutexKey getKey(T object) { + public MutexKey getKey(T object) { - MutexKey newKey = new MutexKey(object); + MutexKey newKey = new MutexKey(object); - synchronized (keyMap) { + synchronized (keyMap) { - WeakReference> reference = keyMap.get(newKey); + WeakReference> reference = keyMap.get(newKey); - if (reference == null) { - return this.addKey(newKey); - } + if (reference == null) { + return this.addKey(newKey); + } - MutexKey currentKey = reference.get(); + MutexKey currentKey = reference.get(); - if (currentKey == null) { - return this.addKey(newKey); - } + if (currentKey == null) { + return this.addKey(newKey); + } - // System.out.println("Returning cached instance of key " + currentKey.getValue() + "[" + this.keyMap.size() + "]"); + // System.out.println("Returning cached instance of key " + currentKey.getValue() + "[" + this.keyMap.size() + "]"); - return currentKey; - } - } + return currentKey; + } + } - private MutexKey addKey(MutexKey key) { + private MutexKey addKey(MutexKey key) { - // System.out.println("\n[mutex] adding id " + key.getValue() + " to mutex map [" + this.keyMap.size() + "]\n"); + // System.out.println("\n[mutex] adding id " + key.getValue() + " to mutex map [" + this.keyMap.size() + "]\n"); - this.keyMap.put(key, new WeakReference>(key)); - return key; - } + this.keyMap.put(key, new WeakReference>(key)); + return key; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleExecutionController.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleExecutionController.java index d74ad2d38fe..18fb6398649 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleExecutionController.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleExecutionController.java @@ -23,182 +23,182 @@ @XMLElement(name="ExecutionController") public class SimpleExecutionController implements ExecutionController, Elementable{ - private final ReentrantLock globalLock = new ReentrantLock(); - private Condition finishedCondition = globalLock.newCondition(); - - private T taskGroup; - - private BlockingQueue taskQueue; - private ThreadPoolTaskGroupHandler threadPoolTaskHandler; - - @XMLAttribute - private boolean started; - - @XMLAttribute - private boolean aborted; - - @XMLAttribute - private int initialTaskCount; - - @XMLAttribute - private AtomicInteger completedTaskCount = new AtomicInteger(); - - public SimpleExecutionController(T taskGroup, ThreadPoolTaskGroupHandler threadPoolTaskHandler) { - - super(); - this.taskGroup = taskGroup; - this.taskQueue = taskGroup.getTasks(); - this.threadPoolTaskHandler = threadPoolTaskHandler; - initialTaskCount = taskQueue.size(); - } - - public void abort() { - - globalLock.lock(); - - try{ - - if(this.threadPoolTaskHandler != null){ - - if(started){ - threadPoolTaskHandler.remove(this); - } - - this.aborted = true; - - this.executionComplete(); - } - - }finally{ - - globalLock.unlock(); - } - } - - public void awaitExecution(long timeout) throws InterruptedException { - - globalLock.lock(); - - try{ - - if(finishedCondition != null){ - - finishedCondition.await(timeout, TimeUnit.MILLISECONDS); - } - - }finally{ - - globalLock.unlock(); - } - - } - - public void awaitExecution() throws InterruptedException { - - globalLock.lock(); - - try{ - - if(finishedCondition != null){ - - finishedCondition.await(); - } - - }finally{ - - globalLock.unlock(); - } - - } - - void executionComplete(){ - - globalLock.lock(); - - try{ - - if(finishedCondition != null){ - - finishedCondition.signalAll(); - - threadPoolTaskHandler = null; - finishedCondition = null; - } - - }finally{ - - globalLock.unlock(); - } - } - - public int getRemainingTaskCount() { - - return taskQueue.size(); - } - - - BlockingQueue getTaskQueue() { - - return taskQueue; - } - - public void start() { - - globalLock.lock(); - - try{ - if(!started && !aborted){ - - this.threadPoolTaskHandler.add(this); - this.started = true; - } - - }finally{ - - globalLock.unlock(); - } - } - - - public int getInitialTaskCount() { - - return initialTaskCount; - } - - - public int getCompletedTaskCount() { - - return completedTaskCount.get(); - } - - void incrementCompletedTaskCount(){ - - this.completedTaskCount.incrementAndGet(); - } - - public boolean isStarted(){ - - return started; - } - - public boolean isAborted(){ - - return aborted; - } - - public boolean isFinished(){ - - return started && !aborted && this.threadPoolTaskHandler == null; - } - - - public T getTaskGroup() { - - return taskGroup; - } - - public Element toXML(Document doc) { - - return XMLGenerator.toXML(this, doc); - } + private final ReentrantLock globalLock = new ReentrantLock(); + private Condition finishedCondition = globalLock.newCondition(); + + private T taskGroup; + + private BlockingQueue taskQueue; + private ThreadPoolTaskGroupHandler threadPoolTaskHandler; + + @XMLAttribute + private boolean started; + + @XMLAttribute + private boolean aborted; + + @XMLAttribute + private int initialTaskCount; + + @XMLAttribute + private AtomicInteger completedTaskCount = new AtomicInteger(); + + public SimpleExecutionController(T taskGroup, ThreadPoolTaskGroupHandler threadPoolTaskHandler) { + + super(); + this.taskGroup = taskGroup; + this.taskQueue = taskGroup.getTasks(); + this.threadPoolTaskHandler = threadPoolTaskHandler; + initialTaskCount = taskQueue.size(); + } + + public void abort() { + + globalLock.lock(); + + try{ + + if(this.threadPoolTaskHandler != null){ + + if(started){ + threadPoolTaskHandler.remove(this); + } + + this.aborted = true; + + this.executionComplete(); + } + + }finally{ + + globalLock.unlock(); + } + } + + public void awaitExecution(long timeout) throws InterruptedException { + + globalLock.lock(); + + try{ + + if(finishedCondition != null){ + + finishedCondition.await(timeout, TimeUnit.MILLISECONDS); + } + + }finally{ + + globalLock.unlock(); + } + + } + + public void awaitExecution() throws InterruptedException { + + globalLock.lock(); + + try{ + + if(finishedCondition != null){ + + finishedCondition.await(); + } + + }finally{ + + globalLock.unlock(); + } + + } + + void executionComplete(){ + + globalLock.lock(); + + try{ + + if(finishedCondition != null){ + + finishedCondition.signalAll(); + + threadPoolTaskHandler = null; + finishedCondition = null; + } + + }finally{ + + globalLock.unlock(); + } + } + + public int getRemainingTaskCount() { + + return taskQueue.size(); + } + + + BlockingQueue getTaskQueue() { + + return taskQueue; + } + + public void start() { + + globalLock.lock(); + + try{ + if(!started && !aborted){ + + this.threadPoolTaskHandler.add(this); + this.started = true; + } + + }finally{ + + globalLock.unlock(); + } + } + + + public int getInitialTaskCount() { + + return initialTaskCount; + } + + + public int getCompletedTaskCount() { + + return completedTaskCount.get(); + } + + void incrementCompletedTaskCount(){ + + this.completedTaskCount.incrementAndGet(); + } + + public boolean isStarted(){ + + return started; + } + + public boolean isAborted(){ + + return aborted; + } + + public boolean isFinished(){ + + return started && !aborted && this.threadPoolTaskHandler == null; + } + + + public T getTaskGroup() { + + return taskGroup; + } + + public Element toXML(Document doc) { + + return XMLGenerator.toXML(this, doc); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleTaskGroup.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleTaskGroup.java index 641ac74692b..2cc8c1b738a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleTaskGroup.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/SimpleTaskGroup.java @@ -12,15 +12,15 @@ public class SimpleTaskGroup implements TaskGroup { - private BlockingQueue queue; - - public SimpleTaskGroup(BlockingQueue queue) { - - this.queue = queue; - } - - public BlockingQueue getTasks() { - - return queue; - } + private BlockingQueue queue; + + public SimpleTaskGroup(BlockingQueue queue) { + + this.queue = queue; + } + + public BlockingQueue getTasks() { + + return queue; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/Status.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/Status.java index 1c65afa6fe1..ee0818f6201 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/Status.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/Status.java @@ -10,7 +10,7 @@ public enum Status { - RUNNING, - TERMINATING, - SHUTDOWN + RUNNING, + TERMINATING, + SHUTDOWN } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroup.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroup.java index fe812a5b761..6c3e8f1e783 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroup.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroup.java @@ -12,5 +12,5 @@ public interface TaskGroup { - BlockingQueue getTasks(); + BlockingQueue getTasks(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroupHandler.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroupHandler.java index 526abf145de..62882007742 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroupHandler.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/TaskGroupHandler.java @@ -13,23 +13,23 @@ public interface TaskGroupHandler> { - Controller execute(Task taskGroup) throws RejectedExecutionException; - - int getTotalTaskCount(); - - int getTaskGroupCount(); - - void abortAllTaskGroups(); - - List getTaskGroups(); - - Status getStatus(); - - void awaitTermination(long timeout) throws InterruptedException; - - void awaitTermination() throws InterruptedException; - - void shutdown(); - - void shutdownNow(); + Controller execute(Task taskGroup) throws RejectedExecutionException; + + int getTotalTaskCount(); + + int getTaskGroupCount(); + + void abortAllTaskGroups(); + + List getTaskGroups(); + + Status getStatus(); + + void awaitTermination(long timeout) throws InterruptedException; + + void awaitTermination() throws InterruptedException; + + void shutdown(); + + void shutdownNow(); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolListener.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolListener.java index 3ff836ca93a..5304e27e7ae 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolListener.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolListener.java @@ -10,8 +10,8 @@ public interface ThreadPoolListener { - void beforeExecute(Thread t, Runnable r); + void beforeExecute(Thread t, Runnable r); - void afterExecute(Throwable t, Runnable r); + void afterExecute(Throwable t, Runnable r); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolTaskGroupHandler.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolTaskGroupHandler.java index 05b1009db22..180a2075056 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolTaskGroupHandler.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadPoolTaskGroupHandler.java @@ -21,316 +21,316 @@ public class ThreadPoolTaskGroupHandler implements TaskGroupHandler>, Runnable{ - protected final ReentrantLock taskGroupRemoveLock = new ReentrantLock(); - protected final Condition taskGroupRemoveCondition = taskGroupRemoveLock.newCondition(); - - protected final ReentrantLock taskGroupAddLock = new ReentrantLock(); - protected final Condition taskGroupAddCondition = taskGroupAddLock.newCondition(); - - protected final CopyOnWriteArrayList> taskGroupList = new CopyOnWriteArrayList>(); - - protected int taskGroupIndex = 0; - - protected Status status = Status.RUNNING; - - protected final ArrayList threads = new ArrayList(); - - private final static Logger logger = Logger.getLogger(ThreadPoolTaskGroupHandler.class); - - public ThreadPoolTaskGroupHandler(int poolSize, boolean daemon){ - - while(threads.size() < poolSize){ - - Thread thread = new Thread(this, "TaskGroupHandler thread " + (threads.size() + 1)); - thread.setDaemon(daemon); - - threads.add(thread); - - thread.start(); - } - } - - public void run() { - - Runnable task = null; - - while(true){ - - while(!taskGroupList.isEmpty() && status != Status.SHUTDOWN){ - - SimpleExecutionController executionController; - - try { - executionController = this.taskGroupList.get(this.getIndex()); - - } catch (IndexOutOfBoundsException e) { - - continue; - } - - task = executionController.getTaskQueue().poll(); - - if(task == null){ - - taskGroupRemoveLock.lock(); - - try{ - - if(executionController.getInitialTaskCount() == executionController.getCompletedTaskCount() && this.taskGroupList.contains(executionController)){ - - this.taskGroupList.remove(executionController); - this.taskGroupRemoveCondition.signalAll(); - executionController.executionComplete(); - - }else{ - - break; - } - - }finally{ - - taskGroupRemoveLock.unlock(); - } - - }else{ - - try{ - task.run(); - - }catch(Throwable e){ - - logger.error(e.getMessage(), e); - - }finally{ - - executionController.incrementCompletedTaskCount(); - } - } - } - - taskGroupAddLock.lock(); - - try{ - if(status == Status.TERMINATING){ - - //Last thread sets shutdown status - if(getLiveThreads() == 1){ - - status = Status.SHUTDOWN; - } - - return; - } - - if(this.isEmpty()){ - - taskGroupAddCondition.await(); - } - - } catch (InterruptedException e) { - - }finally{ - taskGroupAddLock.unlock(); - } - } - } - - public boolean isEmpty() { - - if(this.taskGroupList.isEmpty()){ - return true; - } - - for(SimpleExecutionController controller : this.taskGroupList){ - - if(!controller.getTaskQueue().isEmpty()){ - - return false; - } - } - - return true; - } - - public int getLiveThreads(){ - - int activeThreadCount = 0; - - for(Thread thread : threads){ - - if(thread.isAlive()){ - - activeThreadCount++; - } - } - - return activeThreadCount; - } - - protected synchronized int getIndex() { - - taskGroupIndex++; - - if(taskGroupIndex >= taskGroupList.size()){ - - taskGroupIndex = 0; - } - - return taskGroupIndex; - } - - void remove(SimpleExecutionController executionController){ - - taskGroupRemoveLock.lock(); - - try{ - - this.taskGroupList.remove(executionController); - this.taskGroupRemoveCondition.signalAll(); - - }finally{ - - taskGroupRemoveLock.unlock(); - } - } - - void add(SimpleExecutionController executionController){ - - taskGroupAddLock.lock(); - - try{ - - if(status == Status.RUNNING){ - - this.taskGroupList.add(executionController); - taskGroupAddCondition.signalAll(); - - }else{ - - throw new RejectedExecutionException("TaskGroupHandler status " + status); - } - - }finally{ - - taskGroupAddLock.unlock(); - } - } - - public void abortAllTaskGroups() { - - taskGroupRemoveLock.lock(); - - try{ - - while(!this.taskGroupList.isEmpty()){ - - for(SimpleExecutionController executionController : taskGroupList){ - - executionController.abort(); - } - } - - }finally{ - - taskGroupRemoveLock.unlock(); - } - - } - - public SimpleExecutionController execute(T taskGroup) throws RejectedExecutionException{ - - if(status == Status.RUNNING){ - - return new SimpleExecutionController(taskGroup, this); - - }else{ - - throw new RejectedExecutionException("TaskGroupHandler status " + status); - } - } - - public int getTaskGroupCount() { - - return this.taskGroupList.size(); - } - - public List> getTaskGroups() { - - return new ArrayList>(this.taskGroupList); - } - - public int getTotalTaskCount() { - - int taskCount = 0; - - for(SimpleExecutionController executionController : taskGroupList){ - - taskCount += executionController.getTaskQueue().size(); - } - - return taskCount; - } - - public Status getStatus(){ - - return this.status; - } - - public void awaitTermination() throws InterruptedException { - - taskGroupRemoveLock.lock(); - - try{ - - while(!this.taskGroupList.isEmpty()){ - - taskGroupRemoveCondition.await(); - } - - }finally{ - - taskGroupRemoveLock.unlock(); - } - } - - public void awaitTermination(long timeout) throws InterruptedException { - - taskGroupRemoveLock.lock(); - - try{ - - while(!this.taskGroupList.isEmpty()){ - - taskGroupRemoveCondition.await(timeout,TimeUnit.MILLISECONDS); - } - - }finally{ - - taskGroupRemoveLock.unlock(); - } - } - - public void shutdown() { - - taskGroupAddLock.lock(); - - try{ - - if(this.status == Status.RUNNING){ - - this.status = Status.TERMINATING; - this.taskGroupAddCondition.signalAll(); - } - - }finally{ - - taskGroupAddLock.unlock(); - } - } - - public void shutdownNow() { - - this.shutdown(); - this.abortAllTaskGroups(); - } + protected final ReentrantLock taskGroupRemoveLock = new ReentrantLock(); + protected final Condition taskGroupRemoveCondition = taskGroupRemoveLock.newCondition(); + + protected final ReentrantLock taskGroupAddLock = new ReentrantLock(); + protected final Condition taskGroupAddCondition = taskGroupAddLock.newCondition(); + + protected final CopyOnWriteArrayList> taskGroupList = new CopyOnWriteArrayList>(); + + protected int taskGroupIndex = 0; + + protected Status status = Status.RUNNING; + + protected final ArrayList threads = new ArrayList(); + + private final static Logger logger = Logger.getLogger(ThreadPoolTaskGroupHandler.class); + + public ThreadPoolTaskGroupHandler(int poolSize, boolean daemon){ + + while(threads.size() < poolSize){ + + Thread thread = new Thread(this, "TaskGroupHandler thread " + (threads.size() + 1)); + thread.setDaemon(daemon); + + threads.add(thread); + + thread.start(); + } + } + + public void run() { + + Runnable task = null; + + while(true){ + + while(!taskGroupList.isEmpty() && status != Status.SHUTDOWN){ + + SimpleExecutionController executionController; + + try { + executionController = this.taskGroupList.get(this.getIndex()); + + } catch (IndexOutOfBoundsException e) { + + continue; + } + + task = executionController.getTaskQueue().poll(); + + if(task == null){ + + taskGroupRemoveLock.lock(); + + try{ + + if(executionController.getInitialTaskCount() == executionController.getCompletedTaskCount() && this.taskGroupList.contains(executionController)){ + + this.taskGroupList.remove(executionController); + this.taskGroupRemoveCondition.signalAll(); + executionController.executionComplete(); + + }else{ + + break; + } + + }finally{ + + taskGroupRemoveLock.unlock(); + } + + }else{ + + try{ + task.run(); + + }catch(Throwable e){ + + logger.error(e.getMessage(), e); + + }finally{ + + executionController.incrementCompletedTaskCount(); + } + } + } + + taskGroupAddLock.lock(); + + try{ + if(status == Status.TERMINATING){ + + //Last thread sets shutdown status + if(getLiveThreads() == 1){ + + status = Status.SHUTDOWN; + } + + return; + } + + if(this.isEmpty()){ + + taskGroupAddCondition.await(); + } + + } catch (InterruptedException e) { + + }finally{ + taskGroupAddLock.unlock(); + } + } + } + + public boolean isEmpty() { + + if(this.taskGroupList.isEmpty()){ + return true; + } + + for(SimpleExecutionController controller : this.taskGroupList){ + + if(!controller.getTaskQueue().isEmpty()){ + + return false; + } + } + + return true; + } + + public int getLiveThreads(){ + + int activeThreadCount = 0; + + for(Thread thread : threads){ + + if(thread.isAlive()){ + + activeThreadCount++; + } + } + + return activeThreadCount; + } + + protected synchronized int getIndex() { + + taskGroupIndex++; + + if(taskGroupIndex >= taskGroupList.size()){ + + taskGroupIndex = 0; + } + + return taskGroupIndex; + } + + void remove(SimpleExecutionController executionController){ + + taskGroupRemoveLock.lock(); + + try{ + + this.taskGroupList.remove(executionController); + this.taskGroupRemoveCondition.signalAll(); + + }finally{ + + taskGroupRemoveLock.unlock(); + } + } + + void add(SimpleExecutionController executionController){ + + taskGroupAddLock.lock(); + + try{ + + if(status == Status.RUNNING){ + + this.taskGroupList.add(executionController); + taskGroupAddCondition.signalAll(); + + }else{ + + throw new RejectedExecutionException("TaskGroupHandler status " + status); + } + + }finally{ + + taskGroupAddLock.unlock(); + } + } + + public void abortAllTaskGroups() { + + taskGroupRemoveLock.lock(); + + try{ + + while(!this.taskGroupList.isEmpty()){ + + for(SimpleExecutionController executionController : taskGroupList){ + + executionController.abort(); + } + } + + }finally{ + + taskGroupRemoveLock.unlock(); + } + + } + + public SimpleExecutionController execute(T taskGroup) throws RejectedExecutionException{ + + if(status == Status.RUNNING){ + + return new SimpleExecutionController(taskGroup, this); + + }else{ + + throw new RejectedExecutionException("TaskGroupHandler status " + status); + } + } + + public int getTaskGroupCount() { + + return this.taskGroupList.size(); + } + + public List> getTaskGroups() { + + return new ArrayList>(this.taskGroupList); + } + + public int getTotalTaskCount() { + + int taskCount = 0; + + for(SimpleExecutionController executionController : taskGroupList){ + + taskCount += executionController.getTaskQueue().size(); + } + + return taskCount; + } + + public Status getStatus(){ + + return this.status; + } + + public void awaitTermination() throws InterruptedException { + + taskGroupRemoveLock.lock(); + + try{ + + while(!this.taskGroupList.isEmpty()){ + + taskGroupRemoveCondition.await(); + } + + }finally{ + + taskGroupRemoveLock.unlock(); + } + } + + public void awaitTermination(long timeout) throws InterruptedException { + + taskGroupRemoveLock.lock(); + + try{ + + while(!this.taskGroupList.isEmpty()){ + + taskGroupRemoveCondition.await(timeout,TimeUnit.MILLISECONDS); + } + + }finally{ + + taskGroupRemoveLock.unlock(); + } + } + + public void shutdown() { + + taskGroupAddLock.lock(); + + try{ + + if(this.status == Status.RUNNING){ + + this.status = Status.TERMINATING; + this.taskGroupAddCondition.signalAll(); + } + + }finally{ + + taskGroupAddLock.unlock(); + } + } + + public void shutdownNow() { + + this.shutdown(); + this.abortAllTaskGroups(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadUtils.java index 22f137a900e..e383045db6f 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/threads/ThreadUtils.java @@ -2,22 +2,22 @@ public class ThreadUtils { - - public static void run(Runnable runnable, String threadName, boolean daemon){ - - Thread thread = new Thread(runnable, threadName); - - thread.setName(threadName); - - thread.setDaemon(daemon); - - thread.start(); - } - - public void sleep(long millis){ - - try { - Thread.sleep(millis); - } catch (InterruptedException e) {} - } + + public static void run(Runnable runnable, String threadName, boolean daemon){ + + Thread thread = new Thread(runnable, threadName); + + thread.setName(threadName); + + thread.setDaemon(daemon); + + thread.start(); + } + + public void sleep(long millis){ + + try { + Thread.sleep(millis); + } catch (InterruptedException e) {} + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/time/MillisecondTimeUnits.java b/eagledns/src/main/java/se/unlogic/standardutils/time/MillisecondTimeUnits.java index d5337230054..dfbfed1ad61 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/time/MillisecondTimeUnits.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/time/MillisecondTimeUnits.java @@ -9,11 +9,11 @@ public class MillisecondTimeUnits { - public static final int MILLI_SECOND = 1; - public static final int SECOND = 1000; - public static final int MINUTE = 60000; - public static final int HOUR = 3600000; - public static final int DAY = 86400000; - public static final long MONTH = 2678400000l; - public static final long YEAR = 32140800000l; + public static final int MILLI_SECOND = 1; + public static final int SECOND = 1000; + public static final int MINUTE = 60000; + public static final int HOUR = 3600000; + public static final int DAY = 86400000; + public static final long MONTH = 2678400000l; + public static final long YEAR = 32140800000l; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/time/TimeUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/time/TimeUtils.java index 04ab5c8cb8d..1f27ab34743 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/time/TimeUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/time/TimeUtils.java @@ -13,56 +13,56 @@ public class TimeUtils { - public static SimpleDateFormat HOUR_FORMATTER = new SimpleDateFormat("HH"); - public static SimpleDateFormat MINUTE_FORMATTER = new SimpleDateFormat("mm"); - public static SimpleDateFormat SECOND_FORMATTER = new SimpleDateFormat("ss"); - public static SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("HH:mm"); + public static SimpleDateFormat HOUR_FORMATTER = new SimpleDateFormat("HH"); + public static SimpleDateFormat MINUTE_FORMATTER = new SimpleDateFormat("mm"); + public static SimpleDateFormat SECOND_FORMATTER = new SimpleDateFormat("ss"); + public static SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("HH:mm"); - public static String secondsToString(long time) - { - return millisecondsToString(time * 1000); - } + public static String secondsToString(long time) + { + return millisecondsToString(time * 1000); + } - public static String millisecondsToString(long time) - { - int milliseconds = (int)(time % 1000); - int seconds = (int)((time/1000) % 60); - int minutes = (int)((time/60000) % 60); - int hours = (int)((time/3600000) % 24); - String millisecondsStr = (milliseconds<10 ? "00" : (milliseconds<100 ? "0" : ""))+milliseconds; - String secondsStr = (seconds<10 ? "0" : "")+seconds; - String minutesStr = (minutes<10 ? "0" : "")+minutes; - String hoursStr = (hours<10 ? "0" : "")+hours; - return new String(hoursStr+":"+minutesStr+":"+secondsStr+"."+millisecondsStr); - } + public static String millisecondsToString(long time) + { + int milliseconds = (int)(time % 1000); + int seconds = (int)((time/1000) % 60); + int minutes = (int)((time/60000) % 60); + int hours = (int)((time/3600000) % 24); + String millisecondsStr = (milliseconds<10 ? "00" : (milliseconds<100 ? "0" : ""))+milliseconds; + String secondsStr = (seconds<10 ? "0" : "")+seconds; + String minutesStr = (minutes<10 ? "0" : "")+minutes; + String hoursStr = (hours<10 ? "0" : "")+hours; + return new String(hoursStr+":"+minutesStr+":"+secondsStr+"."+millisecondsStr); + } - public static int getMinutes(long time) - { - return Integer.valueOf(MINUTE_FORMATTER.format(new Date(time))); - } + public static int getMinutes(long time) + { + return Integer.valueOf(MINUTE_FORMATTER.format(new Date(time))); + } - public static int getSeconds(long time) - { - return Integer.valueOf(SECOND_FORMATTER.format(new Date(time))); - } - - public static int getHour(long time) - { - return Integer.valueOf(HOUR_FORMATTER.format(new Date(time))); - } + public static int getSeconds(long time) + { + return Integer.valueOf(SECOND_FORMATTER.format(new Date(time))); + } - public static String hourAndMinutesToString(int hours, int minutes) - { + public static int getHour(long time) + { + return Integer.valueOf(HOUR_FORMATTER.format(new Date(time))); + } - String minutesStr = (minutes < 10 ? "0" : "") + minutes; - String hoursStr = (hours < 10 ? "0" : "") + hours; + public static String hourAndMinutesToString(int hours, int minutes) + { - return new String(hoursStr + ":" + minutesStr); + String minutesStr = (minutes < 10 ? "0" : "") + minutes; + String hoursStr = (hours < 10 ? "0" : "") + hours; - } - - public static Timestamp getCurrentTimestamp(){ - - return new Timestamp(System.currentTimeMillis()); - } + return new String(hoursStr + ":" + minutesStr); + + } + + public static Timestamp getCurrentTimestamp(){ + + return new Timestamp(System.currentTimeMillis()); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/timer/RunnableTimerTask.java b/eagledns/src/main/java/se/unlogic/standardutils/timer/RunnableTimerTask.java index dceabac636e..ccbb8a39b2a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/timer/RunnableTimerTask.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/timer/RunnableTimerTask.java @@ -11,15 +11,15 @@ public class RunnableTimerTask extends TimerTask { - private final Runnable runnable; + private final Runnable runnable; - public RunnableTimerTask(Runnable runnable) { - super(); - this.runnable = runnable; - } + public RunnableTimerTask(Runnable runnable) { + super(); + this.runnable = runnable; + } - @Override - public void run() { - this.runnable.run(); - } + @Override + public void run() { + this.runnable.run(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/DummyStringFormatValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/DummyStringFormatValidator.java index fd81662a987..e5295b23d90 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/DummyStringFormatValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/DummyStringFormatValidator.java @@ -10,8 +10,8 @@ public class DummyStringFormatValidator implements StringFormatValidator { - public boolean validateFormat(String value) { + public boolean validateFormat(String value) { - return true; - } + return true; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/NonNegativeStringIntegerValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/NonNegativeStringIntegerValidator.java index 6f1e85a4307..a3f680308d5 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/NonNegativeStringIntegerValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/NonNegativeStringIntegerValidator.java @@ -3,8 +3,8 @@ public class NonNegativeStringIntegerValidator extends StringIntegerValidator { - public NonNegativeStringIntegerValidator() { + public NonNegativeStringIntegerValidator() { - super(0, null); - } + super(0, null); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/PositiveStringIntegerValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/PositiveStringIntegerValidator.java index 58138b4b064..cb612684994 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/PositiveStringIntegerValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/PositiveStringIntegerValidator.java @@ -3,8 +3,8 @@ public class PositiveStringIntegerValidator extends StringIntegerValidator { - public PositiveStringIntegerValidator() { + public PositiveStringIntegerValidator() { - super(1, null); - } + super(1, null); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFloatValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFloatValidator.java index c9bf58c3fb2..d2d9f0b058f 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFloatValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFloatValidator.java @@ -12,36 +12,36 @@ public class StringFloatValidator extends StringNumberValidator { - public StringFloatValidator() { - super(null, null); - } + public StringFloatValidator() { + super(null, null); + } - public StringFloatValidator(Float minValue, Float maxValue) { - super(minValue,maxValue); - } + public StringFloatValidator(Float minValue, Float maxValue) { + super(minValue,maxValue); + } - public boolean validateFormat(String value) { + public boolean validateFormat(String value) { - Float numberValue = NumberUtils.toFloat(value); + Float numberValue = NumberUtils.toFloat(value); - if(numberValue == null){ + if(numberValue == null){ - return false; + return false; - }else if(maxValue != null && minValue != null){ + }else if(maxValue != null && minValue != null){ - return numberValue <= maxValue && numberValue > minValue; + return numberValue <= maxValue && numberValue > minValue; - }else if(maxValue != null){ + }else if(maxValue != null){ - return numberValue <= maxValue; + return numberValue <= maxValue; - }else if(minValue != null){ + }else if(minValue != null){ - return numberValue >= minValue; - } - else{ - return true; - } - } + return numberValue >= minValue; + } + else{ + return true; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFormatValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFormatValidator.java index e9e8f081fbf..1b50f9ad2c0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFormatValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringFormatValidator.java @@ -10,6 +10,6 @@ public interface StringFormatValidator { - boolean validateFormat(String value); + boolean validateFormat(String value); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringIntegerValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringIntegerValidator.java index cdb32ef31e1..d42e98cf08e 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringIntegerValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringIntegerValidator.java @@ -12,36 +12,36 @@ public class StringIntegerValidator extends StringNumberValidator { - public StringIntegerValidator() { - super(null, null); - } + public StringIntegerValidator() { + super(null, null); + } - public StringIntegerValidator(Integer minValue,Integer maxValue) { - super(minValue,maxValue); - } + public StringIntegerValidator(Integer minValue,Integer maxValue) { + super(minValue,maxValue); + } - public boolean validateFormat(String value) { + public boolean validateFormat(String value) { - Integer numberValue = NumberUtils.toInt(value); + Integer numberValue = NumberUtils.toInt(value); - if(numberValue == null){ + if(numberValue == null){ - return false; + return false; - }else if(maxValue != null && minValue != null){ + }else if(maxValue != null && minValue != null){ - return numberValue <= maxValue && numberValue >= minValue; + return numberValue <= maxValue && numberValue >= minValue; - }else if(maxValue != null){ + }else if(maxValue != null){ - return numberValue <= maxValue; + return numberValue <= maxValue; - }else if(minValue != null){ + }else if(minValue != null){ - return numberValue >= minValue; - } - else{ - return true; - } - } + return numberValue >= minValue; + } + else{ + return true; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLengthValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLengthValidator.java index 2852fc5b9eb..2495d1447e2 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLengthValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLengthValidator.java @@ -3,31 +3,31 @@ public class StringLengthValidator implements StringFormatValidator { - protected final Integer maxLength; - protected final Integer minLength; - - public StringLengthValidator(Integer minLength, Integer maxLength) { + protected final Integer maxLength; + protected final Integer minLength; - super(); - this.minLength = minLength; - this.maxLength = maxLength; - } + public StringLengthValidator(Integer minLength, Integer maxLength) { - public boolean validateFormat(String value) { + super(); + this.minLength = minLength; + this.maxLength = maxLength; + } - if(value == null){ + public boolean validateFormat(String value) { - return false; + if(value == null){ - }else if(value.length() > maxLength){ + return false; - return false; + }else if(value.length() > maxLength){ - }else if(value.length() < minLength){ + return false; - return false; - } - - return false; - } + }else if(value.length() < minLength){ + + return false; + } + + return false; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLongValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLongValidator.java index a0407c454c8..5b7f6d93f83 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLongValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringLongValidator.java @@ -12,36 +12,36 @@ public class StringLongValidator extends StringNumberValidator { - public StringLongValidator() { - super(null, null); - } + public StringLongValidator() { + super(null, null); + } - public StringLongValidator(Long minValue,Long maxValue) { - super(minValue, maxValue); - } + public StringLongValidator(Long minValue,Long maxValue) { + super(minValue, maxValue); + } - public boolean validateFormat(String value) { + public boolean validateFormat(String value) { - Long numberValue = NumberUtils.toLong(value); + Long numberValue = NumberUtils.toLong(value); - if(numberValue == null){ + if(numberValue == null){ - return false; + return false; - }else if(maxValue != null && minValue != null){ + }else if(maxValue != null && minValue != null){ - return numberValue <= maxValue && numberValue >= minValue; + return numberValue <= maxValue && numberValue >= minValue; - }else if(maxValue != null){ + }else if(maxValue != null){ - return numberValue <= maxValue; + return numberValue <= maxValue; - }else if(minValue != null){ + }else if(minValue != null){ - return numberValue >= minValue; - } - else{ - return true; - } - } + return numberValue >= minValue; + } + else{ + return true; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringNumberValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringNumberValidator.java index 96dfcc88612..2e62f98eec3 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/StringNumberValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/StringNumberValidator.java @@ -10,12 +10,12 @@ public abstract class StringNumberValidator implements StringFormatValidator { - protected final T maxValue; - protected final T minValue; + protected final T maxValue; + protected final T minValue; - public StringNumberValidator(T minValue, T maxValue) { - super(); - this.maxValue = maxValue; - this.minValue = minValue; - } + public StringNumberValidator(T minValue, T maxValue) { + super(); + this.maxValue = maxValue; + this.minValue = minValue; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/TCPPortStringFormatValidator.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/TCPPortStringFormatValidator.java index b19617740de..8f294438d46 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/TCPPortStringFormatValidator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/TCPPortStringFormatValidator.java @@ -10,7 +10,7 @@ public class TCPPortStringFormatValidator extends StringIntegerValidator { - public TCPPortStringFormatValidator(){ - super(1,65536); - } + public TCPPortStringFormatValidator(){ + super(1,65536); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationError.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationError.java index 0c803f211ed..f76311a816f 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationError.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationError.java @@ -13,56 +13,56 @@ import se.unlogic.standardutils.xml.XMLUtils; public class ValidationError { - private String fieldName; - private ValidationErrorType validationErrorType; - private String messageKey; - - public ValidationError(String fieldName, ValidationErrorType validationErrorType, String messageKey) { - super(); - this.fieldName = fieldName; - this.validationErrorType = validationErrorType; - this.messageKey = messageKey; - } - - public ValidationError(String fieldName, ValidationErrorType validationErrorType) { - super(); - this.fieldName = fieldName; - this.validationErrorType = validationErrorType; - } + private String fieldName; + private ValidationErrorType validationErrorType; + private String messageKey; - public ValidationError(String messageKey) { - super(); - - this.messageKey = messageKey; - } + public ValidationError(String fieldName, ValidationErrorType validationErrorType, String messageKey) { + super(); + this.fieldName = fieldName; + this.validationErrorType = validationErrorType; + this.messageKey = messageKey; + } - public String getFieldName() { - return fieldName; - } + public ValidationError(String fieldName, ValidationErrorType validationErrorType) { + super(); + this.fieldName = fieldName; + this.validationErrorType = validationErrorType; + } - public ValidationErrorType getValidationErrorType() { - return validationErrorType; - } + public ValidationError(String messageKey) { + super(); - public String getMessageKey() { - return messageKey; - } + this.messageKey = messageKey; + } - public final Node toXML(Document doc) { - Element validationError = doc.createElement("validationError"); - - if(this.fieldName != null){ - validationError.appendChild(XMLUtils.createCDATAElement("fieldName", fieldName, doc)); - } - - if(this.validationErrorType != null){ - validationError.appendChild(XMLUtils.createCDATAElement("validationErrorType", validationErrorType.toString(), doc)); - } - - if(this.messageKey != null){ - validationError.appendChild(XMLUtils.createCDATAElement("messageKey", messageKey, doc)); - } - - return validationError; - } + public String getFieldName() { + return fieldName; + } + + public ValidationErrorType getValidationErrorType() { + return validationErrorType; + } + + public String getMessageKey() { + return messageKey; + } + + public final Node toXML(Document doc) { + Element validationError = doc.createElement("validationError"); + + if(this.fieldName != null){ + validationError.appendChild(XMLUtils.createCDATAElement("fieldName", fieldName, doc)); + } + + if(this.validationErrorType != null){ + validationError.appendChild(XMLUtils.createCDATAElement("validationErrorType", validationErrorType.toString(), doc)); + } + + if(this.messageKey != null){ + validationError.appendChild(XMLUtils.createCDATAElement("messageKey", messageKey, doc)); + } + + return validationError; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationErrorType.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationErrorType.java index 824d921fac7..be7867e5b5c 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationErrorType.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationErrorType.java @@ -8,9 +8,9 @@ package se.unlogic.standardutils.validation; public enum ValidationErrorType { - RequiredField, - InvalidFormat, - Other, - TooShort, - TooLong + RequiredField, + InvalidFormat, + Other, + TooShort, + TooLong } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationException.java b/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationException.java index ba50dd7d806..906653d1ea9 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/validation/ValidationException.java @@ -14,45 +14,45 @@ import java.util.List; public class ValidationException extends Exception { - /** - * - */ - private static final long serialVersionUID = -1221745166857804542L; - private final List errors; + /** + * + */ + private static final long serialVersionUID = -1221745166857804542L; + private final List errors; - public ValidationException(List errors) { - super(); + public ValidationException(List errors) { + super(); - if (errors == null) { - throw new NullPointerException(); - } + if (errors == null) { + throw new NullPointerException(); + } - this.errors = errors; - } + this.errors = errors; + } - public ValidationException(ValidationError... errors) { - super(); + public ValidationException(ValidationError... errors) { + super(); - if (errors == null) { - throw new NullPointerException(); - } + if (errors == null) { + throw new NullPointerException(); + } - this.errors = Arrays.asList(errors); - } + this.errors = Arrays.asList(errors); + } - public List getErrors() { - return errors; - } + public List getErrors() { + return errors; + } - public final Element toXML(Document doc) { - Element validationException = doc.createElement("validationException"); + public final Element toXML(Document doc) { + Element validationException = doc.createElement("validationException"); - for (ValidationError validationError : errors) { - if (validationError != null) { - validationException.appendChild(validationError.toXML(doc)); - } - } + for (ValidationError validationError : errors) { + if (validationError != null) { + validationException.appendChild(validationError.toXML(doc)); + } + } - return validationException; - } + return validationException; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/BeanXMLPopulator.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/BeanXMLPopulator.java index eddc229f551..53618ca72f0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/BeanXMLPopulator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/BeanXMLPopulator.java @@ -11,5 +11,5 @@ import se.unlogic.standardutils.validation.ValidationException; public interface BeanXMLPopulator { - Type populate(Document doc) throws ValidationException; + Type populate(Document doc) throws ValidationException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLT.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLT.java index 3d00f877c0f..2cd28dc2722 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLT.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLT.java @@ -19,6 +19,6 @@ */ public interface CachedXSLT { - void reloadStyleSheet() throws TransformerConfigurationException; - Transformer getTransformer() throws TransformerConfigurationException; + void reloadStyleSheet() throws TransformerConfigurationException; + Transformer getTransformer() throws TransformerConfigurationException; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTBase.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTBase.java index 45da34d3c4d..c4878931c57 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTBase.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTBase.java @@ -14,10 +14,10 @@ public abstract class CachedXSLTBase implements CachedXSLT { - protected Templates templates; + protected Templates templates; - public Transformer getTransformer() throws TransformerConfigurationException { + public Transformer getTransformer() throws TransformerConfigurationException { - return templates.newTransformer(); - } + return templates.newTransformer(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTFile.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTFile.java index 460c686fbc4..76118b89149 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTFile.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTFile.java @@ -16,40 +16,40 @@ public class CachedXSLTFile extends CachedXSLTBase{ - private File file; - private URIResolver uriResolver; + private File file; + private URIResolver uriResolver; - public void reloadStyleSheet() throws TransformerConfigurationException{ - this.cacheStyleSheet(file); - } + public void reloadStyleSheet() throws TransformerConfigurationException{ + this.cacheStyleSheet(file); + } - public CachedXSLTFile(File f) throws TransformerConfigurationException{ - this.file = f; - this.cacheStyleSheet(f); - } + public CachedXSLTFile(File f) throws TransformerConfigurationException{ + this.file = f; + this.cacheStyleSheet(f); + } - public CachedXSLTFile(File file, URIResolver uriResolver) throws TransformerConfigurationException { + public CachedXSLTFile(File file, URIResolver uriResolver) throws TransformerConfigurationException { - this.file = file; - this.uriResolver = uriResolver; - this.cacheStyleSheet(file); - } + this.file = file; + this.uriResolver = uriResolver; + this.cacheStyleSheet(file); + } - private void cacheStyleSheet(File f) throws TransformerConfigurationException{ - Source xsltSource = new StreamSource(f); - TransformerFactory transFact = TransformerFactory.newInstance(); + private void cacheStyleSheet(File f) throws TransformerConfigurationException{ + Source xsltSource = new StreamSource(f); + TransformerFactory transFact = TransformerFactory.newInstance(); - if(uriResolver != null){ - transFact.setURIResolver(uriResolver); - } + if(uriResolver != null){ + transFact.setURIResolver(uriResolver); + } - this.templates = transFact.newTemplates(xsltSource); - this.file = f; - } + this.templates = transFact.newTemplates(xsltSource); + this.file = f; + } - @Override - public String toString() { + @Override + public String toString() { - return "CachedXSLTFile: " + file; - } + return "CachedXSLTFile: " + file; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTResourceStream.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTResourceStream.java index 36df744ef30..a90392d0541 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTResourceStream.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTResourceStream.java @@ -17,33 +17,33 @@ public class CachedXSLTResourceStream extends CachedXSLTBase{ - private Class resourceClass; - private String path; + private Class resourceClass; + private String path; - public CachedXSLTResourceStream(Class resourceClass, String path) throws TransformerConfigurationException { - this.cacheStyleSheet(resourceClass, path); - } + public CachedXSLTResourceStream(Class resourceClass, String path) throws TransformerConfigurationException { + this.cacheStyleSheet(resourceClass, path); + } - public void reloadStyleSheet() throws TransformerConfigurationException { - this.cacheStyleSheet(this.resourceClass,this.path); - } + public void reloadStyleSheet() throws TransformerConfigurationException { + this.cacheStyleSheet(this.resourceClass,this.path); + } - private void cacheStyleSheet(Class resourceClass, String path) throws TransformerConfigurationException{ - InputStream inputStream = resourceClass.getResourceAsStream(path); - Source xsltSource = new StreamSource(inputStream); - TransformerFactory transFact = TransformerFactory.newInstance(); - Templates templates = transFact.newTemplates(xsltSource); + private void cacheStyleSheet(Class resourceClass, String path) throws TransformerConfigurationException{ + InputStream inputStream = resourceClass.getResourceAsStream(path); + Source xsltSource = new StreamSource(inputStream); + TransformerFactory transFact = TransformerFactory.newInstance(); + Templates templates = transFact.newTemplates(xsltSource); - try {inputStream.close();} catch (IOException e) {} + try {inputStream.close();} catch (IOException e) {} - this.templates = templates; - this.resourceClass = resourceClass; - this.path = path; - } + this.templates = templates; + this.resourceClass = resourceClass; + this.path = path; + } - @Override - public String toString() { + @Override + public String toString() { - return "CachedXSLTResourceStream: " + resourceClass + " " + path; - } + return "CachedXSLTResourceStream: " + resourceClass + " " + path; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTURI.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTURI.java index 51cbc846a4c..f1b3d933edc 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTURI.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/CachedXSLTURI.java @@ -15,36 +15,36 @@ public class CachedXSLTURI extends CachedXSLTBase { - private URI uri; - private URIResolver uriResolver; + private URI uri; + private URIResolver uriResolver; - public CachedXSLTURI(URI uri) throws TransformerConfigurationException { - super(); - this.uri = uri; - this.reloadStyleSheet(); - } + public CachedXSLTURI(URI uri) throws TransformerConfigurationException { + super(); + this.uri = uri; + this.reloadStyleSheet(); + } - public CachedXSLTURI(URI uri, URIResolver uriResolver) throws TransformerConfigurationException { + public CachedXSLTURI(URI uri, URIResolver uriResolver) throws TransformerConfigurationException { - this.uri = uri; - this.uriResolver = uriResolver; - this.reloadStyleSheet(); - } + this.uri = uri; + this.uriResolver = uriResolver; + this.reloadStyleSheet(); + } - public void reloadStyleSheet() throws TransformerConfigurationException { + public void reloadStyleSheet() throws TransformerConfigurationException { - TransformerFactory transFact = TransformerFactory.newInstance(); + TransformerFactory transFact = TransformerFactory.newInstance(); - if(uriResolver != null){ - transFact.setURIResolver(uriResolver); - } + if(uriResolver != null){ + transFact.setURIResolver(uriResolver); + } - this.templates = transFact.newTemplates(new StreamSource(uri.toString())); - } + this.templates = transFact.newTemplates(new StreamSource(uri.toString())); + } - @Override - public String toString() { + @Override + public String toString() { - return "CachedXSLTURI: " + uri; - } + return "CachedXSLTURI: " + uri; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassPathURIResolver.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassPathURIResolver.java index f8f00a2e78e..87112dc0e0b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassPathURIResolver.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassPathURIResolver.java @@ -16,36 +16,36 @@ public class ClassPathURIResolver implements URIResolver { - private static final ClassPathURIResolver CLASS_PATH_URI_RESOLVER = new ClassPathURIResolver(); + private static final ClassPathURIResolver CLASS_PATH_URI_RESOLVER = new ClassPathURIResolver(); - public static ClassPathURIResolver getInstance(){ + public static ClassPathURIResolver getInstance(){ - return CLASS_PATH_URI_RESOLVER; - } + return CLASS_PATH_URI_RESOLVER; + } - public static final String PREFIX = "classpath://"; + public static final String PREFIX = "classpath://"; - public Source resolve(String href, String base) throws TransformerException { + public Source resolve(String href, String base) throws TransformerException { - if(href.startsWith(PREFIX) && href.length() > PREFIX.length()){ + if(href.startsWith(PREFIX) && href.length() > PREFIX.length()){ - URL url = getURL(href); + URL url = getURL(href); - if(url != null){ + if(url != null){ - return new StreamSource(url.toString()); - } - - throw new TransformerException("Unable to resolve href " + href); - } + return new StreamSource(url.toString()); + } - return null; - } + throw new TransformerException("Unable to resolve href " + href); + } - public static URL getURL(String href) { + return null; + } - String classPath = "/" + href.substring(PREFIX.length()); + public static URL getURL(String href) { - return ClassPathURIResolver.class.getResource(classPath); - } + String classPath = "/" + href.substring(PREFIX.length()); + + return ClassPathURIResolver.class.getResource(classPath); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassXMLInfo.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassXMLInfo.java index 44437e43ffc..0fc4b7cb38b 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassXMLInfo.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/ClassXMLInfo.java @@ -11,20 +11,20 @@ public class ClassXMLInfo { - private String elementName; - private List fields; + private String elementName; + private List fields; - public ClassXMLInfo(String elementName, List field) { - super(); - this.elementName = elementName; - this.fields = field; - } + public ClassXMLInfo(String elementName, List field) { + super(); + this.elementName = elementName; + this.fields = field; + } - public String getElementName() { - return elementName; - } + public String getElementName() { + return elementName; + } - public List getFields() { - return fields; - } + public List getFields() { + return fields; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/Elementable.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/Elementable.java index 8506e8c5a62..0b1639d223a 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/Elementable.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/Elementable.java @@ -12,5 +12,5 @@ public interface Elementable extends XMLable { - Element toXML(Document doc); + Element toXML(Document doc); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldType.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldType.java index 12a0e9d5408..d0b928eb067 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldType.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldType.java @@ -8,6 +8,6 @@ package se.unlogic.standardutils.xml; public enum FieldType { - Element, - Attribute + Element, + Attribute } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldXMLInfo.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldXMLInfo.java index 92ff07b5851..19efde57d19 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldXMLInfo.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/FieldXMLInfo.java @@ -13,81 +13,81 @@ public class FieldXMLInfo { - private final String name; - private final Field field; - private final FieldType fieldType; - private final boolean cdata; - private final boolean elementable; - private final boolean list; - private final boolean array; - private final boolean skipSubElement; - private final String childName; - private final Stringyfier valueFormatter; + private final String name; + private final Field field; + private final FieldType fieldType; + private final boolean cdata; + private final boolean elementable; + private final boolean list; + private final boolean array; + private final boolean skipSubElement; + private final String childName; + private final Stringyfier valueFormatter; - public FieldXMLInfo(String name, Field field, FieldType fieldType, boolean cdata, boolean elementable, boolean list, boolean array, String childName, boolean skipSubElement, Stringyfier valueFormatter) { + public FieldXMLInfo(String name, Field field, FieldType fieldType, boolean cdata, boolean elementable, boolean list, boolean array, String childName, boolean skipSubElement, Stringyfier valueFormatter) { - super(); - this.name = name; - this.field = field; - this.fieldType = fieldType; - this.cdata = cdata; - this.elementable = elementable; - this.list = list; - this.array = array; - this.childName = childName; - this.valueFormatter = valueFormatter; - this.skipSubElement = skipSubElement; - } + super(); + this.name = name; + this.field = field; + this.fieldType = fieldType; + this.cdata = cdata; + this.elementable = elementable; + this.list = list; + this.array = array; + this.childName = childName; + this.valueFormatter = valueFormatter; + this.skipSubElement = skipSubElement; + } - public String getName() { + public String getName() { - return name; - } + return name; + } - public Field getField() { + public Field getField() { - return field; - } + return field; + } - public FieldType getFieldType() { + public FieldType getFieldType() { - return fieldType; - } + return fieldType; + } - public boolean isCDATA() { + public boolean isCDATA() { - return cdata; - } + return cdata; + } - public boolean isList() { + public boolean isList() { - return list; - } + return list; + } - public boolean isElementable() { + public boolean isElementable() { - return elementable; - } + return elementable; + } - public String getChildName() { + public String getChildName() { - return childName; - } + return childName; + } - public Stringyfier getValueFormatter() { + public Stringyfier getValueFormatter() { - return valueFormatter; - } + return valueFormatter; + } - - public boolean skipSubElement() { - - return skipSubElement; - } - - public boolean isArray() { - - return array; - } + public boolean skipSubElement() { + + return skipSubElement; + } + + + public boolean isArray() { + + return array; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/MissingXMLAnnotationException.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/MissingXMLAnnotationException.java index a127497ff86..f69a26cbf4f 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/MissingXMLAnnotationException.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/MissingXMLAnnotationException.java @@ -9,17 +9,17 @@ public class MissingXMLAnnotationException extends RuntimeException { - private static final long serialVersionUID = -5127582859037405055L; - private Class clazz; + private static final long serialVersionUID = -5127582859037405055L; + private Class clazz; - public MissingXMLAnnotationException(Class clazz) { + public MissingXMLAnnotationException(Class clazz) { - super("Class " + clazz + " is missing the XMLElement annotation and can therefore not be converted to an element"); + super("Class " + clazz + " is missing the XMLElement annotation and can therefore not be converted to an element"); - this.clazz = clazz; - } + this.clazz = clazz; + } - public Class getBeanClass() { - return clazz; - } + public Class getBeanClass() { + return clazz; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/SimpleNamespaceContext.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/SimpleNamespaceContext.java index bc1c0065b8a..008f6e48d19 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/SimpleNamespaceContext.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/SimpleNamespaceContext.java @@ -14,28 +14,28 @@ public class SimpleNamespaceContext implements NamespaceContext { - private String prefix; - private String URI; + private String prefix; + private String URI; - public SimpleNamespaceContext(String prefix, String URI) { + public SimpleNamespaceContext(String prefix, String URI) { - super(); - this.prefix = prefix; - this.URI = URI; - } + super(); + this.prefix = prefix; + this.URI = URI; + } - public String getNamespaceURI(String prefix) { + public String getNamespaceURI(String prefix) { - return URI; - } + return URI; + } - public String getPrefix(String namespaceURI) { + public String getPrefix(String namespaceURI) { - return prefix; - } + return prefix; + } - public Iterator getPrefixes(String namespaceURI) { + public Iterator getPrefixes(String namespaceURI) { - return Collections.singletonList(prefix).iterator(); - } + return Collections.singletonList(prefix).iterator(); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLAttribute.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLAttribute.java index 61b89ce61e5..db6bd1e4f47 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLAttribute.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLAttribute.java @@ -20,6 +20,6 @@ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface XMLAttribute { - String name() default ""; - Class valueFormatter() default DummyStringyfier.class; + String name() default ""; + Class valueFormatter() default DummyStringyfier.class; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLElement.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLElement.java index 047b7888235..d2c0ac80140 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLElement.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLElement.java @@ -20,9 +20,9 @@ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.TYPE}) public @interface XMLElement { - String name() default ""; - boolean cdata() default false; - boolean skipChildParentElement() default false; - String childName() default ""; - Class valueFormatter() default DummyStringyfier.class; + String name() default ""; + boolean cdata() default false; + boolean skipChildParentElement() default false; + String childName() default ""; + Class valueFormatter() default DummyStringyfier.class; } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLGenerator.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLGenerator.java index fb3cdc606b5..74ccc86c438 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLGenerator.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLGenerator.java @@ -26,324 +26,324 @@ public class XMLGenerator { - //TODO Use weak references in this map to prevent memory leaks - private static ConcurrentHashMap, ClassXMLInfo> FIELD_MAP = new ConcurrentHashMap, ClassXMLInfo>(); + //TODO Use weak references in this map to prevent memory leaks + private static ConcurrentHashMap, ClassXMLInfo> FIELD_MAP = new ConcurrentHashMap, ClassXMLInfo>(); - @SuppressWarnings("unchecked") - public static Element toXML(Object bean, Document doc){ + @SuppressWarnings("unchecked") + public static Element toXML(Object bean, Document doc){ - ClassXMLInfo classInfo = FIELD_MAP.get(bean.getClass()); + ClassXMLInfo classInfo = FIELD_MAP.get(bean.getClass()); - if(classInfo == null){ + if(classInfo == null){ - Class clazz = bean.getClass(); + Class clazz = bean.getClass(); - XMLElement xmlElement = clazz.getAnnotation(XMLElement.class); + XMLElement xmlElement = clazz.getAnnotation(XMLElement.class); - if(xmlElement == null){ + if(xmlElement == null){ - throw new MissingXMLAnnotationException(clazz); - } + throw new MissingXMLAnnotationException(clazz); + } - String elementName = xmlElement.name(); + String elementName = xmlElement.name(); - if(StringUtils.isEmpty(elementName)){ + if(StringUtils.isEmpty(elementName)){ - elementName = clazz.getSimpleName(); - } + elementName = clazz.getSimpleName(); + } - List annotatedFields = new ArrayList(); + List annotatedFields = new ArrayList(); - Class currentClazz = clazz; + Class currentClazz = clazz; - while (currentClazz != Object.class) { + while (currentClazz != Object.class) { - Field[] fields = currentClazz.getDeclaredFields(); + Field[] fields = currentClazz.getDeclaredFields(); - for(Field field : fields){ + for(Field field : fields){ - XMLElement elementAnnotation = field.getAnnotation(XMLElement.class); + XMLElement elementAnnotation = field.getAnnotation(XMLElement.class); - if(elementAnnotation != null){ + if(elementAnnotation != null){ - String name = elementAnnotation.name(); + String name = elementAnnotation.name(); - if(StringUtils.isEmpty(name)){ + if(StringUtils.isEmpty(name)){ - name = field.getName(); - } + name = field.getName(); + } - Stringyfier valueFormatter = null; + Stringyfier valueFormatter = null; - if(elementAnnotation.valueFormatter() != DummyStringyfier.class){ + if(elementAnnotation.valueFormatter() != DummyStringyfier.class){ - try { - valueFormatter = elementAnnotation.valueFormatter().newInstance(); + try { + valueFormatter = elementAnnotation.valueFormatter().newInstance(); - } catch (InstantiationException e) { + } catch (InstantiationException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - if(Collection.class.isAssignableFrom(field.getType())){ + if(Collection.class.isAssignableFrom(field.getType())){ - boolean elementable = false; + boolean elementable = false; - if(ReflectionUtils.isGenericlyTyped(field) && Elementable.class.isAssignableFrom((Class) ReflectionUtils.getGenericType(field))){ + if(ReflectionUtils.isGenericlyTyped(field) && Elementable.class.isAssignableFrom((Class) ReflectionUtils.getGenericType(field))){ - elementable = true; - } + elementable = true; + } - String childName = elementAnnotation.childName(); + String childName = elementAnnotation.childName(); - if(StringUtils.isEmpty(childName)){ + if(StringUtils.isEmpty(childName)){ - childName = "value"; - } + childName = "value"; + } - annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Element,elementAnnotation.cdata(),elementable,true,false,childName,elementAnnotation.skipChildParentElement(),valueFormatter)); + annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Element,elementAnnotation.cdata(),elementable,true,false,childName,elementAnnotation.skipChildParentElement(),valueFormatter)); - }else if(field.getType().isArray()){ + }else if(field.getType().isArray()){ - boolean elementable = false; + boolean elementable = false; - if(Elementable.class.isAssignableFrom(field.getType())){ + if(Elementable.class.isAssignableFrom(field.getType())){ - elementable = true; - } + elementable = true; + } - String childName = elementAnnotation.childName(); + String childName = elementAnnotation.childName(); - if(StringUtils.isEmpty(childName)){ + if(StringUtils.isEmpty(childName)){ - childName = "value"; - } + childName = "value"; + } - annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Element,elementAnnotation.cdata(),elementable,false,true,childName,elementAnnotation.skipChildParentElement(),valueFormatter)); + annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Element,elementAnnotation.cdata(),elementable,false,true,childName,elementAnnotation.skipChildParentElement(),valueFormatter)); - }else{ + }else{ - String childName = null; + String childName = null; - if(!StringUtils.isEmpty(elementAnnotation.childName())){ + if(!StringUtils.isEmpty(elementAnnotation.childName())){ - childName = elementAnnotation.childName(); - } + childName = elementAnnotation.childName(); + } - annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Element,elementAnnotation.cdata(),Elementable.class.isAssignableFrom(field.getType()),false,false,childName,false,valueFormatter)); - } + annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Element,elementAnnotation.cdata(),Elementable.class.isAssignableFrom(field.getType()),false,false,childName,false,valueFormatter)); + } - ReflectionUtils.fixFieldAccess(field); - } + ReflectionUtils.fixFieldAccess(field); + } - XMLAttribute attributeAnnotation = field.getAnnotation(XMLAttribute.class); + XMLAttribute attributeAnnotation = field.getAnnotation(XMLAttribute.class); - if(attributeAnnotation != null){ + if(attributeAnnotation != null){ - String name = attributeAnnotation.name(); + String name = attributeAnnotation.name(); - if(StringUtils.isEmpty(name)){ + if(StringUtils.isEmpty(name)){ - name = field.getName(); - } + name = field.getName(); + } - Stringyfier valueFormatter = null; + Stringyfier valueFormatter = null; - if(attributeAnnotation.valueFormatter() != DummyStringyfier.class){ + if(attributeAnnotation.valueFormatter() != DummyStringyfier.class){ - try { - valueFormatter = attributeAnnotation.valueFormatter().newInstance(); + try { + valueFormatter = attributeAnnotation.valueFormatter().newInstance(); - } catch (InstantiationException e) { + } catch (InstantiationException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } - } + throw new RuntimeException(e); + } + } - annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Attribute,false,false,false,false,null,false,valueFormatter)); + annotatedFields.add(new FieldXMLInfo(name, field, FieldType.Attribute,false,false,false,false,null,false,valueFormatter)); - ReflectionUtils.fixFieldAccess(field); - } - } + ReflectionUtils.fixFieldAccess(field); + } + } - currentClazz = currentClazz.getSuperclass(); - } + currentClazz = currentClazz.getSuperclass(); + } - if(annotatedFields.isEmpty()){ + if(annotatedFields.isEmpty()){ - throw new NoAnnotatedFieldsFoundException(clazz,XMLElement.class,XMLAttribute.class); - } + throw new NoAnnotatedFieldsFoundException(clazz,XMLElement.class,XMLAttribute.class); + } - classInfo = new ClassXMLInfo(elementName, annotatedFields); + classInfo = new ClassXMLInfo(elementName, annotatedFields); - FIELD_MAP.put(clazz, classInfo); - } + FIELD_MAP.put(clazz, classInfo); + } - Element classElement = doc.createElement(classInfo.getElementName()); + Element classElement = doc.createElement(classInfo.getElementName()); - for(FieldXMLInfo fieldInfo : classInfo.getFields()){ + for(FieldXMLInfo fieldInfo : classInfo.getFields()){ - Object fieldValue; - try { - fieldValue = fieldInfo.getField().get(bean); - } catch (IllegalArgumentException e) { + Object fieldValue; + try { + fieldValue = fieldInfo.getField().get(bean); + } catch (IllegalArgumentException e) { - throw new RuntimeException(e); + throw new RuntimeException(e); - } catch (IllegalAccessException e) { + } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } + throw new RuntimeException(e); + } - if(fieldValue == null){ + if(fieldValue == null){ - continue; + continue; - }else if(!fieldInfo.isList() && fieldInfo.getValueFormatter() != null){ + }else if(!fieldInfo.isList() && fieldInfo.getValueFormatter() != null){ - fieldValue = fieldInfo.getValueFormatter().format(fieldValue); + fieldValue = fieldInfo.getValueFormatter().format(fieldValue); - }else if(fieldValue instanceof Date){ + }else if(fieldValue instanceof Date){ - fieldValue = DateUtils.DATE_TIME_FORMATTER.format(fieldValue); - } + fieldValue = DateUtils.DATE_TIME_FORMATTER.format(fieldValue); + } - if(fieldInfo.getFieldType() == FieldType.Attribute){ + if(fieldInfo.getFieldType() == FieldType.Attribute){ - classElement.setAttribute(fieldInfo.getName(), fieldValue.toString()); + classElement.setAttribute(fieldInfo.getName(), fieldValue.toString()); - }else if(fieldInfo.isList()){ + }else if(fieldInfo.isList()){ - List fieldValues = (List)fieldValue; + List fieldValues = (List)fieldValue; - if(fieldValues.isEmpty()){ + if(fieldValues.isEmpty()){ - continue; - } + continue; + } - Element subElement; - - if(fieldInfo.skipSubElement()){ - - subElement = classElement; - - }else{ - - subElement = doc.createElement(fieldInfo.getName()); - } + Element subElement; + if(fieldInfo.skipSubElement()){ - for(Object value : fieldValues){ + subElement = classElement; - if(value != null){ + }else{ - parseValue(fieldInfo,value,subElement,doc); - } - } + subElement = doc.createElement(fieldInfo.getName()); + } - if(!fieldInfo.skipSubElement() && subElement.hasChildNodes()){ - classElement.appendChild(subElement); - } - }else if(fieldInfo.isArray()){ + for(Object value : fieldValues){ - Object[] fieldValues = (Object[])fieldValue; + if(value != null){ - if(ArrayUtils.isEmpty(fieldValues)){ + parseValue(fieldInfo,value,subElement,doc); + } + } - continue; - } + if(!fieldInfo.skipSubElement() && subElement.hasChildNodes()){ + classElement.appendChild(subElement); + } - Element subElement; - - if(fieldInfo.skipSubElement()){ - - subElement = classElement; - - }else{ - - subElement = doc.createElement(fieldInfo.getName()); - } + }else if(fieldInfo.isArray()){ + Object[] fieldValues = (Object[])fieldValue; - for(Object value : fieldValues){ + if(ArrayUtils.isEmpty(fieldValues)){ - if(value != null){ + continue; + } - parseValue(fieldInfo,value,subElement,doc); - } - } + Element subElement; - if(!fieldInfo.skipSubElement() && subElement.hasChildNodes()){ - classElement.appendChild(subElement); - } + if(fieldInfo.skipSubElement()){ - }else if(fieldInfo.isElementable()){ + subElement = classElement; - Element subElement = ((Elementable)fieldValue).toXML(doc); + }else{ - if(subElement != null){ + subElement = doc.createElement(fieldInfo.getName()); + } - if(fieldInfo.getChildName() != null){ - Element middleElement = doc.createElement(fieldInfo.getChildName()); - classElement.appendChild(middleElement); - middleElement.appendChild(subElement); + for(Object value : fieldValues){ - }else{ - classElement.appendChild(subElement); - } - } - }else if(fieldInfo.isCDATA()){ + if(value != null){ - classElement.appendChild(XMLUtils.createCDATAElement(fieldInfo.getName(), fieldValue.toString(), doc)); + parseValue(fieldInfo,value,subElement,doc); + } + } - }else{ - classElement.appendChild(XMLUtils.createElement(fieldInfo.getName(), fieldValue.toString(), doc)); - } - } + if(!fieldInfo.skipSubElement() && subElement.hasChildNodes()){ + classElement.appendChild(subElement); + } - return classElement; - } + }else if(fieldInfo.isElementable()){ - private static void parseValue(FieldXMLInfo fieldInfo, Object value, Element subElement, Document doc) { + Element subElement = ((Elementable)fieldValue).toXML(doc); - if(fieldInfo.getValueFormatter() != null){ + if(subElement != null){ - value = fieldInfo.getValueFormatter().format(value); + if(fieldInfo.getChildName() != null){ - }else if(value instanceof Date){ + Element middleElement = doc.createElement(fieldInfo.getChildName()); + classElement.appendChild(middleElement); + middleElement.appendChild(subElement); - value = DateUtils.DATE_TIME_FORMATTER.format(value); - } + }else{ + classElement.appendChild(subElement); + } + } + }else if(fieldInfo.isCDATA()){ - if(fieldInfo.isElementable()){ + classElement.appendChild(XMLUtils.createCDATAElement(fieldInfo.getName(), fieldValue.toString(), doc)); - Element subSubElement = ((Elementable)value).toXML(doc); + }else{ + classElement.appendChild(XMLUtils.createElement(fieldInfo.getName(), fieldValue.toString(), doc)); + } + } - if(subSubElement != null){ + return classElement; + } - subElement.appendChild(subSubElement); - } - }else{ + private static void parseValue(FieldXMLInfo fieldInfo, Object value, Element subElement, Document doc) { - if(fieldInfo.isCDATA()){ + if(fieldInfo.getValueFormatter() != null){ - subElement.appendChild(XMLUtils.createCDATAElement(fieldInfo.getChildName(), value, doc)); + value = fieldInfo.getValueFormatter().format(value); - }else{ + }else if(value instanceof Date){ - subElement.appendChild(XMLUtils.createElement(fieldInfo.getChildName(), value, doc)); - } - } - } + value = DateUtils.DATE_TIME_FORMATTER.format(value); + } + + if(fieldInfo.isElementable()){ + + Element subSubElement = ((Elementable)value).toXML(doc); + + if(subSubElement != null){ + + subElement.appendChild(subSubElement); + } + }else{ + + if(fieldInfo.isCDATA()){ + + subElement.appendChild(XMLUtils.createCDATAElement(fieldInfo.getChildName(), value, doc)); + + }else{ + + subElement.appendChild(XMLUtils.createElement(fieldInfo.getChildName(), value, doc)); + } + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLTransformer.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLTransformer.java index 9a088d44a08..d3c7625daa9 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLTransformer.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLTransformer.java @@ -17,9 +17,9 @@ import java.io.Writer; public class XMLTransformer { - - public static void transformToWriter(Transformer transformer, Document doc, Writer writer, String encoding) throws TransformerException{ - transformer.setOutputProperty(OutputKeys.ENCODING,encoding); - transformer.transform(new DOMSource(doc), new StreamResult(writer)); - } + + public static void transformToWriter(Transformer transformer, Document doc, Writer writer, String encoding) throws TransformerException{ + transformer.setOutputProperty(OutputKeys.ENCODING,encoding); + transformer.transform(new DOMSource(doc), new StreamResult(writer)); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLUtils.java index b73998b69a2..f681fac82d0 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLUtils.java @@ -38,319 +38,319 @@ public class XMLUtils { - private static DocumentBuilder documentBuilder; - private static DocumentBuilder namespaceAwareDocumentBuilder; - private final static Logger logger = Logger.getLogger(XMLUtils.class); + private static DocumentBuilder documentBuilder; + private static DocumentBuilder namespaceAwareDocumentBuilder; + private final static Logger logger = Logger.getLogger(XMLUtils.class); - static { - try { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + static { + try { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilder = documentBuilderFactory.newDocumentBuilder(); + documentBuilder = documentBuilderFactory.newDocumentBuilder(); - documentBuilderFactory.setNamespaceAware(true); + documentBuilderFactory.setNamespaceAware(true); - namespaceAwareDocumentBuilder = documentBuilderFactory.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - logger.error(e.getMessage(), e); - } - } + namespaceAwareDocumentBuilder = documentBuilderFactory.newDocumentBuilder(); + } catch (ParserConfigurationException e) { + logger.error(e.getMessage(), e); + } + } - public static Document createDomDocument() { + public static Document createDomDocument() { - return documentBuilder.newDocument(); - } + return documentBuilder.newDocument(); + } - public static Document createNamespaceAwareDomDocument() { + public static Document createNamespaceAwareDomDocument() { - return namespaceAwareDocumentBuilder.newDocument(); - } + return namespaceAwareDocumentBuilder.newDocument(); + } - public static String toString(Document doc, String encoding, boolean indent) throws TransformerFactoryConfigurationError, TransformerException { - Source source = new DOMSource(doc); - StringWriter sw = new StringWriter(); - Result result = new StreamResult(sw); + public static String toString(Document doc, String encoding, boolean indent) throws TransformerFactoryConfigurationError, TransformerException { + Source source = new DOMSource(doc); + StringWriter sw = new StringWriter(); + Result result = new StreamResult(sw); - Transformer xformer = TransformerFactory.newInstance().newTransformer(); - xformer.setOutputProperty(OutputKeys.ENCODING, encoding); + Transformer xformer = TransformerFactory.newInstance().newTransformer(); + xformer.setOutputProperty(OutputKeys.ENCODING, encoding); - if (indent) { - xformer.setOutputProperty(OutputKeys.INDENT, "yes"); - } + if (indent) { + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + } - xformer.transform(source, result); + xformer.transform(source, result); - return sw.getBuffer().toString(); - } + return sw.getBuffer().toString(); + } - public static void toString(Document doc, String encoding, Writer w, boolean indent) throws TransformerFactoryConfigurationError, TransformerException { - Source source = new DOMSource(doc); - Result result = new StreamResult(w); + public static void toString(Document doc, String encoding, Writer w, boolean indent) throws TransformerFactoryConfigurationError, TransformerException { + Source source = new DOMSource(doc); + Result result = new StreamResult(w); - Transformer xformer = TransformerFactory.newInstance().newTransformer(); - xformer.setOutputProperty(OutputKeys.ENCODING, encoding); + Transformer xformer = TransformerFactory.newInstance().newTransformer(); + xformer.setOutputProperty(OutputKeys.ENCODING, encoding); - if (indent) { - xformer.setOutputProperty(OutputKeys.INDENT, "yes"); - } + if (indent) { + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + } - xformer.transform(source, result); - } + xformer.transform(source, result); + } - public static Document parseXmlFile(String filename, boolean validating, boolean namespaceAware) throws SAXException, IOException, ParserConfigurationException { + public static Document parseXmlFile(String filename, boolean validating, boolean namespaceAware) throws SAXException, IOException, ParserConfigurationException { - return parseXmlFile(new File(filename), validating, namespaceAware); - } + return parseXmlFile(new File(filename), validating, namespaceAware); + } - public static Document parseXmlFile(File file, boolean validating, boolean namespaceAware) throws SAXException, IOException, ParserConfigurationException { + public static Document parseXmlFile(File file, boolean validating, boolean namespaceAware) throws SAXException, IOException, ParserConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(namespaceAware); - factory.setValidating(validating); + factory.setNamespaceAware(namespaceAware); + factory.setValidating(validating); - Document doc = factory.newDocumentBuilder().parse(file); + Document doc = factory.newDocumentBuilder().parse(file); - return doc; - } + return doc; + } - public static Document parseXmlFile(URI uri, boolean validating) throws SAXException, IOException, ParserConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setValidating(validating); - Document doc = factory.newDocumentBuilder().parse(uri.toString()); - return doc; - } + public static Document parseXmlFile(URI uri, boolean validating) throws SAXException, IOException, ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setValidating(validating); + Document doc = factory.newDocumentBuilder().parse(uri.toString()); + return doc; + } - public static Document parseXmlFile(File f, boolean validating) throws SAXException, IOException, ParserConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setValidating(validating); - Document doc = factory.newDocumentBuilder().parse(f); - return doc; - } + public static Document parseXmlFile(File f, boolean validating) throws SAXException, IOException, ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setValidating(validating); + Document doc = factory.newDocumentBuilder().parse(f); + return doc; + } - public static Document parseXmlFile(InputStream stream, boolean validating) throws SAXException, IOException, ParserConfigurationException { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setValidating(validating); - Document doc = factory.newDocumentBuilder().parse(stream); - return doc; - } + public static Document parseXmlFile(InputStream stream, boolean validating) throws SAXException, IOException, ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setValidating(validating); + Document doc = factory.newDocumentBuilder().parse(stream); + return doc; + } - public static Element createElement(String name, Object value, Document doc) { - Element element = doc.createElement(name); - element.appendChild(doc.createTextNode(value.toString())); - return element; - } + public static Element createElement(String name, Object value, Document doc) { + Element element = doc.createElement(name); + element.appendChild(doc.createTextNode(value.toString())); + return element; + } - public static Element createCDATAElement(String name, Object value, Document doc) { - Element element = doc.createElement(name); - element.appendChild(doc.createCDATASection(value.toString())); - return element; - } + public static Element createCDATAElement(String name, Object value, Document doc) { + Element element = doc.createElement(name); + element.appendChild(doc.createCDATASection(value.toString())); + return element; + } - public static void writeXmlFile(Document doc, File file, boolean indent, String encoding) throws TransformerFactoryConfigurationError, TransformerException { - // Prepare the DOM document for writing - Source source = new DOMSource(doc); + public static void writeXmlFile(Document doc, File file, boolean indent, String encoding) throws TransformerFactoryConfigurationError, TransformerException { + // Prepare the DOM document for writing + Source source = new DOMSource(doc); - // Prepare the output file - Result result = new StreamResult(file); + // Prepare the output file + Result result = new StreamResult(file); - Transformer xformer = TransformerFactory.newInstance().newTransformer(); + Transformer xformer = TransformerFactory.newInstance().newTransformer(); - xformer.setOutputProperty(OutputKeys.ENCODING, encoding); - - if (indent) { - xformer.setOutputProperty(OutputKeys.INDENT, "yes"); - } + xformer.setOutputProperty(OutputKeys.ENCODING, encoding); - xformer.transform(source, result); + if (indent) { + xformer.setOutputProperty(OutputKeys.INDENT, "yes"); + } - } + xformer.transform(source, result); - public static void writeXmlFile(Document doc, File file, Entry... outputKeys) throws TransformerFactoryConfigurationError, TransformerException { - // Prepare the DOM document for writing - Source source = new DOMSource(doc); + } - // Prepare the output file - Result result = new StreamResult(file); + public static void writeXmlFile(Document doc, File file, Entry... outputKeys) throws TransformerFactoryConfigurationError, TransformerException { + // Prepare the DOM document for writing + Source source = new DOMSource(doc); - // Write the DOM document to the file - Transformer xformer = TransformerFactory.newInstance().newTransformer(); + // Prepare the output file + Result result = new StreamResult(file); - if(outputKeys != null){ + // Write the DOM document to the file + Transformer xformer = TransformerFactory.newInstance().newTransformer(); - for(Entry entry : outputKeys){ + if(outputKeys != null){ - xformer.setOutputProperty(entry.getKey(), entry.getValue()); - } - } + for(Entry entry : outputKeys){ - xformer.transform(source, result); + xformer.setOutputProperty(entry.getKey(), entry.getValue()); + } + } - } + xformer.transform(source, result); - public static void writeXmlFile(Document doc, String filename, boolean indent, String encoding) throws TransformerFactoryConfigurationError, TransformerException { + } - // Prepare the output file - File file = new File(filename); + public static void writeXmlFile(Document doc, String filename, boolean indent, String encoding) throws TransformerFactoryConfigurationError, TransformerException { + // Prepare the output file + File file = new File(filename); - writeXmlFile(doc, file, indent, encoding); - } + writeXmlFile(doc, file, indent, encoding); - public static void append(Document doc, Element targetElement, Collection beans) { + } - if (beans != null && !beans.isEmpty()) { + public static void append(Document doc, Element targetElement, Collection beans) { - for (XMLable xmlable : beans) { - targetElement.appendChild(xmlable.toXML(doc)); - } - } - } - - public static void append(Document doc, Element targetElement, String elementName, String subElementsName, Object[] values) { - - if(values != null){ - - Element subElement = doc.createElement(elementName); - targetElement.appendChild(subElement); - - for (Object value : values) { - - appendNewCDATAElement(doc, subElement, subElementsName, value); - } - } - } - - public static void append(Document doc, Element targetElement, String elementName, String subElementsName, List values) { - - if(values != null){ - - Element subElement = doc.createElement(elementName); - targetElement.appendChild(subElement); - - for (Object value : values) { - - appendNewCDATAElement(doc, subElement, subElementsName, value); - } - } - } - - public static void append(Document doc, Element targetElement, String elementName, Collection beans) { - - if (beans != null && !beans.isEmpty()) { - - Element subElement = doc.createElement(elementName); - targetElement.appendChild(subElement); - - for (XMLable xmlable : beans) { - subElement.appendChild(xmlable.toXML(doc)); - } - } - } - - public static void appendNewCDATAElement(Document doc, Element targetElement, String elementName, String value) { - - if(value != null){ - targetElement.appendChild(createCDATAElement(elementName, value, doc)); - } - } - - public static void appendNewElement(Document doc, Element targetElement, String elementName, String value) { - - if(value != null){ - targetElement.appendChild(createElement(elementName, value, doc)); - } - } - - public static void appendNewCDATAElement(Document doc, Element targetElement, String elementName, Object value) { - - if(value != null){ - appendNewCDATAElement(doc,targetElement,elementName,value.toString()); - } - } - - public static void appendNewElement(Document doc, Element targetElement, String elementName, Object value) { - - if(value != null){ - appendNewElement(doc,targetElement,elementName,value.toString()); - } - - } - - /** - * Adds or replaces node in parent. - * @param parent - * @param node - * @throws Exception - Node cannot exist more than once, - * i.e. multiple nodes with the same name cannot exist in parent. - */ - public static void replaceSingleNode(Element parent, final Node node) throws RuntimeException { - - NodeList nodes = parent.getElementsByTagName(node.getNodeName()); - - if(nodes.getLength() > 1) { - throw new RuntimeException("Parent element contains multiple nodes with the name " + node.getNodeName()); - } - if(nodes.getLength() == 0) { - parent.appendChild(node); - } else { - parent.replaceChild(node, nodes.item(0)); - } - } - - public enum TimeUnit { - HOUR, - MINUTE, - SECOND; - } - - public static Element getTimeUnits(Document doc, TimeUnit timeUnit) { - switch(timeUnit) { - case HOUR: - Element hoursElement = doc.createElement("hours"); - Element hourElement; - for(int i=0;i<10;++i) { - hourElement = doc.createElement("hour"); - XMLUtils.appendNewElement(doc, hourElement, "value", "0"+i); - hoursElement.appendChild(hourElement); - } - for(int i=10;i<24;++i) { - hourElement = doc.createElement("hour"); - XMLUtils.appendNewElement(doc, hourElement, "value", i); - hoursElement.appendChild(hourElement); - } - return hoursElement; - case MINUTE: - Element minutesElement = doc.createElement("minutes"); - Element minuteElement; - for(int i=0;i<10;++i) { - minuteElement = doc.createElement("minute"); - XMLUtils.appendNewElement(doc, minuteElement, "value", "0"+i); - minutesElement.appendChild(minuteElement); - } - for(int i=10;i<60;++i) { - minuteElement = doc.createElement("minute"); - XMLUtils.appendNewElement(doc, minuteElement, "value", i); - minutesElement.appendChild(minuteElement); - } - return minutesElement; - case SECOND: - Element secondsElement = doc.createElement("seconds"); - Element secondElement; - for(int i=0;i<10;++i) { - secondElement = doc.createElement("second"); - XMLUtils.appendNewElement(doc, secondElement, "value", "0"+i); - secondsElement.appendChild(secondElement); - } - for(int i=10;i<60;++i) { - secondElement = doc.createElement("second"); - XMLUtils.appendNewElement(doc, secondElement, "value", i); - secondsElement.appendChild(secondElement); - } - return secondsElement; - } - return null; - } + if (beans != null && !beans.isEmpty()) { + + for (XMLable xmlable : beans) { + targetElement.appendChild(xmlable.toXML(doc)); + } + } + } + + public static void append(Document doc, Element targetElement, String elementName, String subElementsName, Object[] values) { + + if(values != null){ + + Element subElement = doc.createElement(elementName); + targetElement.appendChild(subElement); + + for (Object value : values) { + + appendNewCDATAElement(doc, subElement, subElementsName, value); + } + } + } + + public static void append(Document doc, Element targetElement, String elementName, String subElementsName, List values) { + + if(values != null){ + + Element subElement = doc.createElement(elementName); + targetElement.appendChild(subElement); + + for (Object value : values) { + + appendNewCDATAElement(doc, subElement, subElementsName, value); + } + } + } + + public static void append(Document doc, Element targetElement, String elementName, Collection beans) { + + if (beans != null && !beans.isEmpty()) { + + Element subElement = doc.createElement(elementName); + targetElement.appendChild(subElement); + + for (XMLable xmlable : beans) { + subElement.appendChild(xmlable.toXML(doc)); + } + } + } + + public static void appendNewCDATAElement(Document doc, Element targetElement, String elementName, String value) { + + if(value != null){ + targetElement.appendChild(createCDATAElement(elementName, value, doc)); + } + } + + public static void appendNewElement(Document doc, Element targetElement, String elementName, String value) { + + if(value != null){ + targetElement.appendChild(createElement(elementName, value, doc)); + } + } + + public static void appendNewCDATAElement(Document doc, Element targetElement, String elementName, Object value) { + + if(value != null){ + appendNewCDATAElement(doc,targetElement,elementName,value.toString()); + } + } + + public static void appendNewElement(Document doc, Element targetElement, String elementName, Object value) { + + if(value != null){ + appendNewElement(doc,targetElement,elementName,value.toString()); + } + + } + + /** + * Adds or replaces node in parent. + * @param parent + * @param node + * @throws Exception - Node cannot exist more than once, + * i.e. multiple nodes with the same name cannot exist in parent. + */ + public static void replaceSingleNode(Element parent, final Node node) throws RuntimeException { + + NodeList nodes = parent.getElementsByTagName(node.getNodeName()); + + if(nodes.getLength() > 1) { + throw new RuntimeException("Parent element contains multiple nodes with the name " + node.getNodeName()); + } + if(nodes.getLength() == 0) { + parent.appendChild(node); + } else { + parent.replaceChild(node, nodes.item(0)); + } + } + + public enum TimeUnit { + HOUR, + MINUTE, + SECOND; + } + + public static Element getTimeUnits(Document doc, TimeUnit timeUnit) { + switch(timeUnit) { + case HOUR: + Element hoursElement = doc.createElement("hours"); + Element hourElement; + for(int i=0;i<10;++i) { + hourElement = doc.createElement("hour"); + XMLUtils.appendNewElement(doc, hourElement, "value", "0"+i); + hoursElement.appendChild(hourElement); + } + for(int i=10;i<24;++i) { + hourElement = doc.createElement("hour"); + XMLUtils.appendNewElement(doc, hourElement, "value", i); + hoursElement.appendChild(hourElement); + } + return hoursElement; + case MINUTE: + Element minutesElement = doc.createElement("minutes"); + Element minuteElement; + for(int i=0;i<10;++i) { + minuteElement = doc.createElement("minute"); + XMLUtils.appendNewElement(doc, minuteElement, "value", "0"+i); + minutesElement.appendChild(minuteElement); + } + for(int i=10;i<60;++i) { + minuteElement = doc.createElement("minute"); + XMLUtils.appendNewElement(doc, minuteElement, "value", i); + minutesElement.appendChild(minuteElement); + } + return minutesElement; + case SECOND: + Element secondsElement = doc.createElement("seconds"); + Element secondElement; + for(int i=0;i<10;++i) { + secondElement = doc.createElement("second"); + XMLUtils.appendNewElement(doc, secondElement, "value", "0"+i); + secondsElement.appendChild(secondElement); + } + for(int i=10;i<60;++i) { + secondElement = doc.createElement("second"); + XMLUtils.appendNewElement(doc, secondElement, "value", i); + secondsElement.appendChild(secondElement); + } + return secondsElement; + } + return null; + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLable.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLable.java index 6b35b27e7d9..3120d32a262 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLable.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/XMLable.java @@ -12,5 +12,5 @@ public interface XMLable { - Node toXML(Document doc); + Node toXML(Document doc); } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xml/XSLVariableReader.java b/eagledns/src/main/java/se/unlogic/standardutils/xml/XSLVariableReader.java index 13d56689155..86b01659088 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xml/XSLVariableReader.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xml/XSLVariableReader.java @@ -34,99 +34,99 @@ */ public class XSLVariableReader { - private final Document doc; - private final List subDocuments; + private final Document doc; + private final List subDocuments; - private final XPath xpath = XPathFactory.newInstance().newXPath();; + private final XPath xpath = XPathFactory.newInstance().newXPath();; - public XSLVariableReader(Document doc) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { + public XSLVariableReader(Document doc) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { - this.doc = doc; - subDocuments = this.getSubDocuments(doc, null); - } + this.doc = doc; + subDocuments = this.getSubDocuments(doc, null); + } - public XSLVariableReader(URI uri) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { + public XSLVariableReader(URI uri) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { - this.doc = XMLUtils.parseXmlFile(uri, false); - subDocuments = this.getSubDocuments(doc, null); - } + this.doc = XMLUtils.parseXmlFile(uri, false); + subDocuments = this.getSubDocuments(doc, null); + } - public XSLVariableReader(String filePath) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { + public XSLVariableReader(String filePath) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { - this.doc = XMLUtils.parseXmlFile(filePath, false, false); - subDocuments = this.getSubDocuments(doc, null); - } + this.doc = XMLUtils.parseXmlFile(filePath, false, false); + subDocuments = this.getSubDocuments(doc, null); + } - public XSLVariableReader(File file) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { + public XSLVariableReader(File file) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, URISyntaxException { - this.doc = XMLUtils.parseXmlFile(file, false); - subDocuments = this.getSubDocuments(doc, null); - } + this.doc = XMLUtils.parseXmlFile(file, false); + subDocuments = this.getSubDocuments(doc, null); + } - protected List getSubDocuments(Document doc, List subDocuments) throws SAXException, IOException, ParserConfigurationException, URISyntaxException, XPathExpressionException { + protected List getSubDocuments(Document doc, List subDocuments) throws SAXException, IOException, ParserConfigurationException, URISyntaxException, XPathExpressionException { - URI uri = new URI(doc.getBaseURI()); + URI uri = new URI(doc.getBaseURI()); - NodeList nodeList = (NodeList) xpath.evaluate("//import/@href | //include/@href", doc, XPathConstants.NODESET); + NodeList nodeList = (NodeList) xpath.evaluate("//import/@href | //include/@href", doc, XPathConstants.NODESET); - if (nodeList.getLength() > 0) { + if (nodeList.getLength() > 0) { - int index = 0; + int index = 0; - while (index < nodeList.getLength()) { + while (index < nodeList.getLength()) { - URI subURI = new URI(nodeList.item(index).getTextContent()); - - if (!subURI.isAbsolute()) { + URI subURI = new URI(nodeList.item(index).getTextContent()); - subURI = new URL(uri.toURL(),nodeList.item(index).getTextContent()).toURI(); - } + if (!subURI.isAbsolute()) { - if (subURI.toString().startsWith(ClassPathURIResolver.PREFIX) && subURI.toString().length() > ClassPathURIResolver.PREFIX.length()) { + subURI = new URL(uri.toURL(),nodeList.item(index).getTextContent()).toURI(); + } - subURI = ClassPathURIResolver.getURL(subURI.toString()).toURI(); - } + if (subURI.toString().startsWith(ClassPathURIResolver.PREFIX) && subURI.toString().length() > ClassPathURIResolver.PREFIX.length()) { - Document subDoc = XMLUtils.parseXmlFile(subURI, false); + subURI = ClassPathURIResolver.getURL(subURI.toString()).toURI(); + } - if (subDocuments == null) { + Document subDoc = XMLUtils.parseXmlFile(subURI, false); - subDocuments = new ArrayList(); - } + if (subDocuments == null) { - subDocuments.add(subDoc); + subDocuments = new ArrayList(); + } - this.getSubDocuments(subDoc, subDocuments); + subDocuments.add(subDoc); - index++; - } - } + this.getSubDocuments(subDoc, subDocuments); - return subDocuments; - } + index++; + } + } - public String getValue(String name) { + return subDocuments; + } - try { - String response = this.xpath.evaluate("//variable[@name='" + name + "']/text()", this.doc.getDocumentElement()); + public String getValue(String name) { - if (subDocuments != null && StringUtils.isEmpty(response)) { + try { + String response = this.xpath.evaluate("//variable[@name='" + name + "']/text()", this.doc.getDocumentElement()); - for (Document document : subDocuments) { + if (subDocuments != null && StringUtils.isEmpty(response)) { - response = this.xpath.evaluate("//variable[@name='" + name + "']/text()", document.getDocumentElement()); + for (Document document : subDocuments) { - if (!StringUtils.isEmpty(response)) { + response = this.xpath.evaluate("//variable[@name='" + name + "']/text()", document.getDocumentElement()); - return response; - } - } - } + if (!StringUtils.isEmpty(response)) { - return response; + return response; + } + } + } - } catch (XPathExpressionException e) { - return null; - } - } + return response; + + } catch (XPathExpressionException e) { + return null; + } + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/xsl/XSLUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/xsl/XSLUtils.java index d03b36e3e9f..7bd61fb6d38 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/xsl/XSLUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/xsl/XSLUtils.java @@ -21,56 +21,56 @@ public class XSLUtils { - private static Pattern XSL_VARIABLE_PATTERN = Pattern.compile("(?<=\\$)[\\w\\.]*(?=($|[\\W]))"); - - /** - * Scans XSL documents for references to XSL variables such as {@literal <}xsl:value-of select="$foo"/{@literal>} and {@literal <}a href="{$foo}"/{@literal >}. Returns the variable names. - * - * @param file Input XSL file - * @return - * @throws SAXException - * @throws IOException - * @throws ParserConfigurationException - */ - public static Set getVariableReferenses(File file) throws SAXException, IOException, ParserConfigurationException { - - XMLSettingNode settingNode = new XMLSettingNode(file); - - List tags = settingNode.getStrings("//@*[contains(.,'$')]"); - - if(tags == null){ - - return null; - } - - LinkedHashSet stringSet = new LinkedHashSet(); - - for (String tag : tags) { - - Matcher matcher = XSL_VARIABLE_PATTERN.matcher(tag); - - while (matcher.find()) { - - stringSet.add(matcher.group()); - } - } - - return stringSet; - } - - /** - * Scans XSL documents for declared XSL variables such as {@literal <}xsl:variable name="myvariable"/{@literal>} - * - * @param file Input XSL file - * @return - * @throws SAXException - * @throws IOException - * @throws ParserConfigurationException - */ - public static List getDeclaredVariables(File file) throws SAXException, IOException, ParserConfigurationException { - - XMLSettingNode settingNode = new XMLSettingNode(file); - - return settingNode.getStrings("//variable/@name"); - } + private static Pattern XSL_VARIABLE_PATTERN = Pattern.compile("(?<=\\$)[\\w\\.]*(?=($|[\\W]))"); + + /** + * Scans XSL documents for references to XSL variables such as {@literal <}xsl:value-of select="$foo"/{@literal>} and {@literal <}a href="{$foo}"/{@literal >}. Returns the variable names. + * + * @param file Input XSL file + * @return + * @throws SAXException + * @throws IOException + * @throws ParserConfigurationException + */ + public static Set getVariableReferenses(File file) throws SAXException, IOException, ParserConfigurationException { + + XMLSettingNode settingNode = new XMLSettingNode(file); + + List tags = settingNode.getStrings("//@*[contains(.,'$')]"); + + if(tags == null){ + + return null; + } + + LinkedHashSet stringSet = new LinkedHashSet(); + + for (String tag : tags) { + + Matcher matcher = XSL_VARIABLE_PATTERN.matcher(tag); + + while (matcher.find()) { + + stringSet.add(matcher.group()); + } + } + + return stringSet; + } + + /** + * Scans XSL documents for declared XSL variables such as {@literal <}xsl:variable name="myvariable"/{@literal>} + * + * @param file Input XSL file + * @return + * @throws SAXException + * @throws IOException + * @throws ParserConfigurationException + */ + public static List getDeclaredVariables(File file) throws SAXException, IOException, ParserConfigurationException { + + XMLSettingNode settingNode = new XMLSettingNode(file); + + return settingNode.getStrings("//variable/@name"); + } } diff --git a/eagledns/src/main/java/se/unlogic/standardutils/zip/ZipUtils.java b/eagledns/src/main/java/se/unlogic/standardutils/zip/ZipUtils.java index 27ef95aeb32..1a37ed9b8ab 100644 --- a/eagledns/src/main/java/se/unlogic/standardutils/zip/ZipUtils.java +++ b/eagledns/src/main/java/se/unlogic/standardutils/zip/ZipUtils.java @@ -11,31 +11,31 @@ public class ZipUtils { - public static void addFile(File file, ZipOutputStream outputStream) throws IOException{ - - ZipEntry zipEntry = new ZipEntry(file.getName()); - - FileInputStream inputStream = null; - - try{ - inputStream = new FileInputStream(file); - - outputStream.putNextEntry(zipEntry); - - StreamUtils.transfer(inputStream, outputStream); - - outputStream.closeEntry(); - }finally{ - - StreamUtils.closeStream(inputStream); - } - } - - public static void addFiles(File[] files, ZipOutputStream outputStream) throws IOException{ - - for(File file : files){ - - addFile(file, outputStream); - } - } + public static void addFile(File file, ZipOutputStream outputStream) throws IOException{ + + ZipEntry zipEntry = new ZipEntry(file.getName()); + + FileInputStream inputStream = null; + + try{ + inputStream = new FileInputStream(file); + + outputStream.putNextEntry(zipEntry); + + StreamUtils.transfer(inputStream, outputStream); + + outputStream.closeEntry(); + }finally{ + + StreamUtils.closeStream(inputStream); + } + } + + public static void addFiles(File[] files, ZipOutputStream outputStream) throws IOException{ + + for(File file : files){ + + addFile(file, outputStream); + } + } } diff --git a/profiling-tests/src/test/java/org/jboss/resteasy/test/profiling/MockedProfilingTest.java b/profiling-tests/src/test/java/org/jboss/resteasy/test/profiling/MockedProfilingTest.java index 612a582cb8c..3d4a52ecd45 100755 --- a/profiling-tests/src/test/java/org/jboss/resteasy/test/profiling/MockedProfilingTest.java +++ b/profiling-tests/src/test/java/org/jboss/resteasy/test/profiling/MockedProfilingTest.java @@ -66,13 +66,13 @@ public void testCleartext() throws Exception MockHttpResponse response = new MockHttpResponse(); MockHttpRequest request = MockHttpRequest.post("/test/create") - .header(HttpHeaders.CONTENT_LANGUAGE, "en") - .header(HttpHeaders.USER_AGENT, "mozilla") - .header("Custom-Header1", "mozilla") - .header("Custom-Header2", "mozilla") - .header("Custom-Header3", "mozilla") - .header("Custom-Header4", "mozilla") - .contentType(MediaType.TEXT_PLAIN); + .header(HttpHeaders.CONTENT_LANGUAGE, "en") + .header(HttpHeaders.USER_AGENT, "mozilla") + .header("Custom-Header1", "mozilla") + .header("Custom-Header2", "mozilla") + .header("Custom-Header3", "mozilla") + .header("Custom-Header4", "mozilla") + .contentType(MediaType.TEXT_PLAIN); ByteArrayInputStream stream = new ByteArrayInputStream("hello".getBytes()); request.setInputStream(stream); diff --git a/providers/abdera-atom/src/test/java/org/jboss/resteasy/test/providers/atom/Customer.java b/providers/abdera-atom/src/test/java/org/jboss/resteasy/test/providers/atom/Customer.java index 91f585d4138..6fe04fd6a0d 100644 --- a/providers/abdera-atom/src/test/java/org/jboss/resteasy/test/providers/atom/Customer.java +++ b/providers/abdera-atom/src/test/java/org/jboss/resteasy/test/providers/atom/Customer.java @@ -31,4 +31,4 @@ public void setName(String name) { this.name = name; } -} \ No newline at end of file +} diff --git a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetCollectionProvider.java b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetCollectionProvider.java index ce17c889a39..4404aad76b6 100644 --- a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetCollectionProvider.java +++ b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetCollectionProvider.java @@ -14,8 +14,8 @@ @Produces({"application/fastinfoset", "application/*+fastinfoset"}) public class FastInfosetCollectionProvider extends CollectionProvider { - @Override - protected boolean needsSecurity() { - return false; - } + @Override + protected boolean needsSecurity() { + return false; + } } diff --git a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetMapProvider.java b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetMapProvider.java index 30f0c47a695..148e470cc36 100644 --- a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetMapProvider.java +++ b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastInfosetMapProvider.java @@ -14,8 +14,8 @@ @Produces({"application/fastinfoset", "application/*+fastinfoset"}) public class FastInfosetMapProvider extends MapProvider { - @Override - protected boolean needsSecurity() { - return false; - } + @Override + protected boolean needsSecurity() { + return false; + } } diff --git a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetContext.java b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetContext.java index d9a81ebdd0f..b6064483875 100644 --- a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetContext.java +++ b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetContext.java @@ -55,4 +55,4 @@ public Validator createValidator() throws JAXBException } -} \ No newline at end of file +} diff --git a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetMarshaller.java b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetMarshaller.java index e82637948fd..708aee47c75 100644 --- a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetMarshaller.java +++ b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetMarshaller.java @@ -46,27 +46,27 @@ protected static XMLStreamWriter getFastinfoSetXMLStreamWriter(OutputStream enti } public void marshal(Object o, Result result) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public void marshal(Object o, OutputStream outputStream) - throws JAXBException + throws JAXBException { marshal(o, getFastinfoSetXMLStreamWriter(outputStream)); } public void marshal(Object o, File file) - throws JAXBException + throws JAXBException { try { OutputStream os = new FileOutputStream(file); try { - marshal(o, os); + marshal(o, os); } finally { - os.close(); + os.close(); } } catch (IOException e) @@ -76,61 +76,61 @@ public void marshal(Object o, File file) } public void marshal(Object o, Writer writer) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public void marshal(Object o, ContentHandler contentHandler) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public void marshal(Object o, Node node) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public void marshal(Object o, XMLStreamWriter xmlStreamWriter) - throws JAXBException + throws JAXBException { marshaller.marshal(o, xmlStreamWriter); } public void marshal(Object o, XMLEventWriter xmlEventWriter) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public Node getNode(Object o) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public void setProperty(String s, Object o) - throws PropertyException + throws PropertyException { marshaller.setProperty(s, o); } public Object getProperty(String s) - throws PropertyException + throws PropertyException { return marshaller.getProperty(s); } public void setEventHandler(ValidationEventHandler validationEventHandler) - throws JAXBException + throws JAXBException { marshaller.setEventHandler(validationEventHandler); } public ValidationEventHandler getEventHandler() - throws JAXBException + throws JAXBException { return marshaller.getEventHandler(); } @@ -179,4 +179,4 @@ public Listener getListener() { return marshaller.getListener(); } -} \ No newline at end of file +} diff --git a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetUnmarshaller.java b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetUnmarshaller.java index 9f66f66cd71..fb79363ac51 100644 --- a/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetUnmarshaller.java +++ b/providers/fastinfoset/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/fastinfoset/FastinfoSetUnmarshaller.java @@ -51,7 +51,7 @@ protected static XMLStreamReader getFastinfoSetXMLStreamReader(InputStream entit } public Object unmarshal(File file) - throws JAXBException + throws JAXBException { try { @@ -64,19 +64,19 @@ public Object unmarshal(File file) } public Object unmarshal(InputStream inputStream) - throws JAXBException + throws JAXBException { return unmarshal(getFastinfoSetXMLStreamReader(inputStream)); } public Object unmarshal(Reader reader) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public Object unmarshal(URL url) - throws JAXBException + throws JAXBException { try { @@ -89,25 +89,25 @@ public Object unmarshal(URL url) } public Object unmarshal(InputSource inputSource) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public Object unmarshal(Node node) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public JAXBElement unmarshal(Node node, Class tClass) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public Object unmarshal(Source source) - throws JAXBException + throws JAXBException { if (!(source instanceof StreamSource)) throw new UnsupportedOperationException(Messages.MESSAGES.expectingStreamSource()); StreamSource stream = (StreamSource) source; @@ -116,7 +116,7 @@ public Object unmarshal(Source source) } public JAXBElement unmarshal(Source source, Class tClass) - throws JAXBException + throws JAXBException { if (!(source instanceof StreamSource)) throw new UnsupportedOperationException(Messages.MESSAGES.expectingStreamSource()); StreamSource stream = (StreamSource) source; @@ -125,25 +125,25 @@ public JAXBElement unmarshal(Source source, Class tClass) } public Object unmarshal(XMLStreamReader xmlStreamReader) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlStreamReader); } public JAXBElement unmarshal(XMLStreamReader xmlStreamReader, Class tClass) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlStreamReader, tClass); } public Object unmarshal(XMLEventReader xmlEventReader) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } public JAXBElement unmarshal(XMLEventReader xmlEventReader, Class tClass) - throws JAXBException + throws JAXBException { throw new UnsupportedOperationException(); } @@ -155,38 +155,38 @@ public UnmarshallerHandler getUnmarshallerHandler() @SuppressWarnings("deprecation") public void setValidating(boolean b) - throws JAXBException + throws JAXBException { unmarshaller.setValidating(b); } @SuppressWarnings("deprecation") public boolean isValidating() - throws JAXBException + throws JAXBException { return unmarshaller.isValidating(); } public void setEventHandler(ValidationEventHandler validationEventHandler) - throws JAXBException + throws JAXBException { unmarshaller.setEventHandler(validationEventHandler); } public ValidationEventHandler getEventHandler() - throws JAXBException + throws JAXBException { return unmarshaller.getEventHandler(); } public void setProperty(String s, Object o) - throws PropertyException + throws PropertyException { unmarshaller.setProperty(s, o); } public Object getProperty(String s) - throws PropertyException + throws PropertyException { return unmarshaller.getProperty(s); } @@ -235,4 +235,4 @@ public Listener getListener() { return unmarshaller.getListener(); } -} \ No newline at end of file +} diff --git a/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/JacksonJsonpInterceptor.java b/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/JacksonJsonpInterceptor.java index 4792b3215f1..8c0f4c01090 100644 --- a/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/JacksonJsonpInterceptor.java +++ b/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/JacksonJsonpInterceptor.java @@ -41,156 +41,156 @@ @Deprecated public class JacksonJsonpInterceptor implements WriterInterceptor{ - /** - * "text/javascript" media type. Default media type of script tags. - */ - public static final MediaType TEXT_JAVASCRIPT_MEDIA_TYPE = new MediaType("text", "javascript"); - - /** - * "application/javascript" media type. - */ - public static final MediaType APPLICATION_JAVASCRIPT_MEDIA_TYPE = new MediaType("application", "javascript"); - - /** - * "text/json" media type. - */ - public static final MediaType TEXT_JSON_TYPE = new MediaType("text", "json"); - - /** - * "application/*+json" media type. - */ - public static final MediaType APPLICATION_PLUS_JSON_TYPE = new MediaType("application", "*+json"); - - /** - * Default name of the query parameter with the method name. - */ - public static final String DEFAULT_CALLBACK_QUERY_PARAMETER = "callback"; - - /** - * If response media type is one of this jsonp response may be created. - */ - public static final MediaTypeMap jsonpCompatibleMediaTypes = new MediaTypeMap(); - - /** - * Default {@link ObjectMapper} for type resolution. Used if none is provided by {@link Providers}. - */ - protected static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper(); - - static { - jsonpCompatibleMediaTypes.add(MediaType.APPLICATION_JSON_TYPE , MediaType.APPLICATION_JSON_TYPE.toString()); - jsonpCompatibleMediaTypes.add(APPLICATION_JAVASCRIPT_MEDIA_TYPE, APPLICATION_JAVASCRIPT_MEDIA_TYPE.toString()); - jsonpCompatibleMediaTypes.add(APPLICATION_PLUS_JSON_TYPE , APPLICATION_PLUS_JSON_TYPE.toString()); - jsonpCompatibleMediaTypes.add(TEXT_JSON_TYPE , TEXT_JSON_TYPE.toString()); - jsonpCompatibleMediaTypes.add(TEXT_JAVASCRIPT_MEDIA_TYPE , TEXT_JAVASCRIPT_MEDIA_TYPE.toString()); - } - - private UriInfo uri; - - private String callbackQueryParameter = DEFAULT_CALLBACK_QUERY_PARAMETER; - - /** - * The {@link ObjectMapper} used to create typing information. - */ - protected ObjectMapper objectMapper; - - /** - * The {@link Providers} used to retrieve the {@link #objectMapper} from. - */ - protected Providers providers; - - /** - * {@inheritDoc} - */ - @Override - public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { - LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName()); - String function = uri.getQueryParameters().getFirst(callbackQueryParameter); - if (function != null && !function.trim().isEmpty() && !jsonpCompatibleMediaTypes.getPossible(context.getMediaType()).isEmpty()){ - OutputStreamWriter writer = new OutputStreamWriter(context.getOutputStream()); - - writer.write(function + "("); - writer.flush(); - context.proceed(); - writer.write(")"); - writer.flush(); - } else { - context.proceed(); - } - } - - /** - * Search for an {@link ObjectMapper} for the given class and mediaType - * - * @param type the {@link Class} to serialize - * @param mediaType the response {@link MediaType} - * @return the {@link ObjectMapper} - */ - protected ObjectMapper getObjectMapper(Class type, MediaType mediaType) - { - if (objectMapper != null) { - return objectMapper; - } - - if (providers != null) { - ContextResolver resolver = providers.getContextResolver(ObjectMapper.class, mediaType); - if (resolver == null) { - resolver = providers.getContextResolver(ObjectMapper.class, null); - } - if (resolver != null) { - return resolver.getContext(type); - } - } - - return DEFAULT_MAPPER; - } - - - /** - * Setter used by RESTeasy to provide the {@link UriInfo}. - * - * @param uri the uri to set - */ - @Context - public void setUri(UriInfo uri) { - this.uri = uri; - } - - /** - * Setter used by RESTeasy to provide the {@link Providers} - * - * @param providers - */ - @Context - public void setProviders(Providers providers) { - this.providers = providers; - } - - /** - * Set an fix {@link ObjectMapper}. If this is not set {@link Providers} are used for lookup. If there are is none too, use a default one. - * - * @param objectMapper - */ - public void setObjectMapper(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } - - /** - * Get the name of the query parameter which contains the JavaScript method name. Default: callback. - * - * @return the callbackQueryParameter - */ - public String getCallbackQueryParameter() { - return callbackQueryParameter; - } - - /** - * Set callback query parameter. - * - * @see #getCallbackQueryParameter() - * @param callbackQueryParameter the callbackQueryParameter to set - */ - public void setCallbackQueryParameter(String callbackQueryParameter) { - this.callbackQueryParameter = callbackQueryParameter; - } + /** + * "text/javascript" media type. Default media type of script tags. + */ + public static final MediaType TEXT_JAVASCRIPT_MEDIA_TYPE = new MediaType("text", "javascript"); + + /** + * "application/javascript" media type. + */ + public static final MediaType APPLICATION_JAVASCRIPT_MEDIA_TYPE = new MediaType("application", "javascript"); + + /** + * "text/json" media type. + */ + public static final MediaType TEXT_JSON_TYPE = new MediaType("text", "json"); + + /** + * "application/*+json" media type. + */ + public static final MediaType APPLICATION_PLUS_JSON_TYPE = new MediaType("application", "*+json"); + + /** + * Default name of the query parameter with the method name. + */ + public static final String DEFAULT_CALLBACK_QUERY_PARAMETER = "callback"; + + /** + * If response media type is one of this jsonp response may be created. + */ + public static final MediaTypeMap jsonpCompatibleMediaTypes = new MediaTypeMap(); + + /** + * Default {@link ObjectMapper} for type resolution. Used if none is provided by {@link Providers}. + */ + protected static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper(); + + static { + jsonpCompatibleMediaTypes.add(MediaType.APPLICATION_JSON_TYPE , MediaType.APPLICATION_JSON_TYPE.toString()); + jsonpCompatibleMediaTypes.add(APPLICATION_JAVASCRIPT_MEDIA_TYPE, APPLICATION_JAVASCRIPT_MEDIA_TYPE.toString()); + jsonpCompatibleMediaTypes.add(APPLICATION_PLUS_JSON_TYPE , APPLICATION_PLUS_JSON_TYPE.toString()); + jsonpCompatibleMediaTypes.add(TEXT_JSON_TYPE , TEXT_JSON_TYPE.toString()); + jsonpCompatibleMediaTypes.add(TEXT_JAVASCRIPT_MEDIA_TYPE , TEXT_JAVASCRIPT_MEDIA_TYPE.toString()); + } + + private UriInfo uri; + + private String callbackQueryParameter = DEFAULT_CALLBACK_QUERY_PARAMETER; + + /** + * The {@link ObjectMapper} used to create typing information. + */ + protected ObjectMapper objectMapper; + + /** + * The {@link Providers} used to retrieve the {@link #objectMapper} from. + */ + protected Providers providers; + + /** + * {@inheritDoc} + */ + @Override + public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { + LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName()); + String function = uri.getQueryParameters().getFirst(callbackQueryParameter); + if (function != null && !function.trim().isEmpty() && !jsonpCompatibleMediaTypes.getPossible(context.getMediaType()).isEmpty()){ + OutputStreamWriter writer = new OutputStreamWriter(context.getOutputStream()); + + writer.write(function + "("); + writer.flush(); + context.proceed(); + writer.write(")"); + writer.flush(); + } else { + context.proceed(); + } + } + + /** + * Search for an {@link ObjectMapper} for the given class and mediaType + * + * @param type the {@link Class} to serialize + * @param mediaType the response {@link MediaType} + * @return the {@link ObjectMapper} + */ + protected ObjectMapper getObjectMapper(Class type, MediaType mediaType) + { + if (objectMapper != null) { + return objectMapper; + } + + if (providers != null) { + ContextResolver resolver = providers.getContextResolver(ObjectMapper.class, mediaType); + if (resolver == null) { + resolver = providers.getContextResolver(ObjectMapper.class, null); + } + if (resolver != null) { + return resolver.getContext(type); + } + } + + return DEFAULT_MAPPER; + } + + + /** + * Setter used by RESTeasy to provide the {@link UriInfo}. + * + * @param uri the uri to set + */ + @Context + public void setUri(UriInfo uri) { + this.uri = uri; + } + + /** + * Setter used by RESTeasy to provide the {@link Providers} + * + * @param providers + */ + @Context + public void setProviders(Providers providers) { + this.providers = providers; + } + + /** + * Set an fix {@link ObjectMapper}. If this is not set {@link Providers} are used for lookup. If there are is none too, use a default one. + * + * @param objectMapper + */ + public void setObjectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + /** + * Get the name of the query parameter which contains the JavaScript method name. Default: callback. + * + * @return the callbackQueryParameter + */ + public String getCallbackQueryParameter() { + return callbackQueryParameter; + } + + /** + * Set callback query parameter. + * + * @see #getCallbackQueryParameter() + * @param callbackQueryParameter the callbackQueryParameter to set + */ + public void setCallbackQueryParameter(String callbackQueryParameter) { + this.callbackQueryParameter = callbackQueryParameter; + } } diff --git a/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJacksonProvider.java b/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJacksonProvider.java index f43d320e3e2..b32c444580a 100644 --- a/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJacksonProvider.java +++ b/providers/jackson/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJacksonProvider.java @@ -25,9 +25,9 @@ @Deprecated public class ResteasyJacksonProvider extends JacksonJsonProvider { - public ResteasyJacksonProvider() { - super(Annotations.JACKSON, Annotations.JAXB); - } + public ResteasyJacksonProvider() { + super(Annotations.JACKSON, Annotations.JAXB); + } @Override public boolean isReadable(Class aClass, Type type, Annotation[] annotations, MediaType mediaType) diff --git a/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/JacksonTest.java b/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/JacksonTest.java index a9967999963..e6fda3989c9 100644 --- a/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/JacksonTest.java +++ b/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/JacksonTest.java @@ -43,7 +43,7 @@ public class JacksonTest extends BaseResourceTest { - private static final Logger LOG = Logger.getLogger(JacksonTest.class); + private static final Logger LOG = Logger.getLogger(JacksonTest.class); public static class Product { @@ -210,7 +210,7 @@ public static void setUp() throws Exception dispatcher.getRegistry().addPerRequestResource(JacksonService.class); dispatcher.getRegistry().addPerRequestResource(XmlService.class); dispatcher.getRegistry().addPerRequestResource(JAXBService.class); - client = new ResteasyClientBuilder().build(); + client = new ResteasyClientBuilder().build(); } @@ -298,95 +298,95 @@ public void testJacksonProxy() throws Exception Assert.assertEquals("Stuff", p.getName()); } - @XmlRootElement - public static class XmlResourceWithJAXB { - String attr1; - String attr2; + @XmlRootElement + public static class XmlResourceWithJAXB { + String attr1; + String attr2; - @XmlElement(name = "attr_1") - public String getAttr1() { + @XmlElement(name = "attr_1") + public String getAttr1() { return attr1; - } + } - public void setAttr1(String attr1) { + public void setAttr1(String attr1) { this.attr1 = attr1; - } + } - @XmlElement - public String getAttr2() { + @XmlElement + public String getAttr2() { return attr2; - } + } - public void setAttr2(String attr2) { + public void setAttr2(String attr2) { this.attr2 = attr2; - } - } + } + } - public static class XmlResourceWithJacksonAnnotation { - String attr1; - String attr2; + public static class XmlResourceWithJacksonAnnotation { + String attr1; + String attr2; - @JsonProperty("attr_1") - public String getAttr1() { + @JsonProperty("attr_1") + public String getAttr1() { return attr1; - } + } - public void setAttr1(String attr1) { + public void setAttr1(String attr1) { this.attr1 = attr1; - } + } - @XmlElement - public String getAttr2() { + @XmlElement + public String getAttr2() { return attr2; - } + } - public void setAttr2(String attr2) { + public void setAttr2(String attr2) { this.attr2 = attr2; - } - } + } + } - @Path("/jaxb") - public static class JAXBService { + @Path("/jaxb") + public static class JAXBService { - @GET - @Produces("application/json") - public XmlResourceWithJAXB getJAXBResource() { + @GET + @Produces("application/json") + public XmlResourceWithJAXB getJAXBResource() { XmlResourceWithJAXB resourceWithJAXB = new XmlResourceWithJAXB(); resourceWithJAXB.setAttr1("XXX"); resourceWithJAXB.setAttr2("YYY"); return resourceWithJAXB; - } + } - @GET - @Path(("/json")) - @Produces("application/json") - public XmlResourceWithJacksonAnnotation getJacksonAnnotatedResource() { + @GET + @Path(("/json")) + @Produces("application/json") + public XmlResourceWithJacksonAnnotation getJacksonAnnotatedResource() { XmlResourceWithJacksonAnnotation resource = new XmlResourceWithJacksonAnnotation(); resource.setAttr1("XXX"); resource.setAttr2("YYY"); return resource; - } + } - } + } - @Test - public void testJacksonJAXB() throws Exception { - { + @Test + public void testJacksonJAXB() throws Exception { + { DefaultHttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(generateBaseUrl() + "/jaxb"); HttpResponse response = client.execute(get); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); Assert.assertTrue(reader.readLine().contains("attr_1")); - } + } - { + { DefaultHttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(generateBaseUrl() + "/jaxb/json"); HttpResponse response = client.execute(get); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); Assert.assertTrue(reader.readLine().contains("attr_1")); - } + } - } + } } diff --git a/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/ProxyWithGenericReturnTypeJacksonTest.java b/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/ProxyWithGenericReturnTypeJacksonTest.java index 00c20f68082..a83d8a30c99 100644 --- a/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/ProxyWithGenericReturnTypeJacksonTest.java +++ b/providers/jackson/src/test/java/org/jboss/resteasy/test/nextgen/providers/jackson/ProxyWithGenericReturnTypeJacksonTest.java @@ -34,50 +34,50 @@ */ public class ProxyWithGenericReturnTypeJacksonTest { - private static final Logger LOG = Logger.getLogger(ProxyWithGenericReturnTypeJacksonTest.class); + private static final Logger LOG = Logger.getLogger(ProxyWithGenericReturnTypeJacksonTest.class); protected ResteasyDeployment deployment; @JsonTypeInfo(use = Id.NAME, include = As.PROPERTY, property = "type") @JsonSubTypes({ - @JsonSubTypes.Type(value = Type1.class, name = "type1"), - @JsonSubTypes.Type(value = Type2.class, name = "type2")}) + @JsonSubTypes.Type(value = Type1.class, name = "type1"), + @JsonSubTypes.Type(value = Type2.class, name = "type2")}) public abstract static class AbstractParent { - - protected long id; + + protected long id; - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } } public static class Type1 extends AbstractParent { - protected String name; + protected String name; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } public static class Type2 extends AbstractParent { - protected String note; + protected String note; - public String getNote() { - return note; - } + public String getNote() { + return note; + } - public void setNote(String note) { - this.note = note; - } + public void setNote(String note) { + this.note = note; + } } public interface TestSubResourceIntf @@ -107,24 +107,24 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl LOG.info("generic return type: " + method.getGenericReturnType()); LOG.info("type of return type: " + method.getGenericReturnType().getClass()); if ("resourceMethod".equals(method.getName())) { - List l = new ArrayList(); - Type1 first = new Type1(); - first.setId(1); - first.setName("MyName"); - l.add(first); - - Type2 second = new Type2(); - second.setId(2); - second.setNote("MyNote"); - l.add(second); - return l; + List l = new ArrayList(); + Type1 first = new Type1(); + first.setId(1); + first.setName("MyName"); + l.add(first); + + Type2 second = new Type2(); + second.setId(2); + second.setNote("MyNote"); + l.add(second); + return l; } if ("resourceMethodOne".equals(method.getName())) { - Type1 first = new Type1(); - first.setId(1); - first.setName("MyName"); - return first; + Type1 first = new Type1(); + first.setId(1); + first.setName("MyName"); + return first; } return null; @@ -160,27 +160,27 @@ public void after() throws Exception deployment = null; } - @Test - public void test() throws Exception - { - ResteasyClient client = new ResteasyClientBuilder().build(); - WebTarget target = client.target("http://localhost:8081/test/one/"); - LOG.info("Sending request"); - Response response = target.request().get(); - String entity = response.readEntity(String.class); - LOG.info("Received response: " + entity); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue("Type property is missing.", entity.contains("type")); - response.close(); + @Test + public void test() throws Exception + { + ResteasyClient client = new ResteasyClientBuilder().build(); + WebTarget target = client.target("http://localhost:8081/test/one/"); + LOG.info("Sending request"); + Response response = target.request().get(); + String entity = response.readEntity(String.class); + LOG.info("Received response: " + entity); + Assert.assertEquals(200, response.getStatus()); + Assert.assertTrue("Type property is missing.", entity.contains("type")); + response.close(); - target = client.target("http://localhost:8081/test/list/"); - LOG.info("Sending request"); - response = target.request().get(); - entity = response.readEntity(String.class); - LOG.info("Received response: " + entity); - Assert.assertEquals(200, response.getStatus()); - Assert.assertTrue("Type property is missing.", entity.contains("type")); - response.close(); - client.close(); - } -} \ No newline at end of file + target = client.target("http://localhost:8081/test/list/"); + LOG.info("Sending request"); + response = target.request().get(); + entity = response.readEntity(String.class); + LOG.info("Received response: " + entity); + Assert.assertEquals(200, response.getStatus()); + Assert.assertTrue("Type property is missing.", entity.contains("type")); + response.close(); + client.close(); + } +} diff --git a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/Jackson2JsonpInterceptor.java b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/Jackson2JsonpInterceptor.java index 96e9f45d159..aaa71ec6dc5 100755 --- a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/Jackson2JsonpInterceptor.java +++ b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/Jackson2JsonpInterceptor.java @@ -57,220 +57,220 @@ @ConstrainedTo(RuntimeType.SERVER) public class Jackson2JsonpInterceptor implements WriterInterceptor{ - /** - * "text/javascript" media type. Default media type of script tags. - */ - public static final MediaType TEXT_JAVASCRIPT_MEDIA_TYPE = new MediaType("text", "javascript"); + /** + * "text/javascript" media type. Default media type of script tags. + */ + public static final MediaType TEXT_JAVASCRIPT_MEDIA_TYPE = new MediaType("text", "javascript"); - /** - * "application/javascript" media type. - */ - public static final MediaType APPLICATION_JAVASCRIPT_MEDIA_TYPE = new MediaType("application", "javascript"); + /** + * "application/javascript" media type. + */ + public static final MediaType APPLICATION_JAVASCRIPT_MEDIA_TYPE = new MediaType("application", "javascript"); - /** - * "text/json" media type. - */ - public static final MediaType TEXT_JSON_TYPE = new MediaType("text", "json"); + /** + * "text/json" media type. + */ + public static final MediaType TEXT_JSON_TYPE = new MediaType("text", "json"); - /** - * "application/*+json" media type. - */ - public static final MediaType APPLICATION_PLUS_JSON_TYPE = new MediaType("application", "*+json"); + /** + * "application/*+json" media type. + */ + public static final MediaType APPLICATION_PLUS_JSON_TYPE = new MediaType("application", "*+json"); - /** - * Default name of the query parameter with the method name. - */ - public static final String DEFAULT_CALLBACK_QUERY_PARAMETER = "callback"; + /** + * Default name of the query parameter with the method name. + */ + public static final String DEFAULT_CALLBACK_QUERY_PARAMETER = "callback"; - /** - * If response media type is one of this jsonp response may be created. - */ - public static final MediaTypeMap jsonpCompatibleMediaTypes = new MediaTypeMap(); + /** + * If response media type is one of this jsonp response may be created. + */ + public static final MediaTypeMap jsonpCompatibleMediaTypes = new MediaTypeMap(); - /** - * Default {@link ObjectMapper} for type resolution. Used if none is provided by {@link Providers}. - */ - protected static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper(); + /** + * Default {@link ObjectMapper} for type resolution. Used if none is provided by {@link Providers}. + */ + protected static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper(); - static { - jsonpCompatibleMediaTypes.add(MediaType.APPLICATION_JSON_TYPE , MediaType.APPLICATION_JSON_TYPE.toString()); - jsonpCompatibleMediaTypes.add(APPLICATION_JAVASCRIPT_MEDIA_TYPE, APPLICATION_JAVASCRIPT_MEDIA_TYPE.toString()); - jsonpCompatibleMediaTypes.add(APPLICATION_PLUS_JSON_TYPE , APPLICATION_PLUS_JSON_TYPE.toString()); - jsonpCompatibleMediaTypes.add(TEXT_JSON_TYPE , TEXT_JSON_TYPE.toString()); - jsonpCompatibleMediaTypes.add(TEXT_JAVASCRIPT_MEDIA_TYPE , TEXT_JAVASCRIPT_MEDIA_TYPE.toString()); - } + static { + jsonpCompatibleMediaTypes.add(MediaType.APPLICATION_JSON_TYPE , MediaType.APPLICATION_JSON_TYPE.toString()); + jsonpCompatibleMediaTypes.add(APPLICATION_JAVASCRIPT_MEDIA_TYPE, APPLICATION_JAVASCRIPT_MEDIA_TYPE.toString()); + jsonpCompatibleMediaTypes.add(APPLICATION_PLUS_JSON_TYPE , APPLICATION_PLUS_JSON_TYPE.toString()); + jsonpCompatibleMediaTypes.add(TEXT_JSON_TYPE , TEXT_JSON_TYPE.toString()); + jsonpCompatibleMediaTypes.add(TEXT_JAVASCRIPT_MEDIA_TYPE , TEXT_JAVASCRIPT_MEDIA_TYPE.toString()); + } - private UriInfo uri; + private UriInfo uri; - private String callbackQueryParameter = DEFAULT_CALLBACK_QUERY_PARAMETER; + private String callbackQueryParameter = DEFAULT_CALLBACK_QUERY_PARAMETER; - private boolean wrapInTryCatch = false; + private boolean wrapInTryCatch = false; - public Jackson2JsonpInterceptor() { - ResteasyConfiguration context = ResteasyProviderFactory.getContextData(ResteasyConfiguration.class); - if (context != null) { - wrapInTryCatch = Boolean.parseBoolean(context.getParameter("resteasy.jsonp.silent")); - enabled = Boolean.parseBoolean(context.getParameter("resteasy.jsonp.enable")); - } - } + public Jackson2JsonpInterceptor() { + ResteasyConfiguration context = ResteasyProviderFactory.getContextData(ResteasyConfiguration.class); + if (context != null) { + wrapInTryCatch = Boolean.parseBoolean(context.getParameter("resteasy.jsonp.silent")); + enabled = Boolean.parseBoolean(context.getParameter("resteasy.jsonp.enable")); + } + } - /** - * The {@link ObjectMapper} used to create typing information. - */ - protected ObjectMapper objectMapper; + /** + * The {@link ObjectMapper} used to create typing information. + */ + protected ObjectMapper objectMapper; - /** - * The {@link Providers} used to retrieve the {@link #objectMapper} from. - */ - protected Providers providers; + /** + * The {@link Providers} used to retrieve the {@link #objectMapper} from. + */ + protected Providers providers; - /** - * Is this interceptor enabled. - */ - private boolean enabled = false; + /** + * Is this interceptor enabled. + */ + private boolean enabled = false; - /** - * This subclass of {@link CommitHeaderOutputStream} overrides the {@link #close()} method so it would commit - * the headers only, without actually calling the {@link #close()} method of the delegate {@link OutputStream} - */ - private static class DoNotCloseDelegateOutputStream extends BufferedOutputStream { + /** + * This subclass of {@link CommitHeaderOutputStream} overrides the {@link #close()} method so it would commit + * the headers only, without actually calling the {@link #close()} method of the delegate {@link OutputStream} + */ + private static class DoNotCloseDelegateOutputStream extends BufferedOutputStream { - DoNotCloseDelegateOutputStream(OutputStream delegate) { - super(delegate); - } + DoNotCloseDelegateOutputStream(OutputStream delegate) { + super(delegate); + } - @Override - public void close() throws IOException { - flush(); - } - } + @Override + public void close() throws IOException { + flush(); + } + } - /** - * {@inheritDoc} - */ - @Override - public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { - LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName()); + /** + * {@inheritDoc} + */ + @Override + public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { + LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName()); - String function = uri.getQueryParameters().getFirst(callbackQueryParameter); - if (enabled && function != null && !function.trim().isEmpty() && !jsonpCompatibleMediaTypes.getPossible(context.getMediaType()).isEmpty()){ + String function = uri.getQueryParameters().getFirst(callbackQueryParameter); + if (enabled && function != null && !function.trim().isEmpty() && !jsonpCompatibleMediaTypes.getPossible(context.getMediaType()).isEmpty()){ - OutputStreamWriter writer = new OutputStreamWriter(context.getOutputStream()); + OutputStreamWriter writer = new OutputStreamWriter(context.getOutputStream()); - if (wrapInTryCatch) writer.write("try{"); - writer.write(function + "("); - writer.flush(); + if (wrapInTryCatch) writer.write("try{"); + writer.write(function + "("); + writer.flush(); - // Disable the close method before calling context.proceed() - OutputStream old = context.getOutputStream(); - DoNotCloseDelegateOutputStream wrappedOutputStream = new DoNotCloseDelegateOutputStream(old); - context.setOutputStream(wrappedOutputStream); + // Disable the close method before calling context.proceed() + OutputStream old = context.getOutputStream(); + DoNotCloseDelegateOutputStream wrappedOutputStream = new DoNotCloseDelegateOutputStream(old); + context.setOutputStream(wrappedOutputStream); - try { - context.proceed(); - wrappedOutputStream.flush(); - writer.write(")"); - if (wrapInTryCatch) writer.write("}catch(e){}"); - writer.flush(); - } finally { - context.setOutputStream(old); - } - } else { + try { context.proceed(); - } - } + wrappedOutputStream.flush(); + writer.write(")"); + if (wrapInTryCatch) writer.write("}catch(e){}"); + writer.flush(); + } finally { + context.setOutputStream(old); + } + } else { + context.proceed(); + } + } - /** - * Search for an {@link ObjectMapper} for the given class and mediaType - * - * @param type the {@link Class} to serialize - * @param mediaType the response {@link MediaType} - * @return the {@link ObjectMapper} - */ - protected ObjectMapper getObjectMapper(Class type, MediaType mediaType) - { - if (objectMapper != null) { - return objectMapper; - } + /** + * Search for an {@link ObjectMapper} for the given class and mediaType + * + * @param type the {@link Class} to serialize + * @param mediaType the response {@link MediaType} + * @return the {@link ObjectMapper} + */ + protected ObjectMapper getObjectMapper(Class type, MediaType mediaType) + { + if (objectMapper != null) { + return objectMapper; + } - if (providers != null) { - ContextResolver resolver = providers.getContextResolver(ObjectMapper.class, mediaType); - if (resolver == null) { - resolver = providers.getContextResolver(ObjectMapper.class, null); - } - if (resolver != null) { - return resolver.getContext(type); - } - } + if (providers != null) { + ContextResolver resolver = providers.getContextResolver(ObjectMapper.class, mediaType); + if (resolver == null) { + resolver = providers.getContextResolver(ObjectMapper.class, null); + } + if (resolver != null) { + return resolver.getContext(type); + } + } - return DEFAULT_MAPPER; - } + return DEFAULT_MAPPER; + } - /** - * Setter used by RESTeasy to provide the {@link UriInfo}. - * - * @param uri the uri to set - */ - @Context - public void setUri(UriInfo uri) { - this.uri = uri; - } + /** + * Setter used by RESTeasy to provide the {@link UriInfo}. + * + * @param uri the uri to set + */ + @Context + public void setUri(UriInfo uri) { + this.uri = uri; + } - /** - * Setter used by RESTeasy to provide the {@link Providers} - * - * @param providers - */ - @Context - public void setProviders(Providers providers) { - this.providers = providers; - } + /** + * Setter used by RESTeasy to provide the {@link Providers} + * + * @param providers + */ + @Context + public void setProviders(Providers providers) { + this.providers = providers; + } - /** - * Set an fix {@link ObjectMapper}. If this is not set {@link Providers} are used for lookup. If there are is none too, use a default one. - * - * @param objectMapper - */ - public void setObjectMapper(ObjectMapper objectMapper) { - this.objectMapper = objectMapper; - } + /** + * Set an fix {@link ObjectMapper}. If this is not set {@link Providers} are used for lookup. If there are is none too, use a default one. + * + * @param objectMapper + */ + public void setObjectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } - /** - * Get the name of the query parameter which contains the JavaScript method name. Default: callback. - * - * @return the callbackQueryParameter - */ - public String getCallbackQueryParameter() { - return callbackQueryParameter; - } + /** + * Get the name of the query parameter which contains the JavaScript method name. Default: callback. + * + * @return the callbackQueryParameter + */ + public String getCallbackQueryParameter() { + return callbackQueryParameter; + } - /** - * Set callback query parameter. - * - * @see #getCallbackQueryParameter() - * @param callbackQueryParameter the callbackQueryParameter to set - */ - public void setCallbackQueryParameter(String callbackQueryParameter) { - this.callbackQueryParameter = callbackQueryParameter; - } + /** + * Set callback query parameter. + * + * @see #getCallbackQueryParameter() + * @param callbackQueryParameter the callbackQueryParameter to set + */ + public void setCallbackQueryParameter(String callbackQueryParameter) { + this.callbackQueryParameter = callbackQueryParameter; + } - /** - * Check is the JSONP callback will be wrapped with try-catch block - * - * @return true if try-catch block is generated; false otherwise - */ - public boolean isWrapInTryCatch() { - return wrapInTryCatch; - } + /** + * Check is the JSONP callback will be wrapped with try-catch block + * + * @return true if try-catch block is generated; false otherwise + */ + public boolean isWrapInTryCatch() { + return wrapInTryCatch; + } - /** - * Enables or disables wrapping the JSONP callback try try-catch block - * - * @param wrapInTryCatch true if you want to wrap the result with try-catch block; false otherwise - */ - public void setWrapInTryCatch(boolean wrapInTryCatch) { - this.wrapInTryCatch = wrapInTryCatch; - } + /** + * Enables or disables wrapping the JSONP callback try try-catch block + * + * @param wrapInTryCatch true if you want to wrap the result with try-catch block; false otherwise + */ + public void setWrapInTryCatch(boolean wrapInTryCatch) { + this.wrapInTryCatch = wrapInTryCatch; + } } diff --git a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/PatchMethodFilter.java b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/PatchMethodFilter.java index 923c0ab2385..d0cf60bde00 100644 --- a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/PatchMethodFilter.java +++ b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/PatchMethodFilter.java @@ -32,8 +32,8 @@ import com.github.fge.jsonpatch.JsonPatch; import com.github.fge.jsonpatch.JsonPatchException; /* -* @author Jim Ma -*/ + * @author Jim Ma + */ @Provider @Priority(Integer.MAX_VALUE) public class PatchMethodFilter implements ContainerRequestFilter diff --git a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJackson2Provider.java b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJackson2Provider.java index 278b8b7055f..4358ace749e 100755 --- a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJackson2Provider.java +++ b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/ResteasyJackson2Provider.java @@ -102,11 +102,11 @@ public int hashCode() } protected final ConcurrentHashMap _readers - = new ConcurrentHashMap(); + = new ConcurrentHashMap(); @Override public Object readFrom(Class type, final Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException + throws IOException { LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); ClassAnnotationKey key = new ClassAnnotationKey(type, annotations); @@ -148,20 +148,20 @@ public Object run() throws Exception { } protected final ConcurrentHashMap _writers - = new ConcurrentHashMap(); + = new ConcurrentHashMap(); @Override public void writeTo(Object value, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws IOException + throws IOException { LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); entityStream = new DelegatingOutputStream(entityStream) { - @Override - public void flush() throws IOException { - // don't flush as this is a performance hit on Undertow. - // and causes chunked encoding to happen. - } + @Override + public void flush() throws IOException { + // don't flush as this is a performance hit on Undertow. + // and causes chunked encoding to happen. + } }; ClassAnnotationKey key = new ClassAnnotationKey(type, annotations); JsonEndpointConfig endpoint; @@ -169,25 +169,25 @@ public void flush() throws IOException { // not yet resolved (or not cached any more)? Resolve! if (endpoint == null) { - ObjectMapper mapper = locateMapper(type, mediaType); - endpoint = _configForWriting(mapper, annotations, null); + ObjectMapper mapper = locateMapper(type, mediaType); + endpoint = _configForWriting(mapper, annotations, null); - // and cache for future reuse + // and cache for future reuse _writers.put(key, endpoint); } - ObjectWriter writer = endpoint.getWriter(); - boolean withIndentOutput = false; // no way to replace _serializationConfig + ObjectWriter writer = endpoint.getWriter(); + boolean withIndentOutput = false; // no way to replace _serializationConfig - // we can't cache this. - if (annotations != null) { - for (Annotation annotation : annotations) { - if (annotation.annotationType().equals(Formatted.class)) { - withIndentOutput = true; - break; - } - } - } + // we can't cache this. + if (annotations != null) { + for (Annotation annotation : annotations) { + if (annotation.annotationType().equals(Formatted.class)) { + withIndentOutput = true; + break; + } + } + } /* 27-Feb-2009, tatu: Where can we find desired encoding? Within * HTTP headers? @@ -237,18 +237,18 @@ public void flush() throws IOException { ClassLoader tccl; if (System.getSecurityManager() == null) { - tccl = Thread.currentThread().getContextClassLoader(); + tccl = Thread.currentThread().getContextClassLoader(); } else { - tccl = AccessController.doPrivileged(new PrivilegedAction() - { - @Override - public ClassLoader run() - { - return Thread.currentThread().getContextClassLoader(); - } - }); + tccl = AccessController.doPrivileged(new PrivilegedAction() + { + @Override + public ClassLoader run() + { + return Thread.currentThread().getContextClassLoader(); + } + }); } mod = ResteasyObjectWriterInjector.get(tccl); } diff --git a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/UnrecognizedPropertyExceptionHandler.java b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/UnrecognizedPropertyExceptionHandler.java index 6f405546e13..d9f35839d37 100644 --- a/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/UnrecognizedPropertyExceptionHandler.java +++ b/providers/jackson2/src/main/java/org/jboss/resteasy/plugins/providers/jackson/UnrecognizedPropertyExceptionHandler.java @@ -16,12 +16,12 @@ */ @Provider public class UnrecognizedPropertyExceptionHandler implements ExceptionMapper { - @Override - public Response toResponse(UnrecognizedPropertyException exception) - { - return Response.status(HttpResponseCodes.SC_BAD_REQUEST) - .type(MediaType.TEXT_HTML) - .entity(exception.getOriginalMessage()) - .build(); - } + @Override + public Response toResponse(UnrecognizedPropertyException exception) + { + return Response.status(HttpResponseCodes.SC_BAD_REQUEST) + .type(MediaType.TEXT_HTML) + .entity(exception.getOriginalMessage()) + .build(); + } } diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/JAXBConfig.java b/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/JAXBConfig.java index d3a3d8d34d8..25cf9a3aa31 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/JAXBConfig.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/JAXBConfig.java @@ -11,7 +11,7 @@ @Documented @Retention(RetentionPolicy.RUNTIME) @Target( - {ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) + {ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) public @interface JAXBConfig { diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/WrappedMap.java b/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/WrappedMap.java index 0f83ec4600a..ca880506c7f 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/WrappedMap.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/WrappedMap.java @@ -26,7 +26,7 @@ String map() default "map"; /** - * entry element name + * entry element name * @return entry */ String entry() default "entry"; @@ -40,4 +40,4 @@ String namespace() default ""; String prefix() default ""; -} \ No newline at end of file +} diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBContextFinder.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBContextFinder.java index efc515fd92b..ff1a11bdd80 100755 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBContextFinder.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBContextFinder.java @@ -72,7 +72,7 @@ public int hashCode() } public JAXBContext findProvidedJAXBContext(Class type, MediaType mediaType) - throws JAXBException + throws JAXBException { JAXBContext jaxb = null; ContextResolver resolver = providers.getContextResolver(JAXBContext.class, mediaType); @@ -155,24 +155,24 @@ public JAXBContext createXmlTypeContext(Annotation[] parameterAnnotations, Class return createContextObject(parameterAnnotations, contextPath.toString()); } - @Override - public JAXBContext createContext(Annotation[] parameterAnnotations, Class... classes) throws JAXBException - { - Set> classes1 = Collections.emptySet(); - if (classes != null && classes.length != 0) { - classes1 = new HashSet>(); - for (Class type : classes) { - if (type == null) - continue; - classes1.add(type); - Class factory = findDefaultObjectFactoryClass(type); - if (factory != null) - classes1.add(factory); - } - } - Class[] classArray = classes1.toArray(new Class[classes1.size()]); - return createContextObject(parameterAnnotations, classArray); - } + @Override + public JAXBContext createContext(Annotation[] parameterAnnotations, Class... classes) throws JAXBException + { + Set> classes1 = Collections.emptySet(); + if (classes != null && classes.length != 0) { + classes1 = new HashSet>(); + for (Class type : classes) { + if (type == null) + continue; + classes1.add(type); + Class factory = findDefaultObjectFactoryClass(type); + if (factory != null) + classes1.add(factory); + } + } + Class[] classArray = classes1.toArray(new Class[classes1.size()]); + return createContextObject(parameterAnnotations, classArray); + } public JAXBContextFinder getContext(Class type) { diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBProvider.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBProvider.java index baafa6c02c1..89f4a295206 100755 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBProvider.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/AbstractJAXBProvider.java @@ -71,7 +71,7 @@ public AbstractJAXBProvider() } public JAXBContext findJAXBContext(Class type, Annotation[] annotations, MediaType mediaType, boolean reader) - throws JAXBException + throws JAXBException { ContextResolver resolver = providers.getContextResolver(JAXBContextFinder.class, mediaType); JAXBContextFinder finder = resolver.getContext(type); @@ -189,7 +189,7 @@ protected Marshaller getMarshaller(Class type, } public static void setCharset(MediaType mediaType, Marshaller marshaller) - throws PropertyException + throws PropertyException { String charset = getCharset(mediaType); // specify the character encoding if it is set on the media type diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/BaseMarshaller.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/BaseMarshaller.java index dacf9a6be3c..fd51c05f9ea 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/BaseMarshaller.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/BaseMarshaller.java @@ -18,7 +18,7 @@ public abstract class BaseMarshaller implements Marshaller protected String charset = StandardCharsets.UTF_8.name(); public void marshal(Object o, OutputStream outputStream) - throws JAXBException + throws JAXBException { try { @@ -31,7 +31,7 @@ public void marshal(Object o, OutputStream outputStream) } public void setProperty(String s, Object o) - throws PropertyException + throws PropertyException { marshaller.setProperty(s, o); if (s.equals(Marshaller.JAXB_ENCODING)) charset = o.toString(); diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBContextWrapper.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBContextWrapper.java index ad7903ad59b..d2fff02d357 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBContextWrapper.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBContextWrapper.java @@ -119,7 +119,7 @@ public JAXBContextWrapper(final Class[] classes, final Map pr @Override public JAXBContext run() throws JAXBException { - return JAXBContext.newInstance(classes, properties); + return JAXBContext.newInstance(classes, properties); } }); } diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlSeeAlsoProvider.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlSeeAlsoProvider.java index 01c21fd6acf..29a31cdcd77 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlSeeAlsoProvider.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlSeeAlsoProvider.java @@ -31,7 +31,7 @@ public class JAXBXmlSeeAlsoProvider extends AbstractJAXBProvider { @Override public JAXBContext findJAXBContext(Class type, Annotation[] annotations, MediaType mediaType, boolean reader) - throws JAXBException + throws JAXBException { ContextResolver resolver = providers.getContextResolver(JAXBContextFinder.class, mediaType); JAXBContextFinder finder = resolver.getContext(type); diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlTypeProvider.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlTypeProvider.java index 66cdee377c7..f808b6cc581 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlTypeProvider.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/JAXBXmlTypeProvider.java @@ -158,7 +158,7 @@ private javax.xml.bind.JAXBContext getJAXBContext(Class type, MediaType LogMessages.LOGGER.debugf("Provider : %s, Method : getJAXBContext", getClass().getName()); ContextResolver resolver = providers.getContextResolver( - javax.xml.bind.JAXBContext.class, mediaType); + javax.xml.bind.JAXBContext.class, mediaType); javax.xml.bind.JAXBContext finder = null; if (resolver != null) @@ -275,7 +275,7 @@ public Method[] run() throws Exception for (Method current : method) { if (current.getParameterTypes().length == 1 && current.getParameterTypes()[0].equals(type) - && current.getName().startsWith("create")) + && current.getName().startsWith("create")) { Object result = current.invoke(factory, t); return JAXBElement.class.cast(result); diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/MapProvider.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/MapProvider.java index 95edda7284d..29e24b24a37 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/MapProvider.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/MapProvider.java @@ -284,7 +284,7 @@ public void writeTo(Object target, Class type, Type genericType, Annotation[] JaxbMap map = new JaxbMap(entryName, keyName, namespaceURI); @SuppressWarnings("unchecked") - Map targetMap = (Map) target; + Map targetMap = (Map) target; for (Map.Entry mapEntry : targetMap.entrySet()) { Object value = mapEntry.getValue(); diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/PrettyProcessor.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/PrettyProcessor.java index 3df39db1971..e18a98acde5 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/PrettyProcessor.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/PrettyProcessor.java @@ -29,4 +29,3 @@ public Marshaller decorate(Marshaller target, Formatted annotation, } } } - diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/SecureUnmarshaller.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/SecureUnmarshaller.java index 7550f359c4f..878cad1e228 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/SecureUnmarshaller.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/SecureUnmarshaller.java @@ -45,7 +45,7 @@ * Created Feb 1, 2012 */ public class SecureUnmarshaller implements Unmarshaller { - + private static class SAXParserProvider { private static final Map saxParserProviders = Collections.synchronizedMap(new WeakHashMap<>()); @@ -66,11 +66,11 @@ public static SAXParserProvider getInstance() } else { try { - tccl = AccessController.doPrivileged(new PrivilegedExceptionAction() { - public ClassLoader run() throws Exception { - return Thread.currentThread().getContextClassLoader(); - } - }); + tccl = AccessController.doPrivileged(new PrivilegedExceptionAction() { + public ClassLoader run() throws Exception { + return Thread.currentThread().getContextClassLoader(); + } + }); } catch (PrivilegedActionException e) { throw new SecurityException(e); } @@ -103,30 +103,30 @@ public SAXParser getParser(boolean disableExternalEntities, boolean enableSecure } } - private Unmarshaller delegate; - boolean disableExternalEntities; - boolean enableSecureProcessingFeature; - boolean disableDTDs; - - public SecureUnmarshaller(Unmarshaller delegate, boolean disableExternalEntities, boolean enableSecureProcessingFeature, boolean disableDTDs) { - this.delegate = delegate; - this.disableExternalEntities = disableExternalEntities; - this.enableSecureProcessingFeature = enableSecureProcessingFeature; - this.disableDTDs = disableDTDs; - } - - @SuppressWarnings("unchecked") + private Unmarshaller delegate; + boolean disableExternalEntities; + boolean enableSecureProcessingFeature; + boolean disableDTDs; + + public SecureUnmarshaller(Unmarshaller delegate, boolean disableExternalEntities, boolean enableSecureProcessingFeature, boolean disableDTDs) { + this.delegate = delegate; + this.disableExternalEntities = disableExternalEntities; + this.enableSecureProcessingFeature = enableSecureProcessingFeature; + this.disableDTDs = disableDTDs; + } + + @SuppressWarnings("unchecked") public A getAdapter(Class type) { - return delegate.getAdapter(type); - } + return delegate.getAdapter(type); + } + + public AttachmentUnmarshaller getAttachmentUnmarshaller() { + return delegate.getAttachmentUnmarshaller(); + } - public AttachmentUnmarshaller getAttachmentUnmarshaller() { - return delegate.getAttachmentUnmarshaller(); - } - - public ValidationEventHandler getEventHandler() throws JAXBException { - return delegate.getEventHandler(); - } + public ValidationEventHandler getEventHandler() throws JAXBException { + return delegate.getEventHandler(); + } public Listener getListener() { return delegate.getListener(); @@ -146,7 +146,7 @@ public UnmarshallerHandler getUnmarshallerHandler() { /** * @deprecated This method is deprecated as of JAXB 2.0 - please use the new - * {@link #getSchema()} API. + * {@link #getSchema()} API. */ @Deprecated public boolean isValidating() throws JAXBException { @@ -215,16 +215,16 @@ public Object unmarshal(URL url) throws JAXBException { */ public Object unmarshal(InputSource source) throws JAXBException { - try - { - SAXParser sp = SAXParserProvider.getInstance().getParser(disableExternalEntities, enableSecureProcessingFeature, disableDTDs); - XMLReader xmlReader = sp.getXMLReader(); - final SAXSource saxSource = new SAXSource(xmlReader, source); - if (System.getSecurityManager() == null) { - return delegate.unmarshal(saxSource); - } - else - { + try + { + SAXParser sp = SAXParserProvider.getInstance().getParser(disableExternalEntities, enableSecureProcessingFeature, disableDTDs); + XMLReader xmlReader = sp.getXMLReader(); + final SAXSource saxSource = new SAXSource(xmlReader, source); + if (System.getSecurityManager() == null) { + return delegate.unmarshal(saxSource); + } + else + { return AccessController.doPrivileged(new PrivilegedExceptionAction() { @Override @@ -233,7 +233,7 @@ public Object run() throws JAXBException return delegate.unmarshal(saxSource); } }); - } + } } catch (SAXException e) { diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/StylesheetProcessor.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/StylesheetProcessor.java index 36e4915f39c..b075b17d15a 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/StylesheetProcessor.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/StylesheetProcessor.java @@ -32,4 +32,4 @@ public Marshaller decorate(Marshaller target, Stylesheet annotation, Class type, } return target; } -} \ No newline at end of file +} diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/XmlJAXBContextFinder.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/XmlJAXBContextFinder.java index 157b3cbcff1..79db1f8b43c 100755 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/XmlJAXBContextFinder.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/XmlJAXBContextFinder.java @@ -26,23 +26,23 @@ public class XmlJAXBContextFinder extends AbstractJAXBContextFinder implements C private ConcurrentHashMap xmlTypeCollectionCache = new ConcurrentHashMap(); - @Override + @Override public JAXBContext findCachedContext(Class type, MediaType mediaType, Annotation[] parameterAnnotations) throws JAXBException { - JAXBContext jaxb = findProvidedJAXBContext(type, mediaType); - if (jaxb != null) + JAXBContext jaxb = findProvidedJAXBContext(type, mediaType); + if (jaxb != null) { - return jaxb; + return jaxb; } - jaxb = type != null ? cache.get(type) : null; - if (jaxb == null) + jaxb = type != null ? cache.get(type) : null; + if (jaxb == null) { - jaxb = createContext(parameterAnnotations, type); - if (jaxb != null && type != null) { - cache.putIfAbsent(type, jaxb); - } + jaxb = createContext(parameterAnnotations, type); + if (jaxb != null && type != null) { + cache.putIfAbsent(type, jaxb); + } } - return jaxb; + return jaxb; } protected JAXBContext createContextObject(Annotation[] parameterAnnotations, Class... classes) throws JAXBException diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/DeleteResourceMethod.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/DeleteResourceMethod.java index 83bd70f807a..1ba55549155 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/DeleteResourceMethod.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/DeleteResourceMethod.java @@ -9,4 +9,4 @@ @XmlRootElement(name = "delete") public class DeleteResourceMethod extends ResourceMethodEntry { -} \ No newline at end of file +} diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/HeadResourceMethod.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/HeadResourceMethod.java index f24b99c83b0..331a4493a31 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/HeadResourceMethod.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/HeadResourceMethod.java @@ -9,4 +9,4 @@ @XmlRootElement(name = "head") public class HeadResourceMethod extends ResourceMethodEntry { -} \ No newline at end of file +} diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/OptionsResourceMethod.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/OptionsResourceMethod.java index 9a160401c70..c2b7055b7e3 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/OptionsResourceMethod.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/OptionsResourceMethod.java @@ -9,4 +9,4 @@ @XmlRootElement(name = "options") public class OptionsResourceMethod extends ResourceMethodEntry { -} \ No newline at end of file +} diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PostResourceMethod.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PostResourceMethod.java index 9957783039b..d5f6fac5f4b 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PostResourceMethod.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PostResourceMethod.java @@ -9,4 +9,4 @@ @XmlRootElement(name = "post") public class PostResourceMethod extends ResourceMethodEntry { -} \ No newline at end of file +} diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PutResourceMethod.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PutResourceMethod.java index f7719bca65e..36da1145987 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PutResourceMethod.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/PutResourceMethod.java @@ -9,4 +9,4 @@ @XmlRootElement(name = "put") public class PutResourceMethod extends ResourceMethodEntry { -} \ No newline at end of file +} diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/RegistryEntry.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/RegistryEntry.java index 971a4f92b91..9f32083481a 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/RegistryEntry.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/RegistryEntry.java @@ -62,12 +62,12 @@ public List getMethods() return methods; } - @Override - public int compareTo(RegistryEntry o) - { - if (this.getUriTemplate() == null) + @Override + public int compareTo(RegistryEntry o) + { + if (this.getUriTemplate() == null) return o.getUriTemplate() == null ? 0 : 1; - return this.getUriTemplate().compareTo(o.getUriTemplate()); - } + return this.getUriTemplate().compareTo(o.getUriTemplate()); + } } diff --git a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/TraceResourceMethod.java b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/TraceResourceMethod.java index df025dbb751..b0570e06df1 100644 --- a/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/TraceResourceMethod.java +++ b/providers/jaxb/src/main/java/org/jboss/resteasy/plugins/stats/TraceResourceMethod.java @@ -9,4 +9,4 @@ @XmlRootElement(name = "trace") public class TraceResourceMethod extends ResourceMethodEntry { -} \ No newline at end of file +} diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/BadgerFish.java b/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/BadgerFish.java index 73e54b518ea..e7faef4a205 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/BadgerFish.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/BadgerFish.java @@ -17,4 +17,4 @@ @Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) public @interface BadgerFish { -} \ No newline at end of file +} diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/Mapped.java b/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/Mapped.java index c08208b11ed..bf9d4e9ac86 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/Mapped.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/annotations/providers/jaxb/json/Mapped.java @@ -15,7 +15,7 @@ @Documented @Retention(RetentionPolicy.RUNTIME) @Target( - {ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) + {ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) public @interface Mapped { /** @@ -33,4 +33,4 @@ XmlNsMap[] namespaceMap() default {}; -} \ No newline at end of file +} diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerMarshaller.java b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerMarshaller.java index e13c44e4305..0229f8d4b7e 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerMarshaller.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerMarshaller.java @@ -35,13 +35,13 @@ public BadgerMarshaller(JAXBContext context) throws JAXBException } public void marshal(Object o, Result result) - throws JAXBException + throws JAXBException { marshaller.marshal(o, result); } public void marshal(Object o, File file) - throws JAXBException + throws JAXBException { try { @@ -62,56 +62,56 @@ public void marshal(Object o, File file) } public void marshal(Object o, Writer writer) - throws JAXBException + throws JAXBException { BadgerFishXMLStreamWriter badger = new BadgerFishXMLStreamWriter(writer); marshaller.marshal(o, badger); } public void marshal(Object o, ContentHandler contentHandler) - throws JAXBException + throws JAXBException { marshaller.marshal(o, contentHandler); } public void marshal(Object o, Node node) - throws JAXBException + throws JAXBException { marshaller.marshal(o, node); } public void marshal(Object o, XMLStreamWriter xmlStreamWriter) - throws JAXBException + throws JAXBException { marshaller.marshal(o, xmlStreamWriter); } public void marshal(Object o, XMLEventWriter xmlEventWriter) - throws JAXBException + throws JAXBException { marshaller.marshal(o, xmlEventWriter); } public Node getNode(Object o) - throws JAXBException + throws JAXBException { return marshaller.getNode(o); } public Object getProperty(String s) - throws PropertyException + throws PropertyException { return marshaller.getProperty(s); } public void setEventHandler(ValidationEventHandler validationEventHandler) - throws JAXBException + throws JAXBException { marshaller.setEventHandler(validationEventHandler); } public ValidationEventHandler getEventHandler() - throws JAXBException + throws JAXBException { return marshaller.getEventHandler(); } diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerUnmarshaller.java b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerUnmarshaller.java index c6292d7768b..c08ef476293 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerUnmarshaller.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/BadgerUnmarshaller.java @@ -46,7 +46,7 @@ public BadgerUnmarshaller(JAXBContext context) throws JAXBException } public Object unmarshal(File file) - throws JAXBException + throws JAXBException { try { @@ -59,13 +59,13 @@ public Object unmarshal(File file) } public Object unmarshal(InputStream inputStream) - throws JAXBException + throws JAXBException { return unmarshal(new InputStreamReader(inputStream)); } public Object unmarshal(Reader reader) - throws JAXBException + throws JAXBException { BadgerFishXMLStreamReader badger = null; badger = getBadgerFishReader(reader); @@ -73,7 +73,7 @@ public Object unmarshal(Reader reader) } protected BadgerFishXMLStreamReader getBadgerFishReader(Reader reader) - throws JAXBException + throws JAXBException { BadgerFishXMLStreamReader badger; char[] buffer = new char[100]; @@ -99,7 +99,7 @@ protected BadgerFishXMLStreamReader getBadgerFishReader(Reader reader) } public Object unmarshal(URL url) - throws JAXBException + throws JAXBException { try { @@ -112,25 +112,25 @@ public Object unmarshal(URL url) } public Object unmarshal(InputSource inputSource) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(inputSource); } public Object unmarshal(Node node) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(node); } public JAXBElement unmarshal(Node node, Class tClass) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(node, tClass); } public Object unmarshal(Source source) - throws JAXBException + throws JAXBException { if (!(source instanceof StreamSource)) throw new UnsupportedOperationException(Messages.MESSAGES.expectingStreamSource()); StreamSource stream = (StreamSource) source; @@ -139,7 +139,7 @@ public Object unmarshal(Source source) } public JAXBElement unmarshal(Source source, Class tClass) - throws JAXBException + throws JAXBException { if (!(source instanceof StreamSource)) throw new UnsupportedOperationException(Messages.MESSAGES.expectingStreamSource()); StreamSource stream = (StreamSource) source; @@ -148,25 +148,25 @@ public JAXBElement unmarshal(Source source, Class tClass) } public Object unmarshal(XMLStreamReader xmlStreamReader) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlStreamReader); } public JAXBElement unmarshal(XMLStreamReader xmlStreamReader, Class tClass) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlStreamReader, tClass); } public Object unmarshal(XMLEventReader xmlEventReader) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlEventReader); } public JAXBElement unmarshal(XMLEventReader xmlEventReader, Class tClass) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlEventReader, tClass); } @@ -178,38 +178,38 @@ public UnmarshallerHandler getUnmarshallerHandler() @SuppressWarnings("deprecation") public void setValidating(boolean b) - throws JAXBException + throws JAXBException { unmarshaller.setValidating(b); } @SuppressWarnings("deprecation") public boolean isValidating() - throws JAXBException + throws JAXBException { return unmarshaller.isValidating(); } public void setEventHandler(ValidationEventHandler validationEventHandler) - throws JAXBException + throws JAXBException { unmarshaller.setEventHandler(validationEventHandler); } public ValidationEventHandler getEventHandler() - throws JAXBException + throws JAXBException { return unmarshaller.getEventHandler(); } public void setProperty(String s, Object o) - throws PropertyException + throws PropertyException { unmarshaller.setProperty(s, o); } public Object getProperty(String s) - throws PropertyException + throws PropertyException { return unmarshaller.getProperty(s); } diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedContext.java b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedContext.java index 17956bb45a0..9b43bc69a6f 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedContext.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedContext.java @@ -123,4 +123,4 @@ public Validator createValidator() throws JAXBException } -} \ No newline at end of file +} diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedMarshaller.java b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedMarshaller.java index 91b521f8b45..bf3e2095fc0 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedMarshaller.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedMarshaller.java @@ -46,13 +46,13 @@ public JettisonMappedMarshaller(JAXBContext context, MappedNamespaceConvention c } public void marshal(Object o, Result result) - throws JAXBException + throws JAXBException { marshaller.marshal(o, result); } public void marshal(Object o, File file) - throws JAXBException + throws JAXBException { try { @@ -73,56 +73,56 @@ public void marshal(Object o, File file) } public void marshal(Object o, Writer writer) - throws JAXBException + throws JAXBException { MappedXMLStreamWriter mapped = new MappedXMLStreamWriter(convention, writer); marshaller.marshal(o, mapped); } public void marshal(Object o, ContentHandler contentHandler) - throws JAXBException + throws JAXBException { marshaller.marshal(o, contentHandler); } public void marshal(Object o, Node node) - throws JAXBException + throws JAXBException { marshaller.marshal(o, node); } public void marshal(Object o, XMLStreamWriter xmlStreamWriter) - throws JAXBException + throws JAXBException { marshaller.marshal(o, xmlStreamWriter); } public void marshal(Object o, XMLEventWriter xmlEventWriter) - throws JAXBException + throws JAXBException { marshaller.marshal(o, xmlEventWriter); } public Node getNode(Object o) - throws JAXBException + throws JAXBException { return marshaller.getNode(o); } public Object getProperty(String s) - throws PropertyException + throws PropertyException { return marshaller.getProperty(s); } public void setEventHandler(ValidationEventHandler validationEventHandler) - throws JAXBException + throws JAXBException { marshaller.setEventHandler(validationEventHandler); } public ValidationEventHandler getEventHandler() - throws JAXBException + throws JAXBException { return marshaller.getEventHandler(); } @@ -171,4 +171,4 @@ public Listener getListener() { return marshaller.getListener(); } -} \ No newline at end of file +} diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedUnmarshaller.java b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedUnmarshaller.java index 4e374172c93..885b34c2417 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedUnmarshaller.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JettisonMappedUnmarshaller.java @@ -60,7 +60,7 @@ public JettisonMappedUnmarshaller(JAXBContext context, MappedNamespaceConvention } public Object unmarshal(File file) - throws JAXBException + throws JAXBException { try { @@ -73,13 +73,13 @@ public Object unmarshal(File file) } public Object unmarshal(InputStream inputStream) - throws JAXBException + throws JAXBException { return unmarshal(new InputStreamReader(inputStream)); } public Object unmarshal(Reader reader) - throws JAXBException + throws JAXBException { MappedXMLStreamReader badger = null; badger = getXmlStreamReader(reader); @@ -87,7 +87,7 @@ public Object unmarshal(Reader reader) } protected MappedXMLStreamReader getXmlStreamReader(Reader reader) - throws JAXBException + throws JAXBException { MappedXMLStreamReader badger; char[] buffer = new char[100]; @@ -112,7 +112,7 @@ protected MappedXMLStreamReader getXmlStreamReader(Reader reader) } public Object unmarshal(URL url) - throws JAXBException + throws JAXBException { try { @@ -125,25 +125,25 @@ public Object unmarshal(URL url) } public Object unmarshal(InputSource inputSource) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(inputSource); } public Object unmarshal(Node node) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(node); } public JAXBElement unmarshal(Node node, Class tClass) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(node, tClass); } public Object unmarshal(Source source) - throws JAXBException + throws JAXBException { if (!(source instanceof StreamSource)) throw new UnsupportedOperationException(Messages.MESSAGES.expectingStreamSource()); StreamSource stream = (StreamSource) source; @@ -152,7 +152,7 @@ public Object unmarshal(Source source) } public JAXBElement unmarshal(Source source, Class tClass) - throws JAXBException + throws JAXBException { if (!(source instanceof StreamSource)) throw new UnsupportedOperationException(Messages.MESSAGES.expectingStreamSource()); StreamSource stream = (StreamSource) source; @@ -161,25 +161,25 @@ public JAXBElement unmarshal(Source source, Class tClass) } public Object unmarshal(XMLStreamReader xmlStreamReader) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlStreamReader); } public JAXBElement unmarshal(XMLStreamReader xmlStreamReader, Class tClass) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlStreamReader, tClass); } public Object unmarshal(XMLEventReader xmlEventReader) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlEventReader); } public JAXBElement unmarshal(XMLEventReader xmlEventReader, Class tClass) - throws JAXBException + throws JAXBException { return unmarshaller.unmarshal(xmlEventReader, tClass); } @@ -191,38 +191,38 @@ public UnmarshallerHandler getUnmarshallerHandler() @SuppressWarnings("deprecation") public void setValidating(boolean b) - throws JAXBException + throws JAXBException { unmarshaller.setValidating(b); } @SuppressWarnings("deprecation") public boolean isValidating() - throws JAXBException + throws JAXBException { return unmarshaller.isValidating(); } public void setEventHandler(ValidationEventHandler validationEventHandler) - throws JAXBException + throws JAXBException { unmarshaller.setEventHandler(validationEventHandler); } public ValidationEventHandler getEventHandler() - throws JAXBException + throws JAXBException { return unmarshaller.getEventHandler(); } public void setProperty(String s, Object o) - throws PropertyException + throws PropertyException { unmarshaller.setProperty(s, o); } public Object getProperty(String s) - throws PropertyException + throws PropertyException { return unmarshaller.getProperty(s); } @@ -271,4 +271,4 @@ public Listener getListener() { return unmarshaller.getListener(); } -} \ No newline at end of file +} diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonJAXBContextFinder.java b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonJAXBContextFinder.java index 18d7ab8380d..377c785f1ea 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonJAXBContextFinder.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonJAXBContextFinder.java @@ -122,7 +122,7 @@ public JAXBContext findCacheContext(MediaType mediaType, Annotation[] annotation } protected JAXBContext find(Class type, MediaType mediaType, ConcurrentHashMap, JAXBContext> cache, Mapped mapped, BadgerFish badger) - throws JAXBException + throws JAXBException { JAXBContext jaxb; jaxb = cache.get(type); diff --git a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonParsing.java b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonParsing.java index 9d0db7962ec..29798485f93 100644 --- a/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonParsing.java +++ b/providers/jettison/src/main/java/org/jboss/resteasy/plugins/providers/jaxb/json/JsonParsing.java @@ -109,7 +109,7 @@ public static String getJsonString(Reader reader) throws IOException } protected static char eatWhitspace(Reader buffer, boolean reset) - throws IOException + throws IOException { int i; char c; diff --git a/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/JsonBindingProvider.java b/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/JsonBindingProvider.java index 0f05ce3a7dc..9e687f97445 100644 --- a/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/JsonBindingProvider.java +++ b/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/JsonBindingProvider.java @@ -41,7 +41,7 @@ @Consumes({"application/json", "application/*+json", "text/json", "*/*"}) @Priority(Priorities.USER-100) public class JsonBindingProvider extends AbstractJsonBindingProvider - implements MessageBodyReader, MessageBodyWriter { + implements MessageBodyReader, MessageBodyWriter { private final boolean disabled; @@ -49,7 +49,7 @@ public JsonBindingProvider() { super(); ResteasyConfiguration context = ResteasyProviderFactory.getContextData(ResteasyConfiguration.class); disabled = (context != null && (Boolean.parseBoolean(context.getParameter(ResteasyContextParameters.RESTEASY_PREFER_JACKSON_OVER_JSONB)) - || Boolean.parseBoolean(context.getParameter("resteasy.jsonp.enable")))); + || Boolean.parseBoolean(context.getParameter("resteasy.jsonp.enable")))); } @Override @@ -64,7 +64,7 @@ public boolean isReadable(Class type, Type genericType, return false; } return (isSupportedMediaType(mediaType)) - && ((hasJsonBindingAnnotations(annotations)) || (!isJaxbClass(type))); + && ((hasJsonBindingAnnotations(annotations)) || (!isJaxbClass(type))); } @Override @@ -137,7 +137,7 @@ public void writeTo(Object t, Class type, Type genericType, Annotation[] anno MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws java.io.IOException, javax.ws.rs.WebApplicationException { + throws java.io.IOException, javax.ws.rs.WebApplicationException { Jsonb jsonb = getJsonb(type); try { diff --git a/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/LogMessages.java b/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/LogMessages.java index d79db718dcb..53c15b0241b 100644 --- a/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/LogMessages.java +++ b/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/LogMessages.java @@ -12,4 +12,4 @@ public interface LogMessages extends BasicLogger { LogMessages LOGGER = Logger.getMessageLogger(LogMessages.class, LogMessages.class.getPackage().getName()); -} \ No newline at end of file +} diff --git a/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/Messages.java b/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/Messages.java index 25d325aafde..0eca54b8f33 100644 --- a/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/Messages.java +++ b/providers/json-binding/src/main/java/org/jboss/resteasy/plugins/providers/jsonb/i18n/Messages.java @@ -18,4 +18,4 @@ public interface Messages @Message(id = BASE + 05, value = "JSON Binding serialization error {0}", format=Format.MESSAGE_FORMAT) String jsonBSerializationError(String element); -} \ No newline at end of file +} diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartFormDataWriter.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartFormDataWriter.java index c8137a861eb..852116383dc 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartFormDataWriter.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartFormDataWriter.java @@ -17,43 +17,43 @@ * @version $Revision: 1 $ */ public class AbstractMultipartFormDataWriter extends AbstractMultipartWriter { - @Override - protected void writeParts(MultipartOutput multipartOutput, - OutputStream entityStream, byte[] boundaryBytes) throws IOException { - if (!(multipartOutput instanceof MultipartFormDataOutput)) - throw new IllegalArgumentException(Messages.MESSAGES.hadToWriteMultipartOutput(multipartOutput, this, MultipartFormDataOutput.class)); - MultipartFormDataOutput form = (MultipartFormDataOutput) multipartOutput; - for (Map.Entry> entry : form.getFormDataMap().entrySet()) { - for (OutputPart outputPart : entry.getValue()) { - if (outputPart.getEntity() == null) { - continue; - } - MultivaluedMap headers = new MultivaluedMapImpl(); - headers.putSingle("Content-Disposition", "form-data; name=\"" - + entry.getKey() + "\"" - + getFilename(outputPart)); - writePart(entityStream, boundaryBytes, outputPart, headers); - } - } - } + @Override + protected void writeParts(MultipartOutput multipartOutput, + OutputStream entityStream, byte[] boundaryBytes) throws IOException { + if (!(multipartOutput instanceof MultipartFormDataOutput)) + throw new IllegalArgumentException(Messages.MESSAGES.hadToWriteMultipartOutput(multipartOutput, this, MultipartFormDataOutput.class)); + MultipartFormDataOutput form = (MultipartFormDataOutput) multipartOutput; + for (Map.Entry> entry : form.getFormDataMap().entrySet()) { + for (OutputPart outputPart : entry.getValue()) { + if (outputPart.getEntity() == null) { + continue; + } + MultivaluedMap headers = new MultivaluedMapImpl(); + headers.putSingle("Content-Disposition", "form-data; name=\"" + + entry.getKey() + "\"" + + getFilename(outputPart)); + writePart(entityStream, boundaryBytes, outputPart, headers); + } + } + } - private String getFilename(OutputPart part) { - String filename = part.getFilename(); - if (filename == null) { - return ""; - } else { - String encodedFilename = filename; - try { - encodedFilename = URLEncoder.encode(filename, "UTF-8"); - // append encoding charset into the value if and only if encoding was needed - if (!encodedFilename.equals(filename)) { - // encoding was needed, so per rfc5987 we have to prepend charset - return "; filename*=utf-8''" + encodedFilename; - } - } catch (UnsupportedEncodingException e) { - // should not happen - } - return "; filename=\"" + filename + "\""; - } - } + private String getFilename(OutputPart part) { + String filename = part.getFilename(); + if (filename == null) { + return ""; + } else { + String encodedFilename = filename; + try { + encodedFilename = URLEncoder.encode(filename, "UTF-8"); + // append encoding charset into the value if and only if encoding was needed + if (!encodedFilename.equals(filename)) { + // encoding was needed, so per rfc5987 we have to prepend charset + return "; filename*=utf-8''" + encodedFilename; + } + } catch (UnsupportedEncodingException e) { + // should not happen + } + return "; filename=\"" + filename + "\""; + } + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartRelatedWriter.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartRelatedWriter.java index 66a97eb55ea..b74f7634759 100755 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartRelatedWriter.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartRelatedWriter.java @@ -15,30 +15,30 @@ * @version $Revision: 1 $ */ public class AbstractMultipartRelatedWriter extends AbstractMultipartWriter { - protected void writeRelated(MultipartRelatedOutput multipartRelatedOutput, - MediaType mediaType, MultivaluedMap httpHeaders, - OutputStream entityStream) throws IOException, - WebApplicationException { - for (OutputPart outputPart : multipartRelatedOutput.getParts()) - if (outputPart.getHeaders().get("Content-ID") == null) - outputPart.getHeaders().putSingle("Content-ID", - ContentIDUtils.generateContentID()); - OutputPart rootOutputPart = multipartRelatedOutput.getRootPart(); - Map mediaTypeParameters = new LinkedHashMap( - mediaType.getParameters()); - if (mediaTypeParameters.containsKey("boundary")) - multipartRelatedOutput.setBoundary(mediaTypeParameters - .get("boundary")); - mediaTypeParameters.put("start", (String) rootOutputPart.getHeaders() - .getFirst("Content-ID")); - mediaTypeParameters.put("type", rootOutputPart.getMediaType().getType() - + "/" + rootOutputPart.getMediaType().getSubtype()); - if (multipartRelatedOutput.getStartInfo() != null) - mediaTypeParameters.put("start-info", multipartRelatedOutput - .getStartInfo()); - MediaType modifiedMediaType = new MediaType(mediaType.getType(), - mediaType.getSubtype(), mediaTypeParameters); - write(multipartRelatedOutput, modifiedMediaType, httpHeaders, - entityStream); - } + protected void writeRelated(MultipartRelatedOutput multipartRelatedOutput, + MediaType mediaType, MultivaluedMap httpHeaders, + OutputStream entityStream) throws IOException, + WebApplicationException { + for (OutputPart outputPart : multipartRelatedOutput.getParts()) + if (outputPart.getHeaders().get("Content-ID") == null) + outputPart.getHeaders().putSingle("Content-ID", + ContentIDUtils.generateContentID()); + OutputPart rootOutputPart = multipartRelatedOutput.getRootPart(); + Map mediaTypeParameters = new LinkedHashMap( + mediaType.getParameters()); + if (mediaTypeParameters.containsKey("boundary")) + multipartRelatedOutput.setBoundary(mediaTypeParameters + .get("boundary")); + mediaTypeParameters.put("start", (String) rootOutputPart.getHeaders() + .getFirst("Content-ID")); + mediaTypeParameters.put("type", rootOutputPart.getMediaType().getType() + + "/" + rootOutputPart.getMediaType().getSubtype()); + if (multipartRelatedOutput.getStartInfo() != null) + mediaTypeParameters.put("start-info", multipartRelatedOutput + .getStartInfo()); + MediaType modifiedMediaType = new MediaType(mediaType.getType(), + mediaType.getSubtype(), mediaTypeParameters); + write(multipartRelatedOutput, modifiedMediaType, httpHeaders, + entityStream); + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartWriter.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartWriter.java index ff03f8d2fcb..5581dd4e0d3 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartWriter.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/AbstractMultipartWriter.java @@ -24,7 +24,7 @@ public class AbstractMultipartWriter protected Providers workers; protected void write(MultipartOutput multipartOutput, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) - throws IOException + throws IOException { String boundary = mediaType.getParameters().get("boundary"); if (boundary == null) @@ -38,7 +38,7 @@ protected void write(MultipartOutput multipartOutput, MediaType mediaType, Multi } protected void writeParts(MultipartOutput multipartOutput, OutputStream entityStream, byte[] boundaryBytes) - throws IOException + throws IOException { for (OutputPart part : multipartOutput.getParts()) { @@ -49,7 +49,7 @@ protected void writeParts(MultipartOutput multipartOutput, OutputStream entitySt @SuppressWarnings(value = "unchecked") protected void writePart(OutputStream entityStream, byte[] boundaryBytes, OutputPart part, MultivaluedMap headers) - throws IOException + throws IOException { entityStream.write(boundaryBytes); entityStream.write("\r\n".getBytes()); diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ContentIDUtils.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ContentIDUtils.java index dc0156413b7..edacdc2fade 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ContentIDUtils.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ContentIDUtils.java @@ -16,109 +16,109 @@ * */ public class ContentIDUtils { - public static final String CID_URL_SCHEME = "cid:"; + public static final String CID_URL_SCHEME = "cid:"; - /** - * Calls {@link #generateContentIDFromAddrSpec(String)} with - * {@link #generateRFC822AddrSpec()} as parameter. - * - * @return the generated Content-ID - */ - public static String generateContentID() { - return generateContentIDFromAddrSpec(generateRFC822AddrSpec()); - } + /** + * Calls {@link #generateContentIDFromAddrSpec(String)} with + * {@link #generateRFC822AddrSpec()} as parameter. + * + * @return the generated Content-ID + */ + public static String generateContentID() { + return generateContentIDFromAddrSpec(generateRFC822AddrSpec()); + } - /** - * Helper method to generate a standards-compliant Content-ID header value - * from the supplied addrSpec. - * - * Used rfc-s: RFC2045, RFC822 - * - * @param addrSpec addrSpec - * @return the generated Content-ID - */ - public static String generateContentIDFromAddrSpec(String addrSpec) { - return "<" + addrSpec + ">"; - } + /** + * Helper method to generate a standards-compliant Content-ID header value + * from the supplied addrSpec. + * + * Used rfc-s: RFC2045, RFC822 + * + * @param addrSpec addrSpec + * @return the generated Content-ID + */ + public static String generateContentIDFromAddrSpec(String addrSpec) { + return "<" + addrSpec + ">"; + } - /** - * Helper method to generate a standards-compliant, random addr-spec as - * described in RFC822. - * - * @return the generated addrSpec - */ - public static String generateRFC822AddrSpec() { - return UUID.randomUUID().toString() + "@resteasy-multipart"; - } + /** + * Helper method to generate a standards-compliant, random addr-spec as + * described in RFC822. + * + * @return the generated addrSpec + */ + public static String generateRFC822AddrSpec() { + return UUID.randomUUID().toString() + "@resteasy-multipart"; + } - /** - * Helper method to generate a standards-compliant cid url from the supplied - * addrSpec. This implementation URL encodes everything without considering - * if it is needed or not. - * - * Used rfc-s: RFC2392, RFC822 - * - * @param addrSpec addrSpec - * @return the generated Content-ID - */ - public static String generateCidFromAddrSpec(String addrSpec) { - String cid = CID_URL_SCHEME; - try { - cid += URLEncoder.encode(addrSpec, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - LogMessages.LOGGER.error(Messages.MESSAGES.urlEncoderDoesNotSupportUtf8(), e); - } - return cid; - } + /** + * Helper method to generate a standards-compliant cid url from the supplied + * addrSpec. This implementation URL encodes everything without considering + * if it is needed or not. + * + * Used rfc-s: RFC2392, RFC822 + * + * @param addrSpec addrSpec + * @return the generated Content-ID + */ + public static String generateCidFromAddrSpec(String addrSpec) { + String cid = CID_URL_SCHEME; + try { + cid += URLEncoder.encode(addrSpec, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + LogMessages.LOGGER.error(Messages.MESSAGES.urlEncoderDoesNotSupportUtf8(), e); + } + return cid; + } - /** - * @param cid - * the RFC2392 compliant cid - * @return the RFC822 defined addr-spec decoded from the cid - */ - public static String parseAddrSpecFromCid(String cid) { - String addrSpec = cid.trim(); - if (addrSpec.startsWith(CID_URL_SCHEME)) - addrSpec = addrSpec.substring(CID_URL_SCHEME.length()).trim(); + /** + * @param cid + * the RFC2392 compliant cid + * @return the RFC822 defined addr-spec decoded from the cid + */ + public static String parseAddrSpecFromCid(String cid) { + String addrSpec = cid.trim(); + if (addrSpec.startsWith(CID_URL_SCHEME)) + addrSpec = addrSpec.substring(CID_URL_SCHEME.length()).trim(); - try { - addrSpec = URLDecoder.decode(addrSpec, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - LogMessages.LOGGER.error(Messages.MESSAGES.urlDecoderDoesNotSupportUtf8(), e); - } + try { + addrSpec = URLDecoder.decode(addrSpec, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + LogMessages.LOGGER.error(Messages.MESSAGES.urlDecoderDoesNotSupportUtf8(), e); + } - return addrSpec; - } + return addrSpec; + } - /** - * @param contentID - * the RFC2045 compliant Content-ID - * @return the RFC822 defined addr-spec decoded from the contentID - */ - public static String parseAddrSpecFromContentID(String contentID) { - String addrSpec = contentID.trim(); + /** + * @param contentID + * the RFC2045 compliant Content-ID + * @return the RFC822 defined addr-spec decoded from the contentID + */ + public static String parseAddrSpecFromContentID(String contentID) { + String addrSpec = contentID.trim(); - if (addrSpec.startsWith("<") && addrSpec.endsWith(">")) - addrSpec = addrSpec.substring(1, addrSpec.length() - 1).trim(); + if (addrSpec.startsWith("<") && addrSpec.endsWith(">")) + addrSpec = addrSpec.substring(1, addrSpec.length() - 1).trim(); - return addrSpec; - } + return addrSpec; + } - /** - * @param cid - * the RFC2392 compliant cid - * @return the RFC2045 compliant Content-ID representing the cid - */ - public static String convertCidToContentID(String cid) { - return generateContentIDFromAddrSpec(parseAddrSpecFromCid(cid)); - } + /** + * @param cid + * the RFC2392 compliant cid + * @return the RFC2045 compliant Content-ID representing the cid + */ + public static String convertCidToContentID(String cid) { + return generateContentIDFromAddrSpec(parseAddrSpecFromCid(cid)); + } - /** - * @param contentID - * the RFC2045 compliant Content-ID - * @return the RFC2392 compliant cid representing the contentID - */ - public static String convertContentIDToCid(String contentID) { - return generateCidFromAddrSpec(parseAddrSpecFromContentID(contentID)); - } + /** + * @param contentID + * the RFC2045 compliant Content-ID + * @return the RFC2392 compliant cid representing the contentID + */ + public static String convertContentIDToCid(String contentID) { + return generateCidFromAddrSpec(parseAddrSpecFromContentID(contentID)); + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/FieldEnablerPrivilegedAction.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/FieldEnablerPrivilegedAction.java index 2650fdd96a4..cdbca99ccd2 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/FieldEnablerPrivilegedAction.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/FieldEnablerPrivilegedAction.java @@ -18,15 +18,15 @@ * */ public class FieldEnablerPrivilegedAction implements PrivilegedAction { - private final Field field; + private final Field field; - public FieldEnablerPrivilegedAction(Field field) { - super(); - this.field = field; - } + public FieldEnablerPrivilegedAction(Field field) { + super(); + this.field = field; + } - public Object run() { - field.setAccessible(true); - return null; - } + public Object run() { + field.setAccessible(true); + return null; + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/HeaderFlushedOutputStream.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/HeaderFlushedOutputStream.java index d3a11c4b0ce..d361b59473b 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/HeaderFlushedOutputStream.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/HeaderFlushedOutputStream.java @@ -11,70 +11,70 @@ * @version $Revision: 1 $ */ public class HeaderFlushedOutputStream extends OutputStream { - private MultivaluedMap headers; - private OutputStream stream; - private boolean headersFlushed = false; + private MultivaluedMap headers; + private OutputStream stream; + private boolean headersFlushed = false; - public HeaderFlushedOutputStream(MultivaluedMap headers, - OutputStream delegate) { - this.headers = headers; - this.stream = delegate; - } + public HeaderFlushedOutputStream(MultivaluedMap headers, + OutputStream delegate) { + this.headers = headers; + this.stream = delegate; + } - @SuppressWarnings(value = "unchecked") - protected void flushHeaders() throws IOException { - if (headersFlushed) - return; + @SuppressWarnings(value = "unchecked") + protected void flushHeaders() throws IOException { + if (headersFlushed) + return; - headersFlushed = true; - RuntimeDelegate delegate = RuntimeDelegate.getInstance(); + headersFlushed = true; + RuntimeDelegate delegate = RuntimeDelegate.getInstance(); - for (String key : headers.keySet()) { - List objs = headers.get(key); - for (Object obj : objs) { - String value; - RuntimeDelegate.HeaderDelegate headerDelegate = delegate - .createHeaderDelegate(obj.getClass()); - if (headerDelegate != null) { - value = headerDelegate.toString(obj); - } else { - value = obj.toString(); - } - stream.write(key.getBytes()); - stream.write(": ".getBytes()); - stream.write(value.getBytes()); - stream.write("\r\n".getBytes()); - } - } - stream.write("\r\n".getBytes()); + for (String key : headers.keySet()) { + List objs = headers.get(key); + for (Object obj : objs) { + String value; + RuntimeDelegate.HeaderDelegate headerDelegate = delegate + .createHeaderDelegate(obj.getClass()); + if (headerDelegate != null) { + value = headerDelegate.toString(obj); + } else { + value = obj.toString(); + } + stream.write(key.getBytes()); + stream.write(": ".getBytes()); + stream.write(value.getBytes()); + stream.write("\r\n".getBytes()); + } + } + stream.write("\r\n".getBytes()); - } + } - @Override - public void write(int i) throws IOException { - flushHeaders(); - stream.write(i); - } + @Override + public void write(int i) throws IOException { + flushHeaders(); + stream.write(i); + } - @Override - public void write(byte[] bytes) throws IOException { - flushHeaders(); - stream.write(bytes); - } + @Override + public void write(byte[] bytes) throws IOException { + flushHeaders(); + stream.write(bytes); + } - @Override - public void write(byte[] bytes, int i, int i1) throws IOException { - flushHeaders(); - stream.write(bytes, i, i1); - } + @Override + public void write(byte[] bytes, int i, int i1) throws IOException { + flushHeaders(); + stream.write(bytes, i, i1); + } - @Override - public void flush() throws IOException { - stream.flush(); - } + @Override + public void flush() throws IOException { + stream.flush(); + } - @Override - public void close() throws IOException { - stream.close(); - } + @Override + public void close() throws IOException { + stream.close(); + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/InputPart.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/InputPart.java index 16d8c5c5db7..0982fa286b6 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/InputPart.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/InputPart.java @@ -13,53 +13,53 @@ * @version $Revision: 1 $ */ public interface InputPart { - /** - * If no content-type header is sent in a multipart message part - * "text/plain; charset=ISO-8859-1" is assumed. - *

- * This can be overwritten by setting a different String value in - * {@link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)} - * with this ("resteasy.provider.multipart.inputpart.defaultContentType") - * String as key. It should be done in a - * {@link javax.ws.rs.container.ContainerRequestFilter}. - *

- */ - String DEFAULT_CONTENT_TYPE_PROPERTY = "resteasy.provider.multipart.inputpart.defaultContentType"; - - /** - * If there is a content-type header without a charset parameter, charset=US-ASCII - * is assumed. - *

+ /** + * If no content-type header is sent in a multipart message part + * "text/plain; charset=ISO-8859-1" is assumed. + *

+ * This can be overwritten by setting a different String value in + * {@link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)} + * with this ("resteasy.provider.multipart.inputpart.defaultContentType") + * String as key. It should be done in a + * {@link javax.ws.rs.container.ContainerRequestFilter}. + *

+ */ + String DEFAULT_CONTENT_TYPE_PROPERTY = "resteasy.provider.multipart.inputpart.defaultContentType"; + + /** + * If there is a content-type header without a charset parameter, charset=US-ASCII + * is assumed. + *

* This can be overwritten by setting a different String value in * {@link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)} * with this ("resteasy.provider.multipart.inputpart.defaultCharset") * String as key. It should be done in a * {@link javax.ws.rs.container.ContainerRequestFilter}. *

- */ - String DEFAULT_CHARSET_PROPERTY = "resteasy.provider.multipart.inputpart.defaultCharset"; + */ + String DEFAULT_CHARSET_PROPERTY = "resteasy.provider.multipart.inputpart.defaultCharset"; - /** - * @return headers of this part - */ - MultivaluedMap getHeaders(); + /** + * @return headers of this part + */ + MultivaluedMap getHeaders(); - String getBodyAsString() throws IOException; + String getBodyAsString() throws IOException; - T getBody(Class type, Type genericType) throws IOException; + T getBody(Class type, Type genericType) throws IOException; - T getBody(GenericType type) throws IOException; + T getBody(GenericType type) throws IOException; - /** - * @return "Content-Type" of this part - */ - MediaType getMediaType(); + /** + * @return "Content-Type" of this part + */ + MediaType getMediaType(); - /** - * @return true if the Content-Type was resolved from the message, false if - * it was resolved from the server default - */ - boolean isContentTypeFromMessage(); + /** + * @return true if the Content-Type was resolved from the message, false if + * it was resolved from the server default + */ + boolean isContentTypeFromMessage(); /** * Change the media type of the body part before you extract it. Useful for specifying a charset. diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ListMultipartReader.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ListMultipartReader.java index 1d8907fbced..cd8e8181bfc 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ListMultipartReader.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/ListMultipartReader.java @@ -27,37 +27,36 @@ @Provider @Consumes("multipart/*") public class ListMultipartReader implements MessageBodyReader> { - protected @Context - Providers workers; + protected @Context Providers workers; - public boolean isReadable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return type.equals(List.class) && genericType != null - && genericType instanceof ParameterizedType; - } + public boolean isReadable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return type.equals(List.class) && genericType != null + && genericType instanceof ParameterizedType; + } - public List readFrom(Class> type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - String boundary = mediaType.getParameters().get("boundary"); - if (boundary == null) - throw new IOException(Messages.MESSAGES.unableToGetBoundary()); - - if (!(genericType instanceof ParameterizedType)) - throw new IllegalArgumentException(Messages.MESSAGES.receivedGenericType(this, genericType, ParameterizedType.class)); + public List readFrom(Class> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) + throws IOException, WebApplicationException { + String boundary = mediaType.getParameters().get("boundary"); + if (boundary == null) + throw new IOException(Messages.MESSAGES.unableToGetBoundary()); - ParameterizedType param = (ParameterizedType) genericType; - Type baseType = param.getActualTypeArguments()[0]; - Class rawType = Types.getRawType(baseType); + if (!(genericType instanceof ParameterizedType)) + throw new IllegalArgumentException(Messages.MESSAGES.receivedGenericType(this, genericType, ParameterizedType.class)); - MultipartInputImpl input = new MultipartInputImpl(mediaType, workers); - input.parse(entityStream); + ParameterizedType param = (ParameterizedType) genericType; + Type baseType = param.getActualTypeArguments()[0]; + Class rawType = Types.getRawType(baseType); - List list = new ArrayList(); + MultipartInputImpl input = new MultipartInputImpl(mediaType, workers); + input.parse(entityStream); - for (InputPart part : input.getParts()) - list.add(part.getBody(rawType, baseType)); + List list = new ArrayList(); + + for (InputPart part : input.getParts()) + list.add(part.getBody(rawType, baseType)); if (!InputStream.class.equals(rawType)) { @@ -65,6 +64,6 @@ public List readFrom(Class> type, Type genericType, input.close(); } - return list; - } -} \ No newline at end of file + return list; + } +} diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataReader.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataReader.java index e75564ec44c..216bbf06754 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataReader.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataReader.java @@ -28,39 +28,38 @@ @Provider @Consumes("multipart/form-data") public class MapMultipartFormDataReader implements MessageBodyReader> { - protected @Context - Providers workers; + protected @Context Providers workers; - public boolean isReadable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - return type.equals(Map.class) && genericType != null - && genericType instanceof ParameterizedType; - } + public boolean isReadable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return type.equals(Map.class) && genericType != null + && genericType instanceof ParameterizedType; + } - public Map readFrom(Class> type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException { - String boundary = mediaType.getParameters().get("boundary"); - if (boundary == null) - throw new IOException(Messages.MESSAGES.unableToGetBoundary()); + public Map readFrom(Class> type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) + throws IOException, WebApplicationException { + String boundary = mediaType.getParameters().get("boundary"); + if (boundary == null) + throw new IOException(Messages.MESSAGES.unableToGetBoundary()); - if (!(genericType instanceof ParameterizedType)) - throw new IllegalArgumentException(Messages.MESSAGES.receivedGenericType(this, genericType, ParameterizedType.class)); - ParameterizedType param = (ParameterizedType) genericType; - Type baseType = param.getActualTypeArguments()[1]; - Class rawType = Types.getRawType(baseType); + if (!(genericType instanceof ParameterizedType)) + throw new IllegalArgumentException(Messages.MESSAGES.receivedGenericType(this, genericType, ParameterizedType.class)); + ParameterizedType param = (ParameterizedType) genericType; + Type baseType = param.getActualTypeArguments()[1]; + Class rawType = Types.getRawType(baseType); - MultipartFormDataInputImpl input = new MultipartFormDataInputImpl( - mediaType, workers); - input.parse(entityStream); + MultipartFormDataInputImpl input = new MultipartFormDataInputImpl( + mediaType, workers); + input.parse(entityStream); - Map map = new LinkedHashMap(); + Map map = new LinkedHashMap(); - for (Map.Entry> entry : input.getFormDataMap() - .entrySet()) - map.put(entry.getKey(), entry.getValue().get(0).getBody(rawType, - baseType)); + for (Map.Entry> entry : input.getFormDataMap() + .entrySet()) + map.put(entry.getKey(), entry.getValue().get(0).getBody(rawType, + baseType)); if (!InputStream.class.equals(rawType)) { @@ -68,6 +67,6 @@ public boolean isReadable(Class type, Type genericType, input.close(); } - return map; - } -} \ No newline at end of file + return map; + } +} diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataWriter.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataWriter.java index 1553eba50a2..aa62dc7c8c5 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataWriter.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MapMultipartFormDataWriter.java @@ -45,4 +45,4 @@ public void writeTo(Map map, Class type, Type genericType, An } write(output, mediaType, httpHeaders, entityStream); } -} \ No newline at end of file +} diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MimeMultipartProvider.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MimeMultipartProvider.java index aa2efac62f3..193c1ea6cc4 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MimeMultipartProvider.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MimeMultipartProvider.java @@ -55,7 +55,7 @@ public class MimeMultipartProvider extends AbstractEntityProvider public static DataSource readDataSource(InputStream in, MediaType mediaType) throws IOException { ByteArrayDataSource ds = new ByteArrayDataSource(new BufferedInputStream(in), mediaType - .toString()); + .toString()); return ds; } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationReader.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationReader.java index 376de5397e6..9041f09221a 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationReader.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationReader.java @@ -33,29 +33,27 @@ @Consumes("multipart/form-data") public class MultipartFormAnnotationReader implements MessageBodyReader { - protected - @Context - Providers workers; + protected @Context Providers workers; @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return FindAnnotation.findAnnotation(annotations, MultipartForm.class) != null - || type.isAnnotationPresent(MultipartForm.class); + || type.isAnnotationPresent(MultipartForm.class); } @Override public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException + throws IOException, WebApplicationException { String boundary = mediaType.getParameters().get("boundary"); if (boundary == null) throw new IOException(Messages.MESSAGES.unableToGetBoundary()); MultipartFormDataInputImpl input = new MultipartFormDataInputImpl( - mediaType, workers); + mediaType, workers); input.parse(entityStream); Object obj; @@ -92,7 +90,7 @@ public Object readFrom(Class type, Type genericType, { FormParam param = method.getAnnotation(FormParam.class); List list = input.getFormDataMap() - .get(param.value()); + .get(param.value()); if (list == null || list.isEmpty()) continue; InputPart part = list.get(0); @@ -104,17 +102,17 @@ public Object readFrom(Class type, Type genericType, Class type1 = method.getParameterTypes()[0]; Object data; if (InputPart.class.equals(type1)) { - hasInputStream = true; - data = part; + hasInputStream = true; + data = part; } else { - if (InputStream.class.equals(type1)) - { - hasInputStream = true; - } - data = part.getBody(type1, - method.getGenericParameterTypes()[0]); + if (InputStream.class.equals(type1)) + { + hasInputStream = true; + } + data = part.getBody(type1, + method.getGenericParameterTypes()[0]); } try { @@ -138,7 +136,7 @@ public Object readFrom(Class type, Type genericType, } protected boolean setFields(Class type, MultipartFormDataInputImpl input, - Object obj) throws IOException + Object obj) throws IOException { boolean hasInputStream = false; for (Field field : type.getDeclaredFields()) @@ -148,7 +146,7 @@ protected boolean setFields(Class type, MultipartFormDataInputImpl input, AccessController.doPrivileged(new FieldEnablerPrivilegedAction(field)); FormParam param = field.getAnnotation(FormParam.class); List list = input.getFormDataMap() - .get(param.value()); + .get(param.value()); if (list == null || list.isEmpty()) continue; InputPart part = list.get(0); @@ -159,17 +157,17 @@ protected boolean setFields(Class type, MultipartFormDataInputImpl input, continue; Object data; if (InputPart.class.equals(field.getType())) { - hasInputStream = true; - data = part; + hasInputStream = true; + data = part; } else { - if (InputStream.class.equals(field.getType())) - { - hasInputStream = true; - } - data = part.getBody(field.getType(), field - .getGenericType()); + if (InputStream.class.equals(field.getType())) + { + hasInputStream = true; + } + data = part.getBody(field.getType(), field + .getGenericType()); } try { @@ -184,4 +182,4 @@ protected boolean setFields(Class type, MultipartFormDataInputImpl input, return hasInputStream; } -} \ No newline at end of file +} diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationWriter.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationWriter.java index 7df597a9a63..a38a3bd4a82 100755 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationWriter.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormAnnotationWriter.java @@ -89,7 +89,7 @@ protected String getFilename(AccessibleObject method) } protected void getFields(Class type, MultipartFormDataOutput output, Object obj) - throws IOException + throws IOException { for (Field field : type.getDeclaredFields()) { @@ -115,4 +115,4 @@ protected void getFields(Class type, MultipartFormDataOutput output, Object o } -} \ No newline at end of file +} diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput.java index 8d572c88c52..c5cc01aff2f 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInput.java @@ -12,22 +12,22 @@ * @version $Revision: 1 $ */ public interface MultipartFormDataInput extends MultipartInput { - /** - * @deprecated Will be removed in the future. Use - * {@link MultipartFormDataInput#getFormDataMap()} instead. - * - * @return A parameter map containing only one value per name. - */ - @Deprecated - Map getFormData(); + /** + * @deprecated Will be removed in the future. Use + * {@link MultipartFormDataInput#getFormDataMap()} instead. + * + * @return A parameter map containing only one value per name. + */ + @Deprecated + Map getFormData(); - /** - * @return A parameter map containing a list of values per name. - */ - Map> getFormDataMap(); + /** + * @return A parameter map containing a list of values per name. + */ + Map> getFormDataMap(); - T getFormDataPart(String key, Class rawType, Type genericType) - throws IOException; + T getFormDataPart(String key, Class rawType, Type genericType) + throws IOException; - T getFormDataPart(String key, GenericType type) throws IOException; + T getFormDataPart(String key, GenericType type) throws IOException; } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInputImpl.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInputImpl.java index e43344f0003..f4523a5764a 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInputImpl.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataInputImpl.java @@ -22,74 +22,74 @@ * @version $Revision: 1 $ */ public class MultipartFormDataInputImpl extends MultipartInputImpl implements - MultipartFormDataInput { - protected Map formData = new HashMap(); - protected Map> formDataMap = new HashMap>(); + MultipartFormDataInput { + protected Map formData = new HashMap(); + protected Map> formDataMap = new HashMap>(); - public MultipartFormDataInputImpl(MediaType contentType, Providers workers) { - super(contentType, workers); - } + public MultipartFormDataInputImpl(MediaType contentType, Providers workers) { + super(contentType, workers); + } /** * @deprecated Will be removed in the future. Use * {@link MultipartFormDataInputImpl#getFormDataMap()} instead. - * + * * @return A parameter map containing only one value per name. */ - @Deprecated - public Map getFormData() { - return formData; - } + @Deprecated + public Map getFormData() { + return formData; + } - public Map> getFormDataMap() { - return formDataMap; - } + public Map> getFormDataMap() { + return formDataMap; + } - public T getFormDataPart(String key, Class rawType, Type genericType) - throws IOException { - List list = getFormDataMap().get(key); - if (list == null || list.isEmpty()) - return null; - InputPart part = list.get(0); - if (part == null) - return null; - return part.getBody(rawType, genericType); - } + public T getFormDataPart(String key, Class rawType, Type genericType) + throws IOException { + List list = getFormDataMap().get(key); + if (list == null || list.isEmpty()) + return null; + InputPart part = list.get(0); + if (part == null) + return null; + return part.getBody(rawType, genericType); + } - public T getFormDataPart(String key, GenericType type) - throws IOException { - List list = getFormDataMap().get(key); - if (list == null || list.isEmpty()) - return null; - InputPart part = list.get(0); - if (part == null) - return null; - return part.getBody(type); - } + public T getFormDataPart(String key, GenericType type) + throws IOException { + List list = getFormDataMap().get(key); + if (list == null || list.isEmpty()) + return null; + InputPart part = list.get(0); + if (part == null) + return null; + return part.getBody(type); + } - @Override - protected InputPart extractPart(BodyPart bodyPart) throws IOException { - InputPart currPart = super.extractPart(bodyPart); - Field disposition = bodyPart.getHeader().getField( - FieldName.CONTENT_DISPOSITION); - if (disposition == null) - throw new RuntimeException(Messages.MESSAGES.couldFindNoContentDispositionHeader()); - if (disposition instanceof ContentDispositionField) { - String name = ((ContentDispositionField) disposition) - .getParameter("name"); - List list = formDataMap.get(name); - if (list == null) { - list = new LinkedList(); - formData.put(name, currPart); - formDataMap.put(name, list); - } - list.add(currPart); - } else { - throw new RuntimeException(Messages.MESSAGES.couldNotParseContentDisposition(disposition)); - } + @Override + protected InputPart extractPart(BodyPart bodyPart) throws IOException { + InputPart currPart = super.extractPart(bodyPart); + Field disposition = bodyPart.getHeader().getField( + FieldName.CONTENT_DISPOSITION); + if (disposition == null) + throw new RuntimeException(Messages.MESSAGES.couldFindNoContentDispositionHeader()); + if (disposition instanceof ContentDispositionField) { + String name = ((ContentDispositionField) disposition) + .getParameter("name"); + List list = formDataMap.get(name); + if (list == null) { + list = new LinkedList(); + formData.put(name, currPart); + formDataMap.put(name, list); + } + list.add(currPart); + } else { + throw new RuntimeException(Messages.MESSAGES.couldNotParseContentDisposition(disposition)); + } - return currPart; - } + return currPart; + } protected void finalize() throws Throwable { diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataReader.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataReader.java index 8bfeb9e7796..9cbdae98515 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataReader.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataReader.java @@ -24,9 +24,7 @@ @Consumes("multipart/form-data") public class MultipartFormDataReader implements MessageBodyReader { - protected - @Context - Providers workers; + protected @Context Providers workers; public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) @@ -55,4 +53,4 @@ public MultipartFormDataInput readFrom(Class type, Type input.parse(entityStream); return input; } -} \ No newline at end of file +} diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInput.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInput.java index e06b9d7993b..1dfe63ac4cd 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInput.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInput.java @@ -8,9 +8,9 @@ */ public interface MultipartInput { - List getParts(); + List getParts(); - String getPreamble(); + String getPreamble(); /** * Call this method to delete any temporary files created from unmarshalling this multipart message diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInputImpl.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInputImpl.java index 72de219779a..28bc7822f71 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInputImpl.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartInputImpl.java @@ -194,14 +194,14 @@ public MultipartInputImpl(MediaType contentType, Providers workers) this.contentType = contentType; this.workers = workers; HttpRequest httpRequest = ResteasyProviderFactory - .getContextData(HttpRequest.class); + .getContextData(HttpRequest.class); if (httpRequest != null) { String defaultContentType = (String) httpRequest .getAttribute(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY); if (defaultContentType != null) this.defaultPartContentType = MediaType - .valueOf(defaultContentType); + .valueOf(defaultContentType); this.defaultPartCharset = (String) httpRequest.getAttribute(InputPart.DEFAULT_CHARSET_PROPERTY); if (defaultPartCharset != null) { @@ -237,16 +237,16 @@ public void parse(InputStream is) throws IOException } protected InputStream addHeaderToHeadlessStream(InputStream is) - throws UnsupportedEncodingException + throws UnsupportedEncodingException { return new SequenceInputStream(createHeaderInputStream(), is); } protected InputStream createHeaderInputStream() - throws UnsupportedEncodingException + throws UnsupportedEncodingException { String header = HttpHeaders.CONTENT_TYPE + ": " + contentType - + "\r\n\r\n"; + + "\r\n\r\n"; return new ByteArrayInputStream(header.getBytes(StandardCharsets.UTF_8)); } @@ -317,7 +317,7 @@ public void setMediaType(MediaType mediaType) @SuppressWarnings("unchecked") public T getBody(Class type, Type genericType) - throws IOException + throws IOException { if (MultipartInput.class.equals(type)) { @@ -410,29 +410,29 @@ public boolean isContentTypeFromMessage() public static void main(String[] args) throws Exception { String input = "URLSTR: file:/Users/billburke/jboss/resteasy-jaxrs/resteasy-jaxrs/src/test/test-data/data.txt\r\n" - + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n" - + "Content-Disposition: form-data; name=\"part1\"\r\n" - + "Content-Type: text/plain; charset=US-ASCII\r\n" - + "Content-Transfer-Encoding: 8bit\r\n" - + "\r\n" - + "This is Value 1\r\n" - + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n" - + "Content-Disposition: form-data; name=\"part2\"\r\n" - + "Content-Type: text/plain; charset=US-ASCII\r\n" - + "Content-Transfer-Encoding: 8bit\r\n" - + "\r\n" - + "This is Value 2\r\n" - + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n" - + "Content-Disposition: form-data; name=\"data.txt\"; filename=\"data.txt\"\r\n" - + "Content-Type: application/octet-stream; charset=ISO-8859-1\r\n" - + "Content-Transfer-Encoding: binary\r\n" - + "\r\n" - + "hello world\r\n" + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3--"; + + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n" + + "Content-Disposition: form-data; name=\"part1\"\r\n" + + "Content-Type: text/plain; charset=US-ASCII\r\n" + + "Content-Transfer-Encoding: 8bit\r\n" + + "\r\n" + + "This is Value 1\r\n" + + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n" + + "Content-Disposition: form-data; name=\"part2\"\r\n" + + "Content-Type: text/plain; charset=US-ASCII\r\n" + + "Content-Transfer-Encoding: 8bit\r\n" + + "\r\n" + + "This is Value 2\r\n" + + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3\r\n" + + "Content-Disposition: form-data; name=\"data.txt\"; filename=\"data.txt\"\r\n" + + "Content-Type: application/octet-stream; charset=ISO-8859-1\r\n" + + "Content-Transfer-Encoding: binary\r\n" + + "\r\n" + + "hello world\r\n" + "--B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3--"; ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes()); Map parameters = new LinkedHashMap(); parameters.put("boundary", "B98hgCmKsQ-B5AUFnm2FnDRCgHPDE3"); MediaType contentType = new MediaType("multipart", "form-data", - parameters); + parameters); MultipartInputImpl multipart = new MultipartInputImpl(contentType, null); multipart.parse(bais); diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartReader.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartReader.java index 06d7ef6704a..d4c0850b288 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartReader.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartReader.java @@ -24,9 +24,7 @@ @Consumes("multipart/*") public class MultipartReader implements MessageBodyReader { - protected - @Context - Providers workers; + protected @Context Providers workers; public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInput.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInput.java index d1ae919ede3..9cae4eeff6d 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInput.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInput.java @@ -14,45 +14,45 @@ */ public interface MultipartRelatedInput extends MultipartInput { - /** - * The type parameter as it was read from the content-type header of the - * multipart/related message. A well formed multipart/related message always - * has this parameter. This is the type of the root part of the message. If - * a content-type header is presented in the root part as well it should - * hold the same value. - * - * @return the type parameter of the content-type header of the message, - * null if there was no such parameter - */ - String getType(); + /** + * The type parameter as it was read from the content-type header of the + * multipart/related message. A well formed multipart/related message always + * has this parameter. This is the type of the root part of the message. If + * a content-type header is presented in the root part as well it should + * hold the same value. + * + * @return the type parameter of the content-type header of the message, + * null if there was no such parameter + */ + String getType(); - /** - * A start parameter is not mandatory in a message. If it is presented it - * holds the id of the root part. - * - * @return the start parameter of the content-type header of the message, - * null if there was no such parameter - */ - String getStart(); + /** + * A start parameter is not mandatory in a message. If it is presented it + * holds the id of the root part. + * + * @return the start parameter of the content-type header of the message, + * null if there was no such parameter + */ + String getStart(); - /** - * Optional. - * - * @return the start-info parameter of the content-type header of the - * message, null if there was no such parameter - */ - String getStartInfo(); + /** + * Optional. + * + * @return the start-info parameter of the content-type header of the + * message, null if there was no such parameter + */ + String getStartInfo(); - /** - * @return the root part of the message. If a start parameter was set in the - * message header the part with that id is returned. If no start - * parameter was set the first part is returned. - */ - InputPart getRootPart(); + /** + * @return the root part of the message. If a start parameter was set in the + * message header the part with that id is returned. If no start + * parameter was set the first part is returned. + */ + InputPart getRootPart(); - /** - * @return a map holding all parts with their unique id-s as keys. The root - * part and the related parts too. - */ - Map getRelatedMap(); + /** + * @return a map holding all parts with their unique id-s as keys. The root + * part and the related parts too. + */ + Map getRelatedMap(); } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInputImpl.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInputImpl.java index 698f937219e..9162470a853 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInputImpl.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedInputImpl.java @@ -19,54 +19,54 @@ * @version $Revision: 1 $ */ public class MultipartRelatedInputImpl extends MultipartInputImpl implements - MultipartRelatedInput { - private Map relatedMap = new LinkedHashMap(); - private String start; - private String startInfo; - private String type; - private InputPart rootPart; + MultipartRelatedInput { + private Map relatedMap = new LinkedHashMap(); + private String start; + private String startInfo; + private String type; + private InputPart rootPart; - public MultipartRelatedInputImpl(MediaType contentType, Providers workers) { - super(contentType, workers); - } + public MultipartRelatedInputImpl(MediaType contentType, Providers workers) { + super(contentType, workers); + } - @Override - public void parse(InputStream is) throws IOException { - super.parse(is); - ContentTypeField contentTypeField = (ContentTypeField) mimeMessage - .getHeader().getField(FieldName.CONTENT_TYPE); - start = contentTypeField.getParameter("start"); - startInfo = contentTypeField.getParameter("start-info"); - type = contentTypeField.getParameter("type"); - rootPart = start == null ? getParts().get(0) : relatedMap.get(start); - } + @Override + public void parse(InputStream is) throws IOException { + super.parse(is); + ContentTypeField contentTypeField = (ContentTypeField) mimeMessage + .getHeader().getField(FieldName.CONTENT_TYPE); + start = contentTypeField.getParameter("start"); + startInfo = contentTypeField.getParameter("start-info"); + type = contentTypeField.getParameter("type"); + rootPart = start == null ? getParts().get(0) : relatedMap.get(start); + } - @Override - protected InputPart extractPart(BodyPart bodyPart) throws IOException { - InputPart inputPart = super.extractPart(bodyPart); - relatedMap - .put(inputPart.getHeaders().getFirst("Content-ID"), inputPart); - return inputPart; - } + @Override + protected InputPart extractPart(BodyPart bodyPart) throws IOException { + InputPart inputPart = super.extractPart(bodyPart); + relatedMap + .put(inputPart.getHeaders().getFirst("Content-ID"), inputPart); + return inputPart; + } - public Map getRelatedMap() { - return relatedMap; - } + public Map getRelatedMap() { + return relatedMap; + } - public InputPart getRootPart() { - return rootPart; - } + public InputPart getRootPart() { + return rootPart; + } - public String getStart() { - return start; - } + public String getStart() { + return start; + } - public String getStartInfo() { - return startInfo; - } + public String getStartInfo() { + return startInfo; + } - public String getType() { - return type; - } + public String getType() { + return type; + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedOutput.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedOutput.java index c1ef93c27f0..c7476661f59 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedOutput.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedOutput.java @@ -26,94 +26,94 @@ * @version $Revision: 1 $ */ public class MultipartRelatedOutput extends MultipartOutput { - private String startInfo; + private String startInfo; - /** - * The part that will be used as the root. - * - * @return the first in the list of added parts. - */ - public OutputPart getRootPart() { - return getParts().get(0); - } + /** + * The part that will be used as the root. + * + * @return the first in the list of added parts. + */ + public OutputPart getRootPart() { + return getParts().get(0); + } - /** - * Used to add parts to the multipart output message. - * - * @param entity - * the object representing the part's body - * @param mediaType - * the Content-Type of the part - * @param contentId - * the Content-ID to be used as identification for the current - * part, optional, if null one will be generated - * @param contentTransferEncoding - * The value to be used for the Content-Transfer-Encoding header - * field of the part. It's optional, if you don't want to set - * this pass null. Example values are: "7bit", - * "quoted-printable", "base64", "8bit", "binary" - * @return {@link OutputPart} - */ - public OutputPart addPart(Object entity, MediaType mediaType, - String contentId, String contentTransferEncoding) { - OutputPart outputPart = super.addPart(entity, mediaType); - if (contentTransferEncoding != null) - outputPart.getHeaders().putSingle("Content-Transfer-Encoding", - contentTransferEncoding); - if (contentId != null) - outputPart.getHeaders().putSingle("Content-ID", contentId); - return outputPart; - } + /** + * Used to add parts to the multipart output message. + * + * @param entity + * the object representing the part's body + * @param mediaType + * the Content-Type of the part + * @param contentId + * the Content-ID to be used as identification for the current + * part, optional, if null one will be generated + * @param contentTransferEncoding + * The value to be used for the Content-Transfer-Encoding header + * field of the part. It's optional, if you don't want to set + * this pass null. Example values are: "7bit", + * "quoted-printable", "base64", "8bit", "binary" + * @return {@link OutputPart} + */ + public OutputPart addPart(Object entity, MediaType mediaType, + String contentId, String contentTransferEncoding) { + OutputPart outputPart = super.addPart(entity, mediaType); + if (contentTransferEncoding != null) + outputPart.getHeaders().putSingle("Content-Transfer-Encoding", + contentTransferEncoding); + if (contentId != null) + outputPart.getHeaders().putSingle("Content-ID", contentId); + return outputPart; + } - /** - * Returns the start-info parameter of the Content-Type. This is an optional - * parameter. - * - * As described in RFC2387: - * - * 3.3. The Start-Info Parameter - * - * Additional information can be provided to an application by the - * start-info parameter. It contains either a string or points, via a - * content-ID, to another MIME entity in the message. A typical use might be - * to provide additional command line parameters or a MIME entity giving - * auxiliary information for processing the compound object. - * - * Applications that use Multipart/Related must specify the interpretation - * of start-info. User Agents shall provide the parameter's value to the - * processing application. Processes can distinguish a start-info reference - * from a token or quoted-string by examining the first non-white-space - * character, ">" indicates a reference. - * - * @return the currently configured start-info - */ - public String getStartInfo() { - return startInfo; - } + /** + * Returns the start-info parameter of the Content-Type. This is an optional + * parameter. + * + * As described in RFC2387: + * + * 3.3. The Start-Info Parameter + * + * Additional information can be provided to an application by the + * start-info parameter. It contains either a string or points, via a + * content-ID, to another MIME entity in the message. A typical use might be + * to provide additional command line parameters or a MIME entity giving + * auxiliary information for processing the compound object. + * + * Applications that use Multipart/Related must specify the interpretation + * of start-info. User Agents shall provide the parameter's value to the + * processing application. Processes can distinguish a start-info reference + * from a token or quoted-string by examining the first non-white-space + * character, ">" indicates a reference. + * + * @return the currently configured start-info + */ + public String getStartInfo() { + return startInfo; + } - /** - * Sets the start-info parameter of the Content-Type. This is an optional - * parameter. - * - * As described in RFC2387: - * - * 3.3. The Start-Info Parameter - * - * Additional information can be provided to an application by the - * start-info parameter. It contains either a string or points, via a - * content-ID, to another MIME entity in the message. A typical use might be - * to provide additional command line parameters or a MIME entity giving - * auxiliary information for processing the compound object. - * - * Applications that use Multipart/Related must specify the interpretation - * of start-info. User Agents shall provide the parameter's value to the - * processing application. Processes can distinguish a start-info reference - * from a token or quoted-string by examining the first non-white-space - * character, ">" indicates a reference. - * - * @param startInfo the value to be set - */ - public void setStartInfo(String startInfo) { - this.startInfo = startInfo; - } + /** + * Sets the start-info parameter of the Content-Type. This is an optional + * parameter. + * + * As described in RFC2387: + * + * 3.3. The Start-Info Parameter + * + * Additional information can be provided to an application by the + * start-info parameter. It contains either a string or points, via a + * content-ID, to another MIME entity in the message. A typical use might be + * to provide additional command line parameters or a MIME entity giving + * auxiliary information for processing the compound object. + * + * Applications that use Multipart/Related must specify the interpretation + * of start-info. User Agents shall provide the parameter's value to the + * processing application. Processes can distinguish a start-info reference + * from a token or quoted-string by examining the first non-white-space + * character, ">" indicates a reference. + * + * @param startInfo the value to be set + */ + public void setStartInfo(String startInfo) { + this.startInfo = startInfo; + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedReader.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedReader.java index 41a2418704d..21b5b73005d 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedReader.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedReader.java @@ -26,11 +26,9 @@ @Provider @Consumes("multipart/related") public class MultipartRelatedReader implements - MessageBodyReader + MessageBodyReader { - protected - @Context - Providers workers; + protected @Context Providers workers; public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) @@ -41,13 +39,13 @@ public boolean isReadable(Class type, Type genericType, public MultipartRelatedInput readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException + throws IOException, WebApplicationException { String boundary = mediaType.getParameters().get("boundary"); if (boundary == null) throw new IOException(Messages.MESSAGES.unableToGetBoundary()); MultipartRelatedInputImpl input = new MultipartRelatedInputImpl( - mediaType, workers); + mediaType, workers); input.parse(entityStream); return input; } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedWriter.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedWriter.java index b0dd96175d5..23a8d3deb78 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedWriter.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/MultipartRelatedWriter.java @@ -21,7 +21,7 @@ @Provider @Produces("multipart/related") public class MultipartRelatedWriter extends AbstractMultipartRelatedWriter - implements MessageBodyWriter + implements MessageBodyWriter { public boolean isWriteable(Class type, Type genericType, @@ -41,10 +41,10 @@ public void writeTo(MultipartRelatedOutput multipartRelatedOutput, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, - WebApplicationException + WebApplicationException { writeRelated(multipartRelatedOutput, mediaType, httpHeaders, - entityStream); + entityStream); } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/OutputPart.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/OutputPart.java index db96875c2d3..84f5cced5b5 100644 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/OutputPart.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/OutputPart.java @@ -21,7 +21,7 @@ public class OutputPart public OutputPart(Object entity, Class type, Type genericType, MediaType mediaType) { - this(entity, type, genericType, mediaType, null); + this(entity, type, genericType, mediaType, null); } public OutputPart(Object entity, Class type, Type genericType, MediaType mediaType, String filename) @@ -60,6 +60,6 @@ public MediaType getMediaType() public String getFilename() { - return filename; + return filename; } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedJAXBProvider.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedJAXBProvider.java index 5638db6618c..c6372f42af9 100755 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedJAXBProvider.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedJAXBProvider.java @@ -40,178 +40,178 @@ * @version $Revision: 1 $ */ public class XopWithMultipartRelatedJAXBProvider extends - AbstractJAXBProvider { - - private static class XopAttachmentMarshaller extends AttachmentMarshaller { - private final MultipartRelatedOutput xopPackage; - - private XopAttachmentMarshaller(MultipartRelatedOutput xopPackage) { - this.xopPackage = xopPackage; - } - - @Override - public String addMtomAttachment(DataHandler data, - String elementNamespace, String elementLocalName) { - return addBinary(data.getDataSource(), data.getContentType()); - } - - @Override - public String addMtomAttachment(byte[] data, int offset, int length, - String mimeType, String elementNamespace, - String elementLocalName) { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - data, offset, length); - return addBinary(byteArrayInputStream, mimeType); - } - - protected String addBinary(Object object, String mimeType) { - String addrSpec = ContentIDUtils.generateRFC822AddrSpec(); - String contentID = ContentIDUtils - .generateContentIDFromAddrSpec(addrSpec); - xopPackage.addPart(object, MediaType.valueOf(mimeType), contentID, - "binary"); - return ContentIDUtils.generateCidFromAddrSpec(addrSpec); - } - - @Override - public String addSwaRefAttachment(DataHandler data) { - throw new UnsupportedOperationException(Messages.MESSAGES.swaRefsNotSupported()); - } - - @Override - public boolean isXOPPackage() { - return true; - } - } - - private static class InputPartBackedDataSource implements DataSource { - private final String cid; - private final InputPart inputPart; - - private InputPartBackedDataSource(String cid, InputPart inputPart) { - this.cid = cid; - this.inputPart = inputPart; - } - - public String getContentType() { - return inputPart.getMediaType().toString(); - } - - public String getName() { - return cid; - } - - public InputStream getInputStream() throws IOException { - return inputPart.getBody(InputStream.class, null); - } - - public OutputStream getOutputStream() throws IOException { - throw new IOException(Messages.MESSAGES.dataSourceRepresentsXopMessagePart()); - } - } - - private static class XopAttachmentUnmarshaller extends - AttachmentUnmarshaller { - - private final MultipartRelatedInput xopPackage; - - private XopAttachmentUnmarshaller(MultipartRelatedInput xopPackage) { - this.xopPackage = xopPackage; - } - - @Override - public byte[] getAttachmentAsByteArray(String cid) { - InputPart inputPart = getInputPart(cid); - try { - return inputPart.getBody(byte[].class, null); - } catch (IOException e) { - throw new IllegalArgumentException(Messages.MESSAGES.exceptionWhileExtractionAttachment(cid), e); - } - } - - @Override - public DataHandler getAttachmentAsDataHandler(final String cid) { - final InputPart inputPart = getInputPart(cid); - return new DataHandler( - new InputPartBackedDataSource(cid, inputPart)); - } - - protected InputPart getInputPart(String cid) { - String contentID = ContentIDUtils.convertCidToContentID(cid); - InputPart inputPart = xopPackage.getRelatedMap().get(contentID); - if (inputPart == null) - throw new IllegalArgumentException(Messages.MESSAGES.noAttachmentFound(cid, contentID)); - return inputPart; - } - - @Override - public boolean isXOPPackage() { - return true; - } - } - - public XopWithMultipartRelatedJAXBProvider(Providers providers) { - super(); - this.providers = providers; - } - - @Override - protected boolean isReadWritable(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType) { - throw new UnsupportedOperationException(Messages.MESSAGES.notMeantForStandaloneUsage()); - } - - public Object readFrom(Class type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, - InputStream entityStream, final MultipartRelatedInput xopPackage) - throws IOException { - try { - LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); - InputPart rootPart = xopPackage.getRootPart(); - JAXBContext jaxb = findJAXBContext(type, annotations, rootPart - .getMediaType(), true); - Unmarshaller unmarshaller = jaxb.createUnmarshaller(); - unmarshaller - .setAttachmentUnmarshaller(new XopAttachmentUnmarshaller( - xopPackage)); - return unmarshaller.unmarshal(new StreamSource(rootPart.getBody( - InputStream.class, null))); - } catch (JAXBException e) { - Response response = Response.serverError().build(); - throw new WebApplicationException(e, response); - } - } - - public void writeTo(Object t, Class type, Type genericType, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, - final MultipartRelatedOutput xopPackage) throws IOException { - try { - LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); - Map mediaTypeParameters = new LinkedHashMap(); - mediaTypeParameters.put("charset", StandardCharsets.UTF_8.name()); - mediaTypeParameters.put("type", "text/xml"); - - MediaType xopRootMediaType = new MediaType("application", - "xop+xml", mediaTypeParameters); - - Marshaller marshaller = getMarshaller(type, annotations, - xopRootMediaType); - marshaller.setAttachmentMarshaller(new XopAttachmentMarshaller( - xopPackage)); - ByteArrayOutputStream xml = new ByteArrayOutputStream(); - marshaller.marshal(t, xml); - - OutputPart outputPart = xopPackage.addPart(xml.toByteArray(), - xopRootMediaType, ContentIDUtils.generateContentID(), null); - List outputParts = xopPackage.getParts(); - outputParts.remove(outputPart); - outputParts.add(0, outputPart); - } catch (JAXBException e) { - Response response = Response.serverError().build(); - throw new WebApplicationException(e, response); - } - } + AbstractJAXBProvider { + + private static class XopAttachmentMarshaller extends AttachmentMarshaller { + private final MultipartRelatedOutput xopPackage; + + private XopAttachmentMarshaller(MultipartRelatedOutput xopPackage) { + this.xopPackage = xopPackage; + } + + @Override + public String addMtomAttachment(DataHandler data, + String elementNamespace, String elementLocalName) { + return addBinary(data.getDataSource(), data.getContentType()); + } + + @Override + public String addMtomAttachment(byte[] data, int offset, int length, + String mimeType, String elementNamespace, + String elementLocalName) { + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( + data, offset, length); + return addBinary(byteArrayInputStream, mimeType); + } + + protected String addBinary(Object object, String mimeType) { + String addrSpec = ContentIDUtils.generateRFC822AddrSpec(); + String contentID = ContentIDUtils + .generateContentIDFromAddrSpec(addrSpec); + xopPackage.addPart(object, MediaType.valueOf(mimeType), contentID, + "binary"); + return ContentIDUtils.generateCidFromAddrSpec(addrSpec); + } + + @Override + public String addSwaRefAttachment(DataHandler data) { + throw new UnsupportedOperationException(Messages.MESSAGES.swaRefsNotSupported()); + } + + @Override + public boolean isXOPPackage() { + return true; + } + } + + private static class InputPartBackedDataSource implements DataSource { + private final String cid; + private final InputPart inputPart; + + private InputPartBackedDataSource(String cid, InputPart inputPart) { + this.cid = cid; + this.inputPart = inputPart; + } + + public String getContentType() { + return inputPart.getMediaType().toString(); + } + + public String getName() { + return cid; + } + + public InputStream getInputStream() throws IOException { + return inputPart.getBody(InputStream.class, null); + } + + public OutputStream getOutputStream() throws IOException { + throw new IOException(Messages.MESSAGES.dataSourceRepresentsXopMessagePart()); + } + } + + private static class XopAttachmentUnmarshaller extends + AttachmentUnmarshaller { + + private final MultipartRelatedInput xopPackage; + + private XopAttachmentUnmarshaller(MultipartRelatedInput xopPackage) { + this.xopPackage = xopPackage; + } + + @Override + public byte[] getAttachmentAsByteArray(String cid) { + InputPart inputPart = getInputPart(cid); + try { + return inputPart.getBody(byte[].class, null); + } catch (IOException e) { + throw new IllegalArgumentException(Messages.MESSAGES.exceptionWhileExtractionAttachment(cid), e); + } + } + + @Override + public DataHandler getAttachmentAsDataHandler(final String cid) { + final InputPart inputPart = getInputPart(cid); + return new DataHandler( + new InputPartBackedDataSource(cid, inputPart)); + } + + protected InputPart getInputPart(String cid) { + String contentID = ContentIDUtils.convertCidToContentID(cid); + InputPart inputPart = xopPackage.getRelatedMap().get(contentID); + if (inputPart == null) + throw new IllegalArgumentException(Messages.MESSAGES.noAttachmentFound(cid, contentID)); + return inputPart; + } + + @Override + public boolean isXOPPackage() { + return true; + } + } + + public XopWithMultipartRelatedJAXBProvider(Providers providers) { + super(); + this.providers = providers; + } + + @Override + protected boolean isReadWritable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + throw new UnsupportedOperationException(Messages.MESSAGES.notMeantForStandaloneUsage()); + } + + public Object readFrom(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, + InputStream entityStream, final MultipartRelatedInput xopPackage) + throws IOException { + try { + LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); + InputPart rootPart = xopPackage.getRootPart(); + JAXBContext jaxb = findJAXBContext(type, annotations, rootPart + .getMediaType(), true); + Unmarshaller unmarshaller = jaxb.createUnmarshaller(); + unmarshaller + .setAttachmentUnmarshaller(new XopAttachmentUnmarshaller( + xopPackage)); + return unmarshaller.unmarshal(new StreamSource(rootPart.getBody( + InputStream.class, null))); + } catch (JAXBException e) { + Response response = Response.serverError().build(); + throw new WebApplicationException(e, response); + } + } + + public void writeTo(Object t, Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, + final MultipartRelatedOutput xopPackage) throws IOException { + try { + LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); + Map mediaTypeParameters = new LinkedHashMap(); + mediaTypeParameters.put("charset", StandardCharsets.UTF_8.name()); + mediaTypeParameters.put("type", "text/xml"); + + MediaType xopRootMediaType = new MediaType("application", + "xop+xml", mediaTypeParameters); + + Marshaller marshaller = getMarshaller(type, annotations, + xopRootMediaType); + marshaller.setAttachmentMarshaller(new XopAttachmentMarshaller( + xopPackage)); + ByteArrayOutputStream xml = new ByteArrayOutputStream(); + marshaller.marshal(t, xml); + + OutputPart outputPart = xopPackage.addPart(xml.toByteArray(), + xopRootMediaType, ContentIDUtils.generateContentID(), null); + List outputParts = xopPackage.getParts(); + outputParts.remove(outputPart); + outputParts.add(0, outputPart); + } catch (JAXBException e) { + Response response = Response.serverError().build(); + throw new WebApplicationException(e, response); + } + } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedReader.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedReader.java index a4a0f36a696..1f58f7f53da 100755 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedReader.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedReader.java @@ -29,33 +29,31 @@ @Consumes("multipart/related") public class XopWithMultipartRelatedReader implements MessageBodyReader { - protected - @Context - Providers workers; + protected @Context Providers workers; public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return FindAnnotation.findAnnotation(annotations, - XopWithMultipartRelated.class) != null - || type.isAnnotationPresent(XopWithMultipartRelated.class); + XopWithMultipartRelated.class) != null + || type.isAnnotationPresent(XopWithMultipartRelated.class); } public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException, WebApplicationException + throws IOException, WebApplicationException { String boundary = mediaType.getParameters().get("boundary"); if (boundary == null) throw new IOException(Messages.MESSAGES.unableToGetBoundary()); MultipartRelatedInputImpl input = new MultipartRelatedInputImpl( - mediaType, workers); + mediaType, workers); input.parse(entityStream); XopWithMultipartRelatedJAXBProvider xopWithMultipartRelatedJAXBProvider = new XopWithMultipartRelatedJAXBProvider( - workers); + workers); return xopWithMultipartRelatedJAXBProvider.readFrom(type, genericType, - annotations, mediaType, httpHeaders, entityStream, input); + annotations, mediaType, httpHeaders, entityStream, input); } } diff --git a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedWriter.java b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedWriter.java index f8d6c27809e..dcad684ccf7 100755 --- a/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedWriter.java +++ b/providers/multipart/src/main/java/org/jboss/resteasy/plugins/providers/multipart/XopWithMultipartRelatedWriter.java @@ -24,7 +24,7 @@ @Provider @Produces("multipart/related") public class XopWithMultipartRelatedWriter extends - AbstractMultipartRelatedWriter implements MessageBodyWriter + AbstractMultipartRelatedWriter implements MessageBodyWriter { public long getSize(Object t, Class type, Type genericType, @@ -37,23 +37,23 @@ public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return FindAnnotation.findAnnotation(annotations, - XopWithMultipartRelated.class) != null - || type.isAnnotationPresent(XopWithMultipartRelated.class); + XopWithMultipartRelated.class) != null + || type.isAnnotationPresent(XopWithMultipartRelated.class); } public void writeTo(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, - WebApplicationException + WebApplicationException { MultipartRelatedOutput xopPackage = new MultipartRelatedOutput(); XopWithMultipartRelatedJAXBProvider xopWithMultipartRelatedJAXBProvider = new XopWithMultipartRelatedJAXBProvider( - workers); + workers); xopWithMultipartRelatedJAXBProvider.writeTo(t, type, genericType, - annotations, mediaType, httpHeaders, xopPackage); + annotations, mediaType, httpHeaders, xopPackage); writeRelated(xopPackage, mediaType, httpHeaders, entityStream); } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/AtomEntryProvider.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/AtomEntryProvider.java index c0e7d6b011f..8f04df65930 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/AtomEntryProvider.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/AtomEntryProvider.java @@ -99,7 +99,7 @@ public void writeTo(Entry entry, Class type, Type genericType, Annotation[] a set.add(Entry.class); if (entry.getAnyOtherJAXBObject() != null) { - set.add(entry.getAnyOtherJAXBObject().getClass()); + set.add(entry.getAnyOtherJAXBObject().getClass()); } if (entry.getContent() != null && entry.getContent().getJAXBObject() != null) { diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Entry.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Entry.java index db57a95d1bf..a20215147f0 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Entry.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Entry.java @@ -100,7 +100,7 @@ @XmlRootElement(name = "entry") @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(propOrder = {"titleElement", "links", "categories", "updated", "id", "published", "authors", "contributors", "source", - "rightsElement", "content", "summaryElement", "anyOther"}) + "rightsElement", "content", "summaryElement", "anyOther"}) public class Entry extends CommonAttributes { private List authors = new ArrayList(); @@ -153,20 +153,20 @@ public void setId(URI id) @XmlElement(name = "title") public Text getTitleElement() { - return title; + return title; } public void setTitleElement(Text title) { - this.title = title; + this.title = title; } @XmlTransient public String getTitle() { - if (this.title == null) - { - return null; - } + if (this.title == null) + { + return null; + } return title.getText(); } @@ -174,7 +174,7 @@ public void setTitle(String title) { if (this.title == null) { - this.title = new Text(); + this.title = new Text(); } this.title.setText(title); } @@ -255,20 +255,20 @@ public void setRightsElement(Text rights) @XmlTransient public String getRights() { - if (rights == null) - { - return null; - } - return rights.getText(); + if (rights == null) + { + return null; + } + return rights.getText(); } public void setRights(String rights) { - if (this.rights == null) - { - this.rights = new Text(); - } - this.rights.setText(rights); + if (this.rights == null) + { + this.rights = new Text(); + } + this.rights.setText(rights); } @XmlElement @@ -295,20 +295,20 @@ public void setSummaryElement(Text summary) @XmlTransient public String getSummary() { - if (rights == null) - { - return null; - } - return rights.getText(); + if (rights == null) + { + return null; + } + return rights.getText(); } public void setSummary(String summary) { - if (this.summary == null) - { - this.summary = new Text(); - } - this.summary.setText(summary); + if (this.summary == null) + { + this.summary = new Text(); + } + this.summary.setText(summary); } @@ -326,7 +326,7 @@ public Element getAnyOtherElement() { if (obj instanceof Element) { - anyOtherElement = (Element) obj; + anyOtherElement = (Element) obj; return anyOtherElement; } } @@ -336,10 +336,10 @@ public Element getAnyOtherElement() @XmlMixed @XmlAnyElement(lax = true) public List getAnyOther() { - if (anyOther == null) { - anyOther = new ArrayList(); - } - return this.anyOther; + if (anyOther == null) { + anyOther = new ArrayList(); + } + return this.anyOther; } /** * Extract the content as the provided JAXB annotated type. @@ -354,48 +354,48 @@ public List getAnyOther() { * @return null if there is no XML content * @throws JAXBException jaxb exception */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - public T getAnyOtherJAXBObject(Class clazz, Class... otherPossibleClasses) throws JAXBException { - JAXBContext ctx = null; - Class[] classes = {clazz}; - if (otherPossibleClasses != null && otherPossibleClasses.length > 0) { - classes = new Class[1 + otherPossibleClasses.length]; - classes[0] = clazz; - for (int i = 0; i < otherPossibleClasses.length; i++) classes[i + 1] = otherPossibleClasses[i]; - } - if (finder != null) { - ctx = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, classes); - } else { - ctx = JAXBContext.newInstance(classes); - } + @SuppressWarnings({ "unchecked", "rawtypes" }) + public T getAnyOtherJAXBObject(Class clazz, Class... otherPossibleClasses) throws JAXBException { + JAXBContext ctx = null; + Class[] classes = {clazz}; + if (otherPossibleClasses != null && otherPossibleClasses.length > 0) { + classes = new Class[1 + otherPossibleClasses.length]; + classes[0] = clazz; + for (int i = 0; i < otherPossibleClasses.length; i++) classes[i + 1] = otherPossibleClasses[i]; + } + if (finder != null) { + ctx = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, classes); + } else { + ctx = JAXBContext.newInstance(classes); + } - Object obj = null; + Object obj = null; - if (getAnyOtherElement() != null) { - obj = ctx.createUnmarshaller().unmarshal(getAnyOtherElement()); - } else { - if (getAnyOther().size() == 0) return null; - for (Object _obj : getAnyOther()) { - for (Class _clazz : classes) { - if (_obj.getClass().equals(_clazz)) { - obj = _obj; - break; - } - } + if (getAnyOtherElement() != null) { + obj = ctx.createUnmarshaller().unmarshal(getAnyOtherElement()); + } else { + if (getAnyOther().size() == 0) return null; + for (Object _obj : getAnyOther()) { + for (Class _clazz : classes) { + if (_obj.getClass().equals(_clazz)) { + obj = _obj; + break; + } } + } - if (obj == null) - return null; - } + if (obj == null) + return null; + } - if (obj instanceof JAXBElement) { - anyOtherJaxbObject = ((JAXBElement) obj).getValue(); - return (T) anyOtherJaxbObject; - } else { - anyOtherJaxbObject = obj; - return (T) obj; - } - } + if (obj instanceof JAXBElement) { + anyOtherJaxbObject = ((JAXBElement) obj).getValue(); + return (T) anyOtherJaxbObject; + } else { + anyOtherJaxbObject = obj; + return (T) obj; + } + } /** @@ -416,11 +416,11 @@ public void setAnyOtherJAXBObject(Object obj) if (anyOtherJaxbObject != null && anyOther != null) anyOther.clear(); if (!obj.getClass().isAnnotationPresent(XmlRootElement.class) && obj.getClass().isAnnotationPresent(XmlType.class)) { - anyOther.add(JAXBXmlTypeProvider.wrapInJAXBElement(obj, obj.getClass())); + anyOther.add(JAXBXmlTypeProvider.wrapInJAXBElement(obj, obj.getClass())); } else { - anyOther.add(obj); + anyOther.add(obj); } anyOtherJaxbObject = obj; } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/RelativeLink.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/RelativeLink.java index 9130e75c0f4..15b407bd448 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/RelativeLink.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/RelativeLink.java @@ -47,4 +47,4 @@ public RelativeLink(String rel, String relativeLink, String mediaType) this(rel, relativeLink); this.setType(MediaType.valueOf(mediaType)); } -} \ No newline at end of file +} diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Source.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Source.java index 3443c8d066a..a8d9adb1126 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Source.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Source.java @@ -55,7 +55,7 @@ */ @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(propOrder = {"title", "subtitle", "categories", "updated", "id", "links", "authors", "contributors", "rights", - "icon", "logo", "generator"}) + "icon", "logo", "generator"}) public class Source extends CommonAttributes { private List authors = new ArrayList(); diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Text.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Text.java index 4c3220ad881..506a20e851f 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Text.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Text.java @@ -48,227 +48,227 @@ public class Text extends CommonAttributes { - private String type; + private String type; - private MediaType mediaType; + private MediaType mediaType; - private String text; + private String text; - private Element element; + private Element element; - private List value; + private List value; - private Object jaxbObject; + private Object jaxbObject; - protected JAXBContextFinder finder; + protected JAXBContextFinder finder; - public Text() - { - } + public Text() + { + } - public Text(String text, String type) - { - setText(text); - setRawType(type); - } + public Text(String text, String type) + { + setText(text); + setRawType(type); + } - public Text(String text) - { - setText(text); - } + public Text(String text) + { + setText(text); + } - protected void setFinder(JAXBContextFinder finder) - { - this.finder = finder; - } + protected void setFinder(JAXBContextFinder finder) + { + this.finder = finder; + } - @XmlAnyElement - @XmlMixed - public List getValue() - { - return value; - } + @XmlAnyElement + @XmlMixed + public List getValue() + { + return value; + } - public void setValue(List value) - { - this.value = value; - } + public void setValue(List value) + { + this.value = value; + } - /** - * Mime type. - * - * @return media type - */ - @XmlTransient - public MediaType getType() - { - if (mediaType == null) - { - if (type.equals("html")) mediaType = MediaType.TEXT_HTML_TYPE; - else if (type.equals("text")) mediaType = MediaType.TEXT_PLAIN_TYPE; - else if (type.equals("xhtml")) mediaType = MediaType.APPLICATION_XHTML_XML_TYPE; - else mediaType = MediaType.valueOf(type); - } - return mediaType; - } + /** + * Mime type. + * + * @return media type + */ + @XmlTransient + public MediaType getType() + { + if (mediaType == null) + { + if (type.equals("html")) mediaType = MediaType.TEXT_HTML_TYPE; + else if (type.equals("text")) mediaType = MediaType.TEXT_PLAIN_TYPE; + else if (type.equals("xhtml")) mediaType = MediaType.APPLICATION_XHTML_XML_TYPE; + else mediaType = MediaType.valueOf(type); + } + return mediaType; + } - public void setType(MediaType type) - { - mediaType = type; - if (type.equals(MediaType.TEXT_PLAIN_TYPE)) this.type = "text"; - else if (type.equals(MediaType.TEXT_HTML_TYPE)) this.type = "html"; - else if (type.equals(MediaType.APPLICATION_XHTML_XML_TYPE)) this.type = "xhtml"; - else this.type = type.toString(); - } + public void setType(MediaType type) + { + mediaType = type; + if (type.equals(MediaType.TEXT_PLAIN_TYPE)) this.type = "text"; + else if (type.equals(MediaType.TEXT_HTML_TYPE)) this.type = "html"; + else if (type.equals(MediaType.APPLICATION_XHTML_XML_TYPE)) this.type = "xhtml"; + else this.type = type.toString(); + } - @XmlAttribute(name = "type") - public String getRawType() - { - return type; - } + @XmlAttribute(name = "type") + public String getRawType() + { + return type; + } - public void setRawType(String type) - { - this.type = type; - } + public void setRawType(String type) + { + this.type = type; + } - /** - * If content is text, return it as a String. Otherwise, if content is not text this will return null. - * - * @return text - */ - @XmlTransient - public String getText() - { - if (value == null) return null; - if (value.size() == 0) return null; - if (text != null) return text; - StringBuffer buf = new StringBuffer(); - for (Object obj : value) - { - if (obj instanceof String) buf.append(obj.toString()); - } - text = buf.toString(); - return text; - } + /** + * If content is text, return it as a String. Otherwise, if content is not text this will return null. + * + * @return text + */ + @XmlTransient + public String getText() + { + if (value == null) return null; + if (value.size() == 0) return null; + if (text != null) return text; + StringBuffer buf = new StringBuffer(); + for (Object obj : value) + { + if (obj instanceof String) buf.append(obj.toString()); + } + text = buf.toString(); + return text; + } - /** - * Set content as text. - * - * @param text text - */ - public void setText(String text) - { - if (value == null) value = new ArrayList(); - if (this.text != null && value != null) value.clear(); - this.text = text; - value.add(text); - } + /** + * Set content as text. + * + * @param text text + */ + public void setText(String text) + { + if (value == null) value = new ArrayList(); + if (this.text != null && value != null) value.clear(); + this.text = text; + value.add(text); + } - /** - * Get content as an XML Element if the content is XML. Otherwise, this will just return null. - * - * @return {@link Element} - */ - @XmlTransient - public Element getElement() - { - if (value == null) return null; - if (element != null) return element; - for (Object obj : value) - { - if (obj instanceof Element) - { - element = (Element) obj; - return element; - } - } - return null; - } + /** + * Get content as an XML Element if the content is XML. Otherwise, this will just return null. + * + * @return {@link Element} + */ + @XmlTransient + public Element getElement() + { + if (value == null) return null; + if (element != null) return element; + for (Object obj : value) + { + if (obj instanceof Element) + { + element = (Element) obj; + return element; + } + } + return null; + } - /** - * Set the content to an XML Element. - * - * @param element {@link Element} - */ - public void setElement(Element element) - { - if (value == null) value = new ArrayList(); - if (this.element != null && value != null) value.clear(); - this.element = element; - value.add(element); + /** + * Set the content to an XML Element. + * + * @param element {@link Element} + */ + public void setElement(Element element) + { + if (value == null) value = new ArrayList(); + if (this.element != null && value != null) value.clear(); + this.element = element; + value.add(element); - } + } - /** - * Extract the content as the provided JAXB annotated type. - *

- * This method will use a cached JAXBContext used by the Resteasy JAXB providers - * or, if those are not existent, it will create a new JAXBContext from scratch - * using the class. - * - * @param clazz class type you are expecting - * @param otherPossibleClasses Other classe you want to create the JAXBContext with - * @return null if there is no XML content - * @throws JAXBException jaxb exception - */ - @SuppressWarnings(value = "unchecked") - public T getJAXBObject(Class clazz, Class... otherPossibleClasses) throws JAXBException - { - JAXBContext ctx = null; - Class[] classes = {clazz}; - if (otherPossibleClasses != null && otherPossibleClasses.length > 0) - { - classes = new Class[1 + otherPossibleClasses.length]; - classes[0] = clazz; - for (int i = 0; i < otherPossibleClasses.length; i++) classes[i + 1] = otherPossibleClasses[i]; - } - if (finder != null) - { - ctx = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, classes); - } - else - { - ctx = JAXBContext.newInstance(classes); - } - if (getElement() == null) return null; - Object obj = ctx.createUnmarshaller().unmarshal(getElement()); - if (obj instanceof JAXBElement) - { - jaxbObject = ((JAXBElement) obj).getValue(); - return (T) jaxbObject; - } - else - { - jaxbObject = obj; - return (T) obj; - } - } + /** + * Extract the content as the provided JAXB annotated type. + *

+ * This method will use a cached JAXBContext used by the Resteasy JAXB providers + * or, if those are not existent, it will create a new JAXBContext from scratch + * using the class. + * + * @param clazz class type you are expecting + * @param otherPossibleClasses Other classe you want to create the JAXBContext with + * @return null if there is no XML content + * @throws JAXBException jaxb exception + */ + @SuppressWarnings(value = "unchecked") + public T getJAXBObject(Class clazz, Class... otherPossibleClasses) throws JAXBException + { + JAXBContext ctx = null; + Class[] classes = {clazz}; + if (otherPossibleClasses != null && otherPossibleClasses.length > 0) + { + classes = new Class[1 + otherPossibleClasses.length]; + classes[0] = clazz; + for (int i = 0; i < otherPossibleClasses.length; i++) classes[i + 1] = otherPossibleClasses[i]; + } + if (finder != null) + { + ctx = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, classes); + } + else + { + ctx = JAXBContext.newInstance(classes); + } + if (getElement() == null) return null; + Object obj = ctx.createUnmarshaller().unmarshal(getElement()); + if (obj instanceof JAXBElement) + { + jaxbObject = ((JAXBElement) obj).getValue(); + return (T) jaxbObject; + } + else + { + jaxbObject = obj; + return (T) obj; + } + } - /** - * Returns previous extracted jaxbobject from a call to getJAXBObject(Class{@literal <}T{@literal >} clazz) - * or value passed in through a previous setJAXBObject(). - * - * @return jaxb object - */ - @XmlTransient - public Object getJAXBObject() - { - return jaxbObject; - } + /** + * Returns previous extracted jaxbobject from a call to getJAXBObject(Class{@literal <}T{@literal >} clazz) + * or value passed in through a previous setJAXBObject(). + * + * @return jaxb object + */ + @XmlTransient + public Object getJAXBObject() + { + return jaxbObject; + } - public void setJAXBObject(Object obj) - { - if (value == null) value = new ArrayList(); - if (jaxbObject != null && value != null) value.clear(); - if (!obj.getClass().isAnnotationPresent(XmlRootElement.class) && obj.getClass().isAnnotationPresent(XmlType.class)) - { - value.add(JAXBXmlTypeProvider.wrapInJAXBElement(obj, obj.getClass())); - } - else - { - value.add(obj); - } - jaxbObject = obj; - } + public void setJAXBObject(Object obj) + { + if (value == null) value = new ArrayList(); + if (jaxbObject != null && value != null) value.clear(); + if (!obj.getClass().isAnnotationPresent(XmlRootElement.class) && obj.getClass().isAnnotationPresent(XmlType.class)) + { + value.add(JAXBXmlTypeProvider.wrapInJAXBElement(obj, obj.getClass())); + } + else + { + value.add(obj); + } + jaxbObject = obj; + } } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppAccept.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppAccept.java index c3fb123b286..099578256fa 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppAccept.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppAccept.java @@ -46,44 +46,44 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "content" + "content" }) @XmlRootElement(name = "accept") public class AppAccept extends AppCommonAttributes { - private static final long serialVersionUID = 8792589507058023990L; - @XmlValue - protected String content; + private static final long serialVersionUID = 8792589507058023990L; + @XmlValue + protected String content; - public AppAccept() {} + public AppAccept() {} - public AppAccept(String content) { - super(); - this.content = content; - } + public AppAccept(String content) { + super(); + this.content = content; + } - /** - * Gets the value of the content property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getContent() { - return content; - } + /** + * Gets the value of the content property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getContent() { + return content; + } - /** - * Sets the value of the content property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setContent(String value) { - this.content = value; - } + /** + * Sets the value of the content property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setContent(String value) { + this.content = value; + } } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCategories.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCategories.java index ac2d2c34332..df55a9bd0fe 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCategories.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCategories.java @@ -46,128 +46,128 @@ @XmlRootElement(name = "categories") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "categories", propOrder = { - "category", "href" + "category", "href" }) public class AppCategories extends AppCommonAttributes { - private static final long serialVersionUID = 7978145545675525082L; - @XmlElements({ - @XmlElement(name = "category", namespace = "http://www.w3.org/2005/Atom", type = Category.class) - }) - protected List category; - @XmlJavaTypeAdapter( BooleanAdapter.class ) - @XmlAttribute - protected Boolean fixed; - @XmlAttribute - @XmlSchemaType(name = "anyURI") - protected String scheme; - @XmlSchemaType(name = "anyURI") - protected String href; + private static final long serialVersionUID = 7978145545675525082L; + @XmlElements({ + @XmlElement(name = "category", namespace = "http://www.w3.org/2005/Atom", type = Category.class) + }) + protected List category; + @XmlJavaTypeAdapter( BooleanAdapter.class ) + @XmlAttribute + protected Boolean fixed; + @XmlAttribute + @XmlSchemaType(name = "anyURI") + protected String scheme; + @XmlSchemaType(name = "anyURI") + protected String href; - public AppCategories() {} + public AppCategories() {} - public AppCategories(List category, Boolean fixed, String scheme, - String href) { - super(); - this.category = category; - this.fixed = fixed; - this.scheme = scheme; - this.href = href; - } + public AppCategories(List category, Boolean fixed, String scheme, + String href) { + super(); + this.category = category; + this.fixed = fixed; + this.scheme = scheme; + this.href = href; + } - /** - * Gets the value of the category property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the category property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getCategory().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Category } - * @return list of categories - * - */ - public List getCategory() { - if (category == null) { - category = new ArrayList(); - } - return this.category; - } + /** + * Gets the value of the category property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the category property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getCategory().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Category } + * @return list of categories + * + */ + public List getCategory() { + if (category == null) { + category = new ArrayList(); + } + return this.category; + } - /** - * Gets the value of the fixed property. - * - * @return - * possible object is - * {@link Boolean } - * - */ - public Boolean isFixed() { - return fixed; - } + /** + * Gets the value of the fixed property. + * + * @return + * possible object is + * {@link Boolean } + * + */ + public Boolean isFixed() { + return fixed; + } - /** - * Sets the value of the fixed property. - * - * @param value - * allowed object is - * {@link Boolean } - * - */ - public void setFixed(Boolean value) { - this.fixed = value; - } + /** + * Sets the value of the fixed property. + * + * @param value + * allowed object is + * {@link Boolean } + * + */ + public void setFixed(Boolean value) { + this.fixed = value; + } - /** - * Gets the value of the scheme property. - * - * @return possible object is {@link String } - * - */ - public String getScheme() { - return scheme; - } + /** + * Gets the value of the scheme property. + * + * @return possible object is {@link String } + * + */ + public String getScheme() { + return scheme; + } - /** - * Sets the value of the scheme property. - * - * @param value - * allowed object is {@link String } - * - */ - public void setScheme(String value) { - this.scheme = value; - } + /** + * Sets the value of the scheme property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setScheme(String value) { + this.scheme = value; + } - /** - * Gets the value of the href property. - * - * @return possible object is {@link String } - * - */ - public String getHref() { - return href; - } + /** + * Gets the value of the href property. + * + * @return possible object is {@link String } + * + */ + public String getHref() { + return href; + } - /** - * Sets the value of the href property. - * - * @param value - * allowed object is {@link String } - * - */ - public void setHref(String value) { - this.href = value; - } + /** + * Sets the value of the href property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setHref(String value) { + this.href = value; + } } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCollection.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCollection.java index b231050e367..412eded3332 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCollection.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCollection.java @@ -58,160 +58,160 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "collection", propOrder = { "href", "title", "accept", - "categories", "any" }) + "categories", "any" }) public class AppCollection extends AppCommonAttributes { - private static final long serialVersionUID = 3466473348035916400L; - @XmlAttribute - @XmlSchemaType(name = "anyURI") - protected String href; - @XmlElement(namespace = "http://www.w3.org/2005/Atom", required = true) - protected String title; - protected List accept; - protected List categories; - @XmlAnyElement(lax = true) - protected List any; + private static final long serialVersionUID = 3466473348035916400L; + @XmlAttribute + @XmlSchemaType(name = "anyURI") + protected String href; + @XmlElement(namespace = "http://www.w3.org/2005/Atom", required = true) + protected String title; + protected List accept; + protected List categories; + @XmlAnyElement(lax = true) + protected List any; - public AppCollection() {} + public AppCollection() {} - public AppCollection(String href, String title) { - super(); - this.href = href; - this.title = title; - } + public AppCollection(String href, String title) { + super(); + this.href = href; + this.title = title; + } - /** - * Gets the value of the title property. - * - * @return possible object is {@link String } - * - */ - public String getTitle() { - return title; - } + /** + * Gets the value of the title property. + * + * @return possible object is {@link String } + * + */ + public String getTitle() { + return title; + } - /** - * Sets the value of the title property. - * - * @param value - * allowed object is {@link String } - * - */ - public void setTitle(String value) { - this.title = value; - } + /** + * Sets the value of the title property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } - /** - * Gets the value of the accept property. - * - *

- * This accessor method returns a reference to the live list, not a - * snapshot. Therefore any modification you make to the returned list will - * be present inside the JAXB object. This is why there is not a - * set method for the accept property. - * - *

- * For example, to add a new item, do as follows: - * - *

-     * getAccept().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list {@link String } - * - * @return list of {@link AppAccept} - */ - public List getAccept() { - if (accept == null) { - accept = new ArrayList(); - } - return this.accept; - } + /** + * Gets the value of the accept property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the accept property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+    * getAccept().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list {@link String } + * + * @return list of {@link AppAccept} + */ + public List getAccept() { + if (accept == null) { + accept = new ArrayList(); + } + return this.accept; + } - /** - * Gets the value of the categories property. - * - *

- * This accessor method returns a reference to the live list, not a - * snapshot. Therefore any modification you make to the returned list will - * be present inside the JAXB object. This is why there is not a - * set method for the categories property. - * - *

- * For example, to add a new item, do as follows: - * - *

-     * getCategories().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link AppCategories } - * - * @return list of {@link AppCategories} - * - */ - public List getCategories() { - if (categories == null) { - categories = new ArrayList(); - } - return this.categories; - } + /** + * Gets the value of the categories property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the categories property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+    * getCategories().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link AppCategories } + * + * @return list of {@link AppCategories} + * + */ + public List getCategories() { + if (categories == null) { + categories = new ArrayList(); + } + return this.categories; + } - /** - * Gets the value of the any property. - * - *

- * This accessor method returns a reference to the live list, not a - * snapshot. Therefore any modification you make to the returned list will - * be present inside the JAXB object. This is why there is not a - * set method for the any property. - * - *

- * For example, to add a new item, do as follows: - * - *

-     * getAny().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list {@link Element } - * {@link Object } - * - * @return list of objects - * - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+    * getAny().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list {@link Element } + * {@link Object } + * + * @return list of objects + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } - /** - * Gets the value of the href property. - * - * @return possible object is {@link String } - * - */ - public String getHref() { - return href; - } + /** + * Gets the value of the href property. + * + * @return possible object is {@link String } + * + */ + public String getHref() { + return href; + } - /** - * Sets the value of the href property. - * - * @param value - * allowed object is {@link String } - * - */ - public void setHref(String value) { - this.href = value; - } + /** + * Sets the value of the href property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setHref(String value) { + this.href = value; + } } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCommonAttributes.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCommonAttributes.java index b851845fcd4..95ea1aa126a 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCommonAttributes.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppCommonAttributes.java @@ -37,109 +37,109 @@ @XmlTransient public class AppCommonAttributes implements Serializable { - private static final long serialVersionUID = -6132753912772236190L; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlSchemaType(name = "anySimpleType") - private String base; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - private String lang; - @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - private String space; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); + private static final long serialVersionUID = -6132753912772236190L; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlSchemaType(name = "anySimpleType") + private String base; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + private String lang; + @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + private String space; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); - /** - * Gets the value of the base property. - * - * @return - * possible object is - * {@link String } - * - */ - @javax.xml.bind.annotation.XmlTransient - public String getBase() { - return base; - } + /** + * Gets the value of the base property. + * + * @return + * possible object is + * {@link String } + * + */ + @javax.xml.bind.annotation.XmlTransient + public String getBase() { + return base; + } - /** - * Sets the value of the base property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setBase(String value) { - this.base = value; - } + /** + * Sets the value of the base property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setBase(String value) { + this.base = value; + } - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - @javax.xml.bind.annotation.XmlTransient - public String getLang() { - return lang; - } + /** + * Gets the value of the lang property. + * + * @return + * possible object is + * {@link String } + * + */ + @javax.xml.bind.annotation.XmlTransient + public String getLang() { + return lang; + } - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } - /** - * Gets the value of the space property. - * - * @return - * possible object is - * {@link String } - * - */ - @javax.xml.bind.annotation.XmlTransient - public String getSpace() { - return space; - } + /** + * Gets the value of the space property. + * + * @return + * possible object is + * {@link String } + * + */ + @javax.xml.bind.annotation.XmlTransient + public String getSpace() { + return space; + } - /** - * Sets the value of the space property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSpace(String value) { - this.space = value; - } + /** + * Sets the value of the space property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSpace(String value) { + this.space = value; + } - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } + /** + * Gets a map that contains attributes that aren't bound to any typed property on this class. + * + *

+ * the map is keyed by the name of the attribute and + * the value is the string value of the attribute. + * + * the map returned by this method is live, and you can add new attribute + * by updating the map directly. Because of this design, there's no setter. + * + * + * @return + * always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppService.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppService.java index 076c3e40b64..74885ce11b3 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppService.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppService.java @@ -60,11 +60,11 @@ @XmlAccessorType(XmlAccessType.FIELD) public class AppService extends AppCommonAttributes { - private static final long serialVersionUID = 1090747778031855442L; - private List workspace = new ArrayList(); + private static final long serialVersionUID = 1090747778031855442L; + private List workspace = new ArrayList(); - public List getWorkspace() { - return workspace; - } + public List getWorkspace() { + return workspace; + } } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppWorkspace.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppWorkspace.java index ee54762fc67..4efd8118dd3 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppWorkspace.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/AppWorkspace.java @@ -55,96 +55,96 @@ @XmlAccessorType(XmlAccessType.FIELD) public class AppWorkspace extends AppCommonAttributes { - private static final long serialVersionUID = -2595744438212041512L; - @XmlElement(namespace = "http://www.w3.org/2005/Atom", required = true) - protected String title; + private static final long serialVersionUID = -2595744438212041512L; + @XmlElement(namespace = "http://www.w3.org/2005/Atom", required = true) + protected String title; - protected List collection; - @XmlAnyElement(lax = true) - protected List any; + protected List collection; + @XmlAnyElement(lax = true) + protected List any; - /** - * Gets the value of the title property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTitle() { - return title; - } + /** + * Gets the value of the title property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTitle() { + return title; + } - /** - * Sets the value of the title property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTitle(String value) { - this.title = value; - } + /** + * Sets the value of the title property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } - /** - * Gets the value of the collection property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the collection property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getCollection().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link AppCollection } - * - * @return list of {@link AppCollection} - * - */ - public List getCollection() { - if (collection == null) { - collection = new ArrayList(); - } - return this.collection; - } + /** + * Gets the value of the collection property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the collection property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getCollection().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link AppCollection } + * + * @return list of {@link AppCollection} + * + */ + public List getCollection() { + if (collection == null) { + collection = new ArrayList(); + } + return this.collection; + } - /** - * Gets the value of the any property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the any property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAny().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link org.w3c.dom.Element } - * {@link Object } - * - * @return list of objects - * - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getAny().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link org.w3c.dom.Element } + * {@link Object } + * + * @return list of objects + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } } diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/BooleanAdapter.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/BooleanAdapter.java index b0b382156b5..adc9504ab9b 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/BooleanAdapter.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/BooleanAdapter.java @@ -18,16 +18,15 @@ public class BooleanAdapter extends XmlAdapter { - @Override - public Boolean unmarshal( String yesno ) - { - return yesno == null ? null : yesno.toLowerCase().equals("yes"); - } + @Override + public Boolean unmarshal( String yesno ) + { + return yesno == null ? null : yesno.toLowerCase().equals("yes"); + } - @Override - public String marshal( Boolean c ) - { - return c == null ? null : c ? "yes" : "no"; - } + @Override + public String marshal( Boolean c ) + { + return c == null ? null : c ? "yes" : "no"; + } } - diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/package-info.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/package-info.java index 75807520788..1e9fd413296 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/package-info.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/app/package-info.java @@ -13,9 +13,9 @@ * */ @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.w3.org/2007/app", - xmlns = { - @javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.w3.org/2007/app", prefix = "app"), - @javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.w3.org/2005/Atom", prefix = "atom") - }, - elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) + xmlns = { + @javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.w3.org/2007/app", prefix = "app"), + @javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.w3.org/2005/Atom", prefix = "atom") + }, + elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.jboss.resteasy.plugins.providers.atom.app; diff --git a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/package-info.java b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/package-info.java index fbe5fd487b2..272eeb0813a 100644 --- a/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/package-info.java +++ b/providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/package-info.java @@ -1,16 +1,16 @@ @XmlSchema(namespace = "http://www.w3.org/2005/Atom", // attributeFormDefault = XmlNsForm.QUALIFIED, - elementFormDefault = XmlNsForm.QUALIFIED + elementFormDefault = XmlNsForm.QUALIFIED ) @XmlJavaTypeAdapters( - { - @XmlJavaTypeAdapter(type = URI.class, value = UriAdapter.class), - @XmlJavaTypeAdapter(type = MediaType.class, value = MediaTypeAdapter.class) - }) package org.jboss.resteasy.plugins.providers.atom; + { + @XmlJavaTypeAdapter(type = URI.class, value = UriAdapter.class), + @XmlJavaTypeAdapter(type = MediaType.class, value = MediaTypeAdapter.class) + }) package org.jboss.resteasy.plugins.providers.atom; import javax.ws.rs.core.MediaType; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters; -import java.net.URI; \ No newline at end of file +import java.net.URI; diff --git a/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/HtmlRenderableWriter.java b/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/HtmlRenderableWriter.java index fc7f2739408..7cc1e1958b1 100644 --- a/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/HtmlRenderableWriter.java +++ b/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/HtmlRenderableWriter.java @@ -35,135 +35,135 @@ public class HtmlRenderableWriter implements MessageBodyWriter { - /* (non-Javadoc - * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object, java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) - */ - //@Override - public long getSize(Renderable obj, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { - // No chance of figuring this out ahead of time - return -1; - } - - /* (non-Javadoc) - * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) - */ - //@Override - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) - { - return Renderable.class.isAssignableFrom(type); - } - - /* (non-Javadoc) - * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(java.lang.Object, java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, java.io.OutputStream) - */ - //@Override - public void writeTo(Renderable viewingPleasure, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, - MultivaluedMap httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException - { - try - { - viewingPleasure.render( - // disable async processing as that would mess with interceptors, - // and entityStream is committed after writeTo and interceptors returns. - new HttpServletRequestWrapper(getContextData(HttpServletRequest.class)) { - - @Override - public boolean isAsyncSupported() { - return false; - } - - @Override - public boolean isAsyncStarted() { - return false; - } - - @Override - public AsyncContext getAsyncContext() { - throw new IllegalStateException(); - } - - @Override - public AsyncContext startAsync() throws IllegalStateException { - throw new IllegalStateException(); - } - - @Override - public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { - throw new IllegalStateException(); - } - }, - - // RESTEASY-1422: wrap entityStream to make sure headers added through JAX-RS are committed when the ServletOutputStream is written to. - // Also disable async processing on the ServletOutputStream, for consistency with the request. - new HttpServletResponseWrapper(getContextData(HttpServletResponse.class)) { - - private ServletOutputStream outputStream; - private PrintWriter writer; - - @Override - public ServletOutputStream getOutputStream() { - - if (writer != null) { - throw new IllegalStateException(); - } - if (outputStream == null) { - outputStream = new ServletOutputStream() { - - @Override - public boolean isReady() { - return true; - } - - @Override - public void setWriteListener(WriteListener writeListener) { - throw new IllegalStateException(); - } - - @Override - public void write(int b) throws IOException { - entityStream.write(b); - } - - @Override - public void write(byte[] b) throws IOException { - entityStream.write(b); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - entityStream.write(b, off, len); - } - - @Override - public void flush() throws IOException { - entityStream.flush(); - } - - @Override - public void close() throws IOException { - entityStream.close(); - } - }; - } - return outputStream; - } - - @Override - public PrintWriter getWriter() throws IOException { - if (outputStream != null) { - throw new IllegalStateException(); - } - if (writer == null) { - writer = new PrintWriter(new OutputStreamWriter(entityStream, getCharacterEncoding())); - } - return writer; - } - }); - } - catch (ServletException ex) - { - throw new WebApplicationException(ex); - } - } + /* (non-Javadoc + * @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object, java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) + */ + //@Override + public long getSize(Renderable obj, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) + { + // No chance of figuring this out ahead of time + return -1; + } + + /* (non-Javadoc) + * @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType) + */ + //@Override + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) + { + return Renderable.class.isAssignableFrom(type); + } + + /* (non-Javadoc) + * @see javax.ws.rs.ext.MessageBodyWriter#writeTo(java.lang.Object, java.lang.Class, java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap, java.io.OutputStream) + */ + //@Override + public void writeTo(Renderable viewingPleasure, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException + { + try + { + viewingPleasure.render( + // disable async processing as that would mess with interceptors, + // and entityStream is committed after writeTo and interceptors returns. + new HttpServletRequestWrapper(getContextData(HttpServletRequest.class)) { + + @Override + public boolean isAsyncSupported() { + return false; + } + + @Override + public boolean isAsyncStarted() { + return false; + } + + @Override + public AsyncContext getAsyncContext() { + throw new IllegalStateException(); + } + + @Override + public AsyncContext startAsync() throws IllegalStateException { + throw new IllegalStateException(); + } + + @Override + public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { + throw new IllegalStateException(); + } + }, + + // RESTEASY-1422: wrap entityStream to make sure headers added through JAX-RS are committed when the ServletOutputStream is written to. + // Also disable async processing on the ServletOutputStream, for consistency with the request. + new HttpServletResponseWrapper(getContextData(HttpServletResponse.class)) { + + private ServletOutputStream outputStream; + private PrintWriter writer; + + @Override + public ServletOutputStream getOutputStream() { + + if (writer != null) { + throw new IllegalStateException(); + } + if (outputStream == null) { + outputStream = new ServletOutputStream() { + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setWriteListener(WriteListener writeListener) { + throw new IllegalStateException(); + } + + @Override + public void write(int b) throws IOException { + entityStream.write(b); + } + + @Override + public void write(byte[] b) throws IOException { + entityStream.write(b); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + entityStream.write(b, off, len); + } + + @Override + public void flush() throws IOException { + entityStream.flush(); + } + + @Override + public void close() throws IOException { + entityStream.close(); + } + }; + } + return outputStream; + } + + @Override + public PrintWriter getWriter() throws IOException { + if (outputStream != null) { + throw new IllegalStateException(); + } + if (writer == null) { + writer = new PrintWriter(new OutputStreamWriter(entityStream, getCharacterEncoding())); + } + return writer; + } + }); + } + catch (ServletException ex) + { + throw new WebApplicationException(ex); + } + } } diff --git a/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/Renderable.java b/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/Renderable.java index 0550a833ab8..e132a17191d 100644 --- a/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/Renderable.java +++ b/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/Renderable.java @@ -24,6 +24,6 @@ public interface Renderable * @throws WebApplicationException if application error occurred */ void render(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException, WebApplicationException; + throws IOException, ServletException, WebApplicationException; } diff --git a/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/View.java b/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/View.java index 7b7d411cbc5..198f38280e5 100644 --- a/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/View.java +++ b/providers/resteasy-html/src/main/java/org/jboss/resteasy/plugins/providers/html/View.java @@ -30,7 +30,7 @@ public class View implements Renderable /** * Creates a view without a model. - * + * * @param path * will be dispatched to using the servlet container; it should * have a leading /. diff --git a/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/AbstractValidatorContextResolver.java b/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/AbstractValidatorContextResolver.java index 407603de2a8..3b7358524e2 100755 --- a/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/AbstractValidatorContextResolver.java +++ b/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/AbstractValidatorContextResolver.java @@ -67,21 +67,21 @@ ValidatorFactory getValidatorFactory() BootstrapConfiguration getConfig() { - BootstrapConfiguration tmpConfig = bootstrapConfiguration; - if (tmpConfig == null) - { - synchronized (RD_LOCK) - { - tmpConfig = bootstrapConfiguration; - if (tmpConfig == null) - { - config = Validation.byDefaultProvider().configure(); - bootstrapConfiguration = tmpConfig = config.getBootstrapConfiguration(); + BootstrapConfiguration tmpConfig = bootstrapConfiguration; + if (tmpConfig == null) + { + synchronized (RD_LOCK) + { + tmpConfig = bootstrapConfiguration; + if (tmpConfig == null) + { + config = Validation.byDefaultProvider().configure(); + bootstrapConfiguration = tmpConfig = config.getBootstrapConfiguration(); - } - } - } - return tmpConfig; + } + } + } + return tmpConfig; } public GeneralValidatorCDI getContext(Class type) { diff --git a/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java b/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java index bdd2f621da9..c7231215856 100755 --- a/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java +++ b/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/GeneralValidatorImpl.java @@ -120,8 +120,8 @@ public void validate(HttpRequest request, Object object, Class... groups) private ValidationException toValidationException(Exception exception, SimpleViolationsContainer simpleViolationsContainer) { if (exception instanceof ConstraintDeclarationException || - exception instanceof ConstraintDefinitionException || - exception instanceof GroupDefinitionException) + exception instanceof ConstraintDefinitionException || + exception instanceof GroupDefinitionException) { return (ValidationException) exception; } @@ -185,7 +185,7 @@ public void validateAllParameters(HttpRequest request, Object object, Method met if ((violationsContainer.isFieldsValidated() || !GetRestful.isRootResource(object.getClass()) || hasApplicationScope(object)) - && violationsContainer.size() > 0) + && violationsContainer.size() > 0) { throw new ResteasyViolationException(violationsContainer, request.getHttpHeaders().getAcceptableMediaTypes()); } @@ -239,7 +239,7 @@ public boolean isValidatable(Class clazz, InjectorFactory injectorFactory) } catch (NoClassDefFoundError e) { - // Shouldn't get here. Deliberately empty. + // Shouldn't get here. Deliberately empty. } return true; } @@ -347,41 +347,41 @@ protected List getExecutableTypesOnMethodInHierarchy(Method me protected List getExecutableTypesOnMethodInInterfaces(Class clazz, Method method) { - List typesList = new ArrayList(); - Class[] interfaces = clazz.getInterfaces(); - for (int i = 0; i < interfaces.length; i++) - { - Method interfaceMethod = getSuperMethod(method, interfaces[i]); - if (interfaceMethod != null) - { - ExecutableType[] types = getExecutableTypesOnMethod(interfaceMethod); - if (types != null) - { - typesList.add(types); - } - } - List superList = getExecutableTypesOnMethodInInterfaces(interfaces[i], method); - if (superList.size() > 0) - { - typesList.addAll(superList); - } - } - return typesList; + List typesList = new ArrayList(); + Class[] interfaces = clazz.getInterfaces(); + for (int i = 0; i < interfaces.length; i++) + { + Method interfaceMethod = getSuperMethod(method, interfaces[i]); + if (interfaceMethod != null) + { + ExecutableType[] types = getExecutableTypesOnMethod(interfaceMethod); + if (types != null) + { + typesList.add(types); + } + } + List superList = getExecutableTypesOnMethodInInterfaces(interfaces[i], method); + if (superList.size() > 0) + { + typesList.addAll(superList); + } + } + return typesList; } static protected ExecutableType[] getExecutableTypesOnMethod(Method method) { - ValidateOnExecution voe = method.getAnnotation(ValidateOnExecution.class); - if (voe == null || voe.type().length == 0) - { - return null; - } - ExecutableType[] types = voe.type(); - if (types == null || types.length == 0) - { - return null; - } - return types; + ValidateOnExecution voe = method.getAnnotation(ValidateOnExecution.class); + if (voe == null || voe.type().length == 0) + { + return null; + } + ExecutableType[] types = voe.type(); + if (types == null || types.length == 0) + { + return null; + } + return types; } static protected boolean isGetter(Method m) @@ -461,18 +461,18 @@ public Method[] run() throws Exception { return null; } - /** - * Checks, whether {@code subTypeMethod} overrides {@code superTypeMethod}. - * - * N.B. "Override" here is reflexive. I.e., a method overrides itself. - * - * @param subTypeMethod The sub type method (cannot be {@code null}). - * @param superTypeMethod The super type method (cannot be {@code null}). - * - * @return Returns {@code true} if {@code subTypeMethod} overrides {@code superTypeMethod}, {@code false} otherwise. - * - * Taken from Hibernate Validator - */ + /** + * Checks, whether {@code subTypeMethod} overrides {@code superTypeMethod}. + * + * N.B. "Override" here is reflexive. I.e., a method overrides itself. + * + * @param subTypeMethod The sub type method (cannot be {@code null}). + * @param superTypeMethod The super type method (cannot be {@code null}). + * + * @return Returns {@code true} if {@code subTypeMethod} overrides {@code superTypeMethod}, {@code false} otherwise. + * + * Taken from Hibernate Validator + */ protected boolean overrides(Method subTypeMethod, Method superTypeMethod) { if (subTypeMethod == null || superTypeMethod == null) @@ -633,9 +633,9 @@ private Locale getLocale(HttpRequest request) { /** * A filter implementation filtering methods matching given methods. - * + * * @author Gunnar Morling - * + * * Taken from Hibernate Validator */ static protected class SimpleMethodFilter implements Filter diff --git a/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/ValidatorContextResolverCDI.java b/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/ValidatorContextResolverCDI.java index cc0cb604e50..443cd758a4f 100644 --- a/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/ValidatorContextResolverCDI.java +++ b/providers/resteasy-validator-provider-11/src/main/java/org/jboss/resteasy/plugins/validation/ValidatorContextResolverCDI.java @@ -14,7 +14,6 @@ * Copyright May 23, 2013 */ @Provider -public class ValidatorContextResolverCDI extends AbstractValidatorContextResolver -implements ContextResolver +public class ValidatorContextResolverCDI extends AbstractValidatorContextResolver implements ContextResolver { } diff --git a/providers/yaml/src/main/java/org/jboss/resteasy/plugins/providers/YamlProvider.java b/providers/yaml/src/main/java/org/jboss/resteasy/plugins/providers/YamlProvider.java index bdebc122afc..ffd65978212 100755 --- a/providers/yaml/src/main/java/org/jboss/resteasy/plugins/providers/YamlProvider.java +++ b/providers/yaml/src/main/java/org/jboss/resteasy/plugins/providers/YamlProvider.java @@ -39,75 +39,75 @@ @Deprecated public class YamlProvider extends AbstractEntityProvider { - // MessageBodyReader + // MessageBodyReader - public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return true; - } + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return true; + } - public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, + public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { - try { - LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); - if (isValidInternalType(type)) { - return new Yaml().load(entityStream); - } else { - CustomClassLoaderConstructor customClassLoaderConstructor = new CustomClassLoaderConstructor(type.getClassLoader()); - return new Yaml(customClassLoaderConstructor).loadAs(entityStream, type); - } - } catch (Exception e) { - LogMessages.LOGGER.debug(Messages.MESSAGES.failedToDecodeYamlMessage(e.getMessage())); - throw new ReaderException(Messages.MESSAGES.failedToDecodeYaml(), e); - } - } - - // MessageBodyWriter - protected boolean isValidInternalType(Class type) { - if (List.class.isAssignableFrom(type) - || Set.class.isAssignableFrom(type) - || Map.class.isAssignableFrom(type) - || type.isArray()) { - return true; - } else { - return false; - } - } - - protected boolean isValidType(Class type) { - if (isValidInternalType(type)) { - return true; - } - if (StreamingOutput.class.isAssignableFrom(type)) return false; - String className = type.getName(); - if (className.startsWith("java.")) return false; - if (className.startsWith("javax.")) return false; - if (type.isPrimitive()) return false; - - return true; - } - - - public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { - return isValidType(type); - } - - public void writeTo(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, + try { + LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); + if (isValidInternalType(type)) { + return new Yaml().load(entityStream); + } else { + CustomClassLoaderConstructor customClassLoaderConstructor = new CustomClassLoaderConstructor(type.getClassLoader()); + return new Yaml(customClassLoaderConstructor).loadAs(entityStream, type); + } + } catch (Exception e) { + LogMessages.LOGGER.debug(Messages.MESSAGES.failedToDecodeYamlMessage(e.getMessage())); + throw new ReaderException(Messages.MESSAGES.failedToDecodeYaml(), e); + } + } + + // MessageBodyWriter + protected boolean isValidInternalType(Class type) { + if (List.class.isAssignableFrom(type) + || Set.class.isAssignableFrom(type) + || Map.class.isAssignableFrom(type) + || type.isArray()) { + return true; + } else { + return false; + } + } + + protected boolean isValidType(Class type) { + if (isValidInternalType(type)) { + return true; + } + if (StreamingOutput.class.isAssignableFrom(type)) return false; + String className = type.getName(); + if (className.startsWith("java.")) return false; + if (className.startsWith("javax.")) return false; + if (type.isPrimitive()) return false; + + return true; + } + + + public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return isValidType(type); + } + + public void writeTo(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { - try { - LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); - entityStream.write(new Yaml().dump(t).getBytes()); + try { + LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); + entityStream.write(new Yaml().dump(t).getBytes()); - } catch (Exception e) { + } catch (Exception e) { - LogMessages.LOGGER.debug(Messages.MESSAGES.failedToEncodeYaml(t.toString())); - throw new WriterException(e); + LogMessages.LOGGER.debug(Messages.MESSAGES.failedToEncodeYaml(t.toString())); + throw new WriterException(e); - } + } - } + } } diff --git a/resteasy-cache/resteasy-cache-core/src/main/java/org/jboss/resteasy/plugins/cache/server/ServerCacheInterceptor.java b/resteasy-cache/resteasy-cache-core/src/main/java/org/jboss/resteasy/plugins/cache/server/ServerCacheInterceptor.java index 045799c0de9..b5807604a30 100644 --- a/resteasy-cache/resteasy-cache-core/src/main/java/org/jboss/resteasy/plugins/cache/server/ServerCacheInterceptor.java +++ b/resteasy-cache/resteasy-cache-core/src/main/java/org/jboss/resteasy/plugins/cache/server/ServerCacheInterceptor.java @@ -42,10 +42,12 @@ public ServerCacheInterceptor(ServerCache cache) protected Request validation; - private static final String pseudo[] = {"0", "1", "2", - "3", "4", "5", "6", "7", "8", - "9", "A", "B", "C", "D", "E", - "F"}; + private static final String pseudo[] = { + "0", "1", "2", + "3", "4", "5", "6", "7", "8", + "9", "A", "B", "C", "D", "E", + "F" + }; public static String byteArrayToHexString(byte[] bytes) { @@ -89,7 +91,7 @@ protected String createHash(byte[] entity) @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { - LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName()); + LogMessages.LOGGER.debugf("Interceptor : %s, Method : aroundWriteTo", getClass().getName()); if (!request.getHttpMethod().equalsIgnoreCase("GET") || request.getAttribute(ServerCacheHitFilter.DO_NOT_CACHE_RESPONSE) != null) { @@ -137,7 +139,7 @@ public void aroundWriteTo(WriterInterceptorContext context) throws IOException, } if (!cc.isPrivate() && !cc.isNoStore()) { - cache.add(request.getUri().getRequestUri().toString(), context.getMediaType(), cc, context.getHeaders(), entity, etag); + cache.add(request.getUri().getRequestUri().toString(), context.getMediaType(), cc, context.getHeaders(), entity, etag); } // check to see if ETags are the same. If they are, we don't need to send a response back. diff --git a/resteasy-cache/resteasy-cache-core/src/test/java/org/jboss/resteasy/test/cache/PersistentServerCacheTest.java b/resteasy-cache/resteasy-cache-core/src/test/java/org/jboss/resteasy/test/cache/PersistentServerCacheTest.java index 20fa6917ed1..3b924ae7dff 100644 --- a/resteasy-cache/resteasy-cache-core/src/test/java/org/jboss/resteasy/test/cache/PersistentServerCacheTest.java +++ b/resteasy-cache/resteasy-cache-core/src/test/java/org/jboss/resteasy/test/cache/PersistentServerCacheTest.java @@ -388,4 +388,4 @@ public void testPreferredButNotCachedAccepts() throws Exception Assert.assertEquals(response.getEntity(), "html" + 1); } } -} \ No newline at end of file +} diff --git a/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/CdiInjectorFactory.java b/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/CdiInjectorFactory.java index eeed21a31a3..0f17517c3a6 100755 --- a/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/CdiInjectorFactory.java +++ b/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/CdiInjectorFactory.java @@ -175,15 +175,15 @@ protected BeanManager lookupBeanManager() beanManager = lookupBeanManagerCDIUtil(); if(beanManager != null) { - LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerViaCDI()); - return beanManager; + LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerViaCDI()); + return beanManager; } beanManager = lookupBeanManagerViaServletContext(); if(beanManager != null) { - LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerInServletContext()); - return beanManager; + LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerInServletContext()); + return beanManager; } throw new RuntimeException(Messages.MESSAGES.unableToLookupBeanManager()); @@ -211,58 +211,58 @@ private BeanManager lookupBeanManagerInJndi(String name) private static BeanManager lookupBeanManagerViaServletContext() { - BeanManager beanManager = null; - try - { - // Look for BeanManager in ServletContext - ServletContext servletContext = ResteasyProviderFactory.getContextData(ServletContext.class); - // null check for RESTEASY-1009 - if (servletContext != null) - { - beanManager = (BeanManager) servletContext.getAttribute(BEAN_MANAGER_ATTRIBUTE_PREFIX + BeanManager.class.getName()); - if (beanManager != null) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerInServletContext()); - return beanManager; - } - - // Look for BeanManager in ServletContext (the old attribute name for backwards compatibility) - beanManager = (BeanManager) servletContext.getAttribute(BeanManager.class.getName()); - if (beanManager != null) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerInServletContext()); - return beanManager; - } - } - } - catch (NoClassDefFoundError e) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.unableToFindServletContextClass(), e); - } - - catch (Exception e) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.errorOccurredLookingUpServletContext(), e); - } - return beanManager; + BeanManager beanManager = null; + try + { + // Look for BeanManager in ServletContext + ServletContext servletContext = ResteasyProviderFactory.getContextData(ServletContext.class); + // null check for RESTEASY-1009 + if (servletContext != null) + { + beanManager = (BeanManager) servletContext.getAttribute(BEAN_MANAGER_ATTRIBUTE_PREFIX + BeanManager.class.getName()); + if (beanManager != null) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerInServletContext()); + return beanManager; + } + + // Look for BeanManager in ServletContext (the old attribute name for backwards compatibility) + beanManager = (BeanManager) servletContext.getAttribute(BeanManager.class.getName()); + if (beanManager != null) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.foundBeanManagerInServletContext()); + return beanManager; + } + } + } + catch (NoClassDefFoundError e) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.unableToFindServletContextClass(), e); + } + + catch (Exception e) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.errorOccurredLookingUpServletContext(), e); + } + return beanManager; } public static BeanManager lookupBeanManagerCDIUtil() { - BeanManager bm = null; - try - { - bm = CDI.current().getBeanManager(); - } - catch (NoClassDefFoundError e) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.unableToFindCDIClass(), e); - } - catch (Exception e) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.errorOccurredLookingUpViaCDIUtil(), e); - } - return bm; + BeanManager bm = null; + try + { + bm = CDI.current().getBeanManager(); + } + catch (NoClassDefFoundError e) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.unableToFindCDIClass(), e); + } + catch (Exception e) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.errorOccurredLookingUpViaCDIUtil(), e); + } + return bm; } /** diff --git a/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/ResteasyCdiExtension.java b/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/ResteasyCdiExtension.java index 58f127180d9..c8f6bec6baa 100644 --- a/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/ResteasyCdiExtension.java +++ b/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/ResteasyCdiExtension.java @@ -71,7 +71,7 @@ public static boolean isCDIActive() /** * Obtain BeanManager reference for future use. - * + * * @param event event * @param beanManager bean manager */ @@ -90,19 +90,19 @@ public void observeBeforeBeanDiscovery(@Observes BeforeBeanDiscovery event, Bean */ public void observeResources(@WithAnnotations({Path.class}) @Observes ProcessAnnotatedType event, BeanManager beanManager) { - setBeanManager(beanManager); - AnnotatedType annotatedType = event.getAnnotatedType(); + setBeanManager(beanManager); + AnnotatedType annotatedType = event.getAnnotatedType(); - if(!annotatedType.getJavaClass().isInterface() + if(!annotatedType.getJavaClass().isInterface() && !isSessionBean(annotatedType) // This check is redundant for CDI 1.1 containers but required for CDI 1.0 && GetRestful.isRootResource(annotatedType.getJavaClass()) && !annotatedType.isAnnotationPresent(Decorator.class)) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanJaxRsResource(annotatedType.getJavaClass().getCanonicalName())); - event.setAnnotatedType(wrapAnnotatedType(annotatedType, requestScopedLiteral)); - this.resources.add(annotatedType.getJavaClass()); - } + { + LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanJaxRsResource(annotatedType.getJavaClass().getCanonicalName())); + event.setAnnotatedType(wrapAnnotatedType(annotatedType, requestScopedLiteral)); + this.resources.add(annotatedType.getJavaClass()); + } } /** @@ -114,18 +114,18 @@ public void observeResources(@WithAnnotations({Path.class}) @Observes Proces */ public void observeProviders(@WithAnnotations({Provider.class}) @Observes ProcessAnnotatedType event, BeanManager beanManager) { - setBeanManager(beanManager); - AnnotatedType annotatedType = event.getAnnotatedType(); + setBeanManager(beanManager); + AnnotatedType annotatedType = event.getAnnotatedType(); - if(!annotatedType.getJavaClass().isInterface() + if(!annotatedType.getJavaClass().isInterface() && !isSessionBean(annotatedType) // This check is redundant for CDI 1.1 containers but required for CDI 1.0 && annotatedType.isAnnotationPresent(Provider.class)) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanJaxRsProvider(annotatedType.getJavaClass().getCanonicalName())); - event.setAnnotatedType(wrapAnnotatedType(annotatedType, applicationScopedLiteral)); - this.providers.add(annotatedType.getJavaClass()); - } + { + LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanJaxRsProvider(annotatedType.getJavaClass().getCanonicalName())); + event.setAnnotatedType(wrapAnnotatedType(annotatedType, applicationScopedLiteral)); + this.providers.add(annotatedType.getJavaClass()); + } } /** @@ -137,14 +137,14 @@ public void observeProviders(@WithAnnotations({Provider.class}) @Observes Pr */ public void observeApplications(@Observes ProcessAnnotatedType event, BeanManager beanManager) { - setBeanManager(beanManager); - AnnotatedType annotatedType = event.getAnnotatedType(); + setBeanManager(beanManager); + AnnotatedType annotatedType = event.getAnnotatedType(); - if(!isSessionBean(annotatedType)) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanApplication(annotatedType.getJavaClass().getCanonicalName())); - event.setAnnotatedType(wrapAnnotatedType(annotatedType, applicationScopedLiteral)); - } + if(!isSessionBean(annotatedType)) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.discoveredCDIBeanApplication(annotatedType.getJavaClass().getCanonicalName())); + event.setAnnotatedType(wrapAnnotatedType(annotatedType, applicationScopedLiteral)); + } } protected AnnotatedType wrapAnnotatedType(AnnotatedType type, Annotation scope) @@ -164,7 +164,7 @@ protected AnnotatedType wrapAnnotatedType(AnnotatedType type, Annotati /** * Wrap InjectionTarget of JAX-RS components within JaxrsInjectionTarget * which takes care of JAX-RS property injection. - * + * * @param type * @param event event */ @@ -192,10 +192,10 @@ protected InjectionTarget wrapInjectionTarget(ProcessInjectionTarget e * interface) map for Session beans with local interfaces. This map is * necessary since RESTEasy identifies a bean class as JAX-RS components * while CDI requires a local interface to be used for lookup. - * + * * @param type * @param event event - * + * */ public void observeSessionBeans(@Observes ProcessSessionBean event) { @@ -232,33 +232,33 @@ public Map, Type> getSessionBeanInterface() private boolean isSessionBean(AnnotatedType annotatedType) { - for (Annotation annotation : annotatedType.getAnnotations()) - { - Class annotationType = annotation.annotationType(); - if (annotationType.getName().equals(JAVAX_EJB_STATELESS) || annotationType.getName().equals(JAVAX_EJB_SINGLETON)) - { - LogMessages.LOGGER.debug(Messages.MESSAGES.beanIsSLSBOrSingleton(annotatedType.getJavaClass())); - return true; // Do not modify scopes of SLSBs and Singletons - } - } - return false; + for (Annotation annotation : annotatedType.getAnnotations()) + { + Class annotationType = annotation.annotationType(); + if (annotationType.getName().equals(JAVAX_EJB_STATELESS) || annotationType.getName().equals(JAVAX_EJB_SINGLETON)) + { + LogMessages.LOGGER.debug(Messages.MESSAGES.beanIsSLSBOrSingleton(annotatedType.getJavaClass())); + return true; // Do not modify scopes of SLSBs and Singletons + } + } + return false; } private void setBeanManager(BeanManager beanManager) { - if (this.beanManager == null) { - // this may happen if Solder Config receives BBD first - this.beanManager = beanManager; - } + if (this.beanManager == null) { + // this may happen if Solder Config receives BBD first + this.beanManager = beanManager; + } } public List getProviders() { - return providers; + return providers; } public List getResources() { - return resources; + return resources; } } diff --git a/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/Utils.java b/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/Utils.java index 88d61732d8d..8fa6ac42141 100644 --- a/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/Utils.java +++ b/resteasy-cdi/src/main/java/org/jboss/resteasy/cdi/Utils.java @@ -58,7 +58,7 @@ public static boolean isJaxrsAnnotatedClass(Class clazz) * Returns true if and only if the given class is a JAX-RS root resource or a * sub-resource. The class itself as well as its interfaces are scanned for * JAX-RS annotations. - * + * * @param clazz class * @return true if the given class is JAX-RS resource or sub-resource */ diff --git a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java index f769ec997c9..7d01a7bde58 100644 --- a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java +++ b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientEngine.java @@ -35,260 +35,260 @@ import org.jboss.resteasy.client.jaxrs.internal.ClientResponse; public class JettyClientEngine implements AsyncClientHttpEngine { - private static final AtomicBoolean WARN_BUF = new AtomicBoolean(); - public static final String REQUEST_TIMEOUT_MS = JettyClientEngine.class + "$RequestTimeout"; - // Yeah, this is the Jersey one, but there's no standard one and it makes more sense to reuse than make our own... - public static final String FOLLOW_REDIRECTS = "jersey.config.client.followRedirects"; + private static final AtomicBoolean WARN_BUF = new AtomicBoolean(); + public static final String REQUEST_TIMEOUT_MS = JettyClientEngine.class + "$RequestTimeout"; + // Yeah, this is the Jersey one, but there's no standard one and it makes more sense to reuse than make our own... + public static final String FOLLOW_REDIRECTS = "jersey.config.client.followRedirects"; - private static final InvocationCallback NOP = new InvocationCallback() { - @Override - public void completed(ClientResponse response) { - } + private static final InvocationCallback NOP = new InvocationCallback() { + @Override + public void completed(ClientResponse response) { + } - @Override - public void failed(Throwable throwable) { - } - }; + @Override + public void failed(Throwable throwable) { + } + }; - private final HttpClient client; + private final HttpClient client; - public JettyClientEngine(HttpClient client) { - if (!client.isStarted()) { - try { - client.start(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - this.client = client; - } + public JettyClientEngine(HttpClient client) { + if (!client.isStarted()) { + try { + client.start(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + this.client = client; + } - @Override - public SSLContext getSslContext() { - return client.getSslContextFactory().getSslContext(); - } + @Override + public SSLContext getSslContext() { + return client.getSslContextFactory().getSslContext(); + } - @Override - public HostnameVerifier getHostnameVerifier() { - throw new UnsupportedOperationException(); - } + @Override + public HostnameVerifier getHostnameVerifier() { + throw new UnsupportedOperationException(); + } - @Override - public ClientResponse invoke(ClientInvocation invocation) { - Future future = submit(invocation, true, NOP, null); - try { - return future.get(1, TimeUnit.HOURS); // There's already an idle and connect timeout, do we need one here? - } catch (InterruptedException e) { - future.cancel(true); - Thread.currentThread().interrupt(); - throw clientException(e, null); - } catch (TimeoutException | ExecutionException e) { - future.cancel(true); - throw clientException(e.getCause(), null); - } - } + @Override + public ClientResponse invoke(ClientInvocation invocation) { + Future future = submit(invocation, true, NOP, null); + try { + return future.get(1, TimeUnit.HOURS); // There's already an idle and connect timeout, do we need one here? + } catch (InterruptedException e) { + future.cancel(true); + Thread.currentThread().interrupt(); + throw clientException(e, null); + } catch (TimeoutException | ExecutionException e) { + future.cancel(true); + throw clientException(e.getCause(), null); + } + } - /** - * Implementation note: due to lack of asynchronous message decoders the request must either be buffered, - * or it must have a {@code null} extractor and type parameter {@code } must be {@link ClientResponse}, - * which will read the data through its stream. It is not possible to use the synchronous JAX-RS message - * decoding infrastructure without buffering or spinning up auxiliary threads (arguably more expensive than buffering). - * - * @see AsyncClientHttpEngine#submit(ClientInvocation, boolean, InvocationCallback, org.jboss.resteasy.client.jaxrs.AsyncClientHttpEngine.ResultExtractor) - */ - @Override - public Future submit(ClientInvocation invocation, boolean bufIn, InvocationCallback callback, ResultExtractor extractor) { - final boolean buffered; - if (!bufIn && extractor != null) { - if (!WARN_BUF.getAndSet(true)) { - Logger LOG = Logger.getLogger(JettyClientEngine.class); - LOG.error("TODO: ResultExtractor is synchronous and may not be used without buffering - forcing buffer mode."); - } - buffered = true; - } else { - buffered = bufIn; - } + /** + * Implementation note: due to lack of asynchronous message decoders the request must either be buffered, + * or it must have a {@code null} extractor and type parameter {@code } must be {@link ClientResponse}, + * which will read the data through its stream. It is not possible to use the synchronous JAX-RS message + * decoding infrastructure without buffering or spinning up auxiliary threads (arguably more expensive than buffering). + * + * @see AsyncClientHttpEngine#submit(ClientInvocation, boolean, InvocationCallback, org.jboss.resteasy.client.jaxrs.AsyncClientHttpEngine.ResultExtractor) + */ + @Override + public Future submit(ClientInvocation invocation, boolean bufIn, InvocationCallback callback, ResultExtractor extractor) { + final boolean buffered; + if (!bufIn && extractor != null) { + if (!WARN_BUF.getAndSet(true)) { + Logger LOG = Logger.getLogger(JettyClientEngine.class); + LOG.error("TODO: ResultExtractor is synchronous and may not be used without buffering - forcing buffer mode."); + } + buffered = true; + } else { + buffered = bufIn; + } - final Request request = client.newRequest(invocation.getUri()); - final CompletableFuture future = new RequestFuture(request); - // readEntity calls releaseConnection which calls cancel, so don't let that interrupt us - final AtomicBoolean completing = new AtomicBoolean(); + final Request request = client.newRequest(invocation.getUri()); + final CompletableFuture future = new RequestFuture(request); + // readEntity calls releaseConnection which calls cancel, so don't let that interrupt us + final AtomicBoolean completing = new AtomicBoolean(); - invocation.getMutableProperties().forEach(request::attribute); - request.method(invocation.getMethod()); - invocation.getHeaders().asMap().forEach((h, vs) -> vs.forEach(v -> request.header(h, v))); - configureTimeout(request); - if (request.getAttributes().get(FOLLOW_REDIRECTS) == Boolean.FALSE) { - request.followRedirects(false); - } + invocation.getMutableProperties().forEach(request::attribute); + request.method(invocation.getMethod()); + invocation.getHeaders().asMap().forEach((h, vs) -> vs.forEach(v -> request.header(h, v))); + configureTimeout(request); + if (request.getAttributes().get(FOLLOW_REDIRECTS) == Boolean.FALSE) { + request.followRedirects(false); + } - if (invocation.getEntity() != null) { - final ByteArrayOutputStream os = new ByteArrayOutputStream(); - try { - invocation.writeRequestBody(os); - } catch (IOException e) { - future.completeExceptionally(e); - if (callback != null) { - callback.failed(e); - } - return future; + if (invocation.getEntity() != null) { + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + invocation.writeRequestBody(os); + } catch (IOException e) { + future.completeExceptionally(e); + if (callback != null) { + callback.failed(e); } - request.content(new BytesContentProvider(os.toByteArray())); - } + return future; + } + request.content(new BytesContentProvider(os.toByteArray())); + } - request.send(new Response.Listener.Adapter() { - private ClientResponse cr; - private JettyResponseStream stream = new JettyResponseStream(); + request.send(new Response.Listener.Adapter() { + private ClientResponse cr; + private JettyResponseStream stream = new JettyResponseStream(); - @Override - public void onHeaders(Response response) { - cr = new JettyClientResponse(invocation.getClientConfiguration(), stream, () -> { - if (!completing.get()) { - future.cancel(true); - } - }); - cr.setProperties(invocation.getMutableProperties()); - cr.setStatus(response.getStatus()); - cr.setHeaders(extract(response.getHeaders())); - if (!buffered) { - complete(); - } + @Override + public void onHeaders(Response response) { + cr = new JettyClientResponse(invocation.getClientConfiguration(), stream, () -> { + if (!completing.get()) { + future.cancel(true); + } + }); + cr.setProperties(invocation.getMutableProperties()); + cr.setStatus(response.getStatus()); + cr.setHeaders(extract(response.getHeaders())); + if (!buffered) { + complete(); } + } - @Override - public void onContent(Response response, ByteBuffer buf) { - final ByteBufferPool bufs = client.getByteBufferPool(); - final ByteBuffer copy = bufs.acquire(buf.remaining(), false); - copy.limit(buf.remaining()); - copy.put(buf); - copy.flip(); - stream.offer(copy, new ReleaseCallback(bufs, copy)); - } + @Override + public void onContent(Response response, ByteBuffer buf) { + final ByteBufferPool bufs = client.getByteBufferPool(); + final ByteBuffer copy = bufs.acquire(buf.remaining(), false); + copy.limit(buf.remaining()); + copy.put(buf); + copy.flip(); + stream.offer(copy, new ReleaseCallback(bufs, copy)); + } - @Override - public void onSuccess(Response response) { - if (buffered) { - try { - complete(); - } catch (Exception e) { - onFailure(response, e); - } - } + @Override + public void onSuccess(Response response) { + if (buffered) { + try { + complete(); + } catch (Exception e) { + onFailure(response, e); + } } + } - @SuppressWarnings("unchecked") - private void complete() { - completing.set(true); - if (buffered) { - cr.bufferEntity(); - } - // TODO: dangerous cast, see javadoc! - complete(extractor == null ? (T) cr : extractor.extractResult(cr)); + @SuppressWarnings("unchecked") + private void complete() { + completing.set(true); + if (buffered) { + cr.bufferEntity(); } + // TODO: dangerous cast, see javadoc! + complete(extractor == null ? (T) cr : extractor.extractResult(cr)); + } - @Override - public void onFailure(Response response, Throwable failure) { - failed(failure); - } + @Override + public void onFailure(Response response, Throwable failure) { + failed(failure); + } - @Override - public void onComplete(Result result) { - try { - if (extractor != null) { - stream.close(); - } - } catch (IOException e) { - throw new UncheckedIOException(e); - } + @Override + public void onComplete(Result result) { + try { + if (extractor != null) { + stream.close(); + } + } catch (IOException e) { + throw new UncheckedIOException(e); } + } - private void complete(T result) { - future.complete(result); - if (callback != null) { - callback.completed(result); - } + private void complete(T result) { + future.complete(result); + if (callback != null) { + callback.completed(result); } + } - private void failed(Throwable t) { - final RuntimeException x = clientException(t, cr); - future.completeExceptionally(x); - if (callback != null) { - callback.failed(x); - } + private void failed(Throwable t) { + final RuntimeException x = clientException(t, cr); + future.completeExceptionally(x); + if (callback != null) { + callback.failed(x); } - }); - return future; - } + } + }); + return future; + } - private void configureTimeout(final Request request) { - final Object timeout = request.getAttributes().get(REQUEST_TIMEOUT_MS); - final long timeoutMs; - if (timeout instanceof Duration) { - timeoutMs = ((Duration) timeout).toMillis(); - } else if (timeout instanceof Number) { - timeoutMs = ((Number) timeout).intValue(); - } else if (timeout != null) { - timeoutMs = Integer.parseInt(timeout.toString()); - } else { - timeoutMs = -1; - } - if (timeoutMs > 0) { - request.timeout(timeoutMs, TimeUnit.MILLISECONDS); - } - } + private void configureTimeout(final Request request) { + final Object timeout = request.getAttributes().get(REQUEST_TIMEOUT_MS); + final long timeoutMs; + if (timeout instanceof Duration) { + timeoutMs = ((Duration) timeout).toMillis(); + } else if (timeout instanceof Number) { + timeoutMs = ((Number) timeout).intValue(); + } else if (timeout != null) { + timeoutMs = Integer.parseInt(timeout.toString()); + } else { + timeoutMs = -1; + } + if (timeoutMs > 0) { + request.timeout(timeoutMs, TimeUnit.MILLISECONDS); + } + } - @Override - public void close() { - try { - client.stop(); - } catch (Exception e) { - throw new RuntimeException("Unable to close JettyHttpEngine", e); - } - } + @Override + public void close() { + try { + client.stop(); + } catch (Exception e) { + throw new RuntimeException("Unable to close JettyHttpEngine", e); + } + } - MultivaluedMap extract(HttpFields headers) { - final MultivaluedMap extracted = new MultivaluedHashMap<>(); - headers.forEach(h -> extracted.add(h.getName(), h.getValue())); - return extracted; - } + MultivaluedMap extract(HttpFields headers) { + final MultivaluedMap extracted = new MultivaluedHashMap<>(); + headers.forEach(h -> extracted.add(h.getName(), h.getValue())); + return extracted; + } - private static RuntimeException clientException(Throwable ex, javax.ws.rs.core.Response clientResponse) { - RuntimeException ret; - if (ex == null) { - final NullPointerException e = new NullPointerException(); - e.fillInStackTrace(); - ret = new ProcessingException(e); - } - else if (ex instanceof WebApplicationException) { - ret = (WebApplicationException) ex; - } - else if (ex instanceof ProcessingException) { - ret = (ProcessingException) ex; - } - else if (clientResponse != null) { - ret = new ResponseProcessingException(clientResponse, ex); - } - else { - ret = new ProcessingException(ex); - } - ret.fillInStackTrace(); - return ret; - } + private static RuntimeException clientException(Throwable ex, javax.ws.rs.core.Response clientResponse) { + RuntimeException ret; + if (ex == null) { + final NullPointerException e = new NullPointerException(); + e.fillInStackTrace(); + ret = new ProcessingException(e); + } + else if (ex instanceof WebApplicationException) { + ret = (WebApplicationException) ex; + } + else if (ex instanceof ProcessingException) { + ret = (ProcessingException) ex; + } + else if (clientResponse != null) { + ret = new ResponseProcessingException(clientResponse, ex); + } + else { + ret = new ProcessingException(ex); + } + ret.fillInStackTrace(); + return ret; + } - static class RequestFuture extends CompletableFuture { - private final Request request; + static class RequestFuture extends CompletableFuture { + private final Request request; - RequestFuture(Request request) { - this.request = request; - } + RequestFuture(Request request) { + this.request = request; + } - @Override - public boolean cancel(boolean mayInterruptIfRunning) { - final boolean cancelled = super.cancel(mayInterruptIfRunning); - if (mayInterruptIfRunning && cancelled) { - request.abort(new CancellationException()); - } - return cancelled; - } - } + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + final boolean cancelled = super.cancel(mayInterruptIfRunning); + if (mayInterruptIfRunning && cancelled) { + request.abort(new CancellationException()); + } + return cancelled; + } + } } diff --git a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java index 85bbce43722..3e29f7a46fb 100644 --- a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java +++ b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyClientResponse.java @@ -7,41 +7,41 @@ import org.jboss.resteasy.client.jaxrs.internal.ClientResponse; class JettyClientResponse extends ClientResponse { - private final Runnable cancel; - private InputStream stream; - - JettyClientResponse(ClientConfiguration configuration, InputStream stream, Runnable cancel) { - super(configuration); - this.cancel = cancel; - this.stream = stream; - } - - @Override - protected InputStream getInputStream() { - return stream; - } - - @Override - protected void setInputStream(InputStream is) { - stream = is; - resetEntity(); - } - - @Override - public void releaseConnection() throws IOException { - releaseConnection(false); - } - - @Override - public void releaseConnection(boolean consumeInputStream) throws IOException { - InputStream is = getInputStream(); - if (is != null && consumeInputStream) - { - while (is.read() > 0) - { - } - } - cancel.run(); - } - + private final Runnable cancel; + private InputStream stream; + + JettyClientResponse(ClientConfiguration configuration, InputStream stream, Runnable cancel) { + super(configuration); + this.cancel = cancel; + this.stream = stream; + } + + @Override + protected InputStream getInputStream() { + return stream; + } + + @Override + protected void setInputStream(InputStream is) { + stream = is; + resetEntity(); + } + + @Override + public void releaseConnection() throws IOException { + releaseConnection(false); + } + + @Override + public void releaseConnection(boolean consumeInputStream) throws IOException { + InputStream is = getInputStream(); + if (is != null && consumeInputStream) + { + while (is.read() > 0) + { + } + } + cancel.run(); + } + } diff --git a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyContentStream.java b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyContentStream.java index 5cee3714eba..ea0c881defe 100644 --- a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyContentStream.java +++ b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyContentStream.java @@ -9,94 +9,94 @@ import org.eclipse.jetty.util.Callback; class JettyContentStream extends OutputStream { - private static final int BUF_SIZE = 16 * 1024; - - private final ByteBufferPool bufs; - private final DeferredContentProvider out; - - private ByteBuffer buf; - - JettyContentStream(ByteBufferPool bufs, DeferredContentProvider out) { - this.bufs = bufs; - this.out = out; - buf = acquire(); - } - - @Override - public void write(int b) throws IOException { - checkClose(); - if (!buf.hasRemaining()) { - flush(); - } - buf.put((byte)b); - } - - @Override - public void write(byte[] b, int off, int rem) { - checkClose(); - while (true) { - if (!buf.hasRemaining() || rem == 0) { - flush(); - return; - } - final int r = Math.min(buf.remaining(), rem); - buf.put(b, off, r); - off += r; - rem -= r; + private static final int BUF_SIZE = 16 * 1024; + + private final ByteBufferPool bufs; + private final DeferredContentProvider out; + + private ByteBuffer buf; + + JettyContentStream(ByteBufferPool bufs, DeferredContentProvider out) { + this.bufs = bufs; + this.out = out; + buf = acquire(); + } + + @Override + public void write(int b) throws IOException { + checkClose(); + if (!buf.hasRemaining()) { + flush(); + } + buf.put((byte)b); + } + + @Override + public void write(byte[] b, int off, int rem) { + checkClose(); + while (true) { + if (!buf.hasRemaining() || rem == 0) { flush(); - } - } - - @Override - public void flush() { - checkClose(); - buf.flip(); - if (buf.limit() == 0) { - bufs.release(buf); return; - } - out.offer(buf, new ReleaseCallback(bufs, buf)); - buf = acquire(); - } - - @Override - public void close() throws IOException { - if (buf != null) { - flush(); - buf = null; - } - } - - private void checkClose() { - if (out.isClosed()) { - throw new IllegalStateException("closed"); - } - } - - private ByteBuffer acquire() { - final ByteBuffer b = bufs.acquire(BUF_SIZE, false); - b.limit(b.capacity()); - return b; - } + } + final int r = Math.min(buf.remaining(), rem); + buf.put(b, off, r); + off += r; + rem -= r; + flush(); + } + } + + @Override + public void flush() { + checkClose(); + buf.flip(); + if (buf.limit() == 0) { + bufs.release(buf); + return; + } + out.offer(buf, new ReleaseCallback(bufs, buf)); + buf = acquire(); + } + + @Override + public void close() throws IOException { + if (buf != null) { + flush(); + buf = null; + } + } + + private void checkClose() { + if (out.isClosed()) { + throw new IllegalStateException("closed"); + } + } + + private ByteBuffer acquire() { + final ByteBuffer b = bufs.acquire(BUF_SIZE, false); + b.limit(b.capacity()); + return b; + } } class ReleaseCallback implements Callback { - private final ByteBufferPool bufs; - private final ByteBuffer buf; + private final ByteBufferPool bufs; + private final ByteBuffer buf; - ReleaseCallback(ByteBufferPool bufs, ByteBuffer buf) { - this.bufs = bufs; - this.buf = buf; - } + ReleaseCallback(ByteBufferPool bufs, ByteBuffer buf) { + this.bufs = bufs; + this.buf = buf; + } - @Override - public void succeeded() { - bufs.release(buf); - } + @Override + public void succeeded() { + bufs.release(buf); + } - @Override - public void failed(Throwable x) { - bufs.release(buf); - } + @Override + public void failed(Throwable x) { + bufs.release(buf); + } } diff --git a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyResponseStream.java b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyResponseStream.java index 41e73109f1a..09e6c525245 100644 --- a/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyResponseStream.java +++ b/resteasy-client-jetty/src/main/java/org/jboss/resteasy/client/jaxrs/engines/jetty/JettyResponseStream.java @@ -10,72 +10,72 @@ import org.eclipse.jetty.util.Callback; class JettyResponseStream extends InputStream { - private final Deque chunks = new LinkedList<>(); - private Chunk readTop; - private volatile boolean closed; + private final Deque chunks = new LinkedList<>(); + private Chunk readTop; + private volatile boolean closed; - void offer(ByteBuffer content, Callback callback) { - if (closed) { - final IllegalStateException x = new IllegalStateException("closed"); - callback.failed(x); - throw x; - } - chunks.add(new Chunk(content, callback)); - } + void offer(ByteBuffer content, Callback callback) { + if (closed) { + final IllegalStateException x = new IllegalStateException("closed"); + callback.failed(x); + throw x; + } + chunks.add(new Chunk(content, callback)); + } - @Override - public int read() throws IOException { - return read0(chunk -> chunk.buf.get()); - } + @Override + public int read() throws IOException { + return read0(chunk -> chunk.buf.get()); + } - @Override - public int read(byte[] b, int off, int len) throws IOException { - return read0(chunk -> { - final int r = Math.min(chunk.buf.remaining(), len); - chunk.buf.get(b, off, r); - return r; - }); - } + @Override + public int read(byte[] b, int off, int len) throws IOException { + return read0(chunk -> { + final int r = Math.min(chunk.buf.remaining(), len); + chunk.buf.get(b, off, r); + return r; + }); + } - private int read0(ToIntFunction reader) throws IOException { - if (closed) { - throw new IllegalStateException("closed"); - } - if (readTop == null) { - readTop = chunks.pollFirst(); - } - if (readTop == null || closed) { - return -1; - } + private int read0(ToIntFunction reader) throws IOException { + if (closed) { + throw new IllegalStateException("closed"); + } + if (readTop == null) { + readTop = chunks.pollFirst(); + } + if (readTop == null || closed) { + return -1; + } - final int result = reader.applyAsInt(readTop); - if (!readTop.buf.hasRemaining()) { - readTop.callback.succeeded(); - readTop = null; - } - return result; - } + final int result = reader.applyAsInt(readTop); + if (!readTop.buf.hasRemaining()) { + readTop.callback.succeeded(); + readTop = null; + } + return result; + } - @Override - public void close() throws IOException { - closed = true; - if (readTop != null) { - readTop.callback.succeeded(); - readTop = null; - } - chunks.removeIf(c -> { - c.callback.succeeded(); - return true; - }); - } + @Override + public void close() throws IOException { + closed = true; + if (readTop != null) { + readTop.callback.succeeded(); + readTop = null; + } + chunks.removeIf(c -> { + c.callback.succeeded(); + return true; + }); + } - static class Chunk { - final ByteBuffer buf; - final Callback callback; + static class Chunk { + final ByteBuffer buf; + final Callback callback; - Chunk(ByteBuffer buf, Callback callback) { - this.buf = buf; - this.callback = callback; - } - } + Chunk(ByteBuffer buf, Callback callback) { + this.buf = buf; + this.callback = callback; + } + } } diff --git a/resteasy-client-jetty/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java b/resteasy-client-jetty/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java index e9be3206e50..89567919608 100644 --- a/resteasy-client-jetty/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java +++ b/resteasy-client-jetty/src/test/java/org/jboss/resteasy/test/client/jetty/JettyClientEngineTest.java @@ -42,198 +42,198 @@ import org.junit.Test; public class JettyClientEngineTest { - Server server = new Server(0); - Client client; - - @After - public void stop() throws Exception { - if (client != null) { - client.close(); - } - server.stop(); - } - - private Client client() throws Exception { - if (!server.isStarted()) { - server.start(); - } - if (client == null) { - final HttpClient hc = new HttpClient(); - client = new ResteasyClientBuilder().httpEngine(new JettyClientEngine(hc)).build(); - } - return client; - } - - @Test - public void testSimple() throws Exception { - server.setHandler(new AbstractHandler() { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { - baseRequest.setHandled(true); - if (baseRequest.getHeader("User-Agent").contains("Apache")) { - response.setStatus(503); - } else if (!"abracadabra".equals(baseRequest.getHeader("Password"))) { - response.setStatus(403); - } else { - response.setStatus(200); - response.getWriter().println("Success"); - } - } - }); - - final Response response = client().target(baseUri()).request() - .header("Password", "abracadabra") - .get(); - - assertEquals(200, response.getStatus()); - assertEquals("Success\n", response.readEntity(String.class)); - } - - @Test - public void testBigly() throws Exception { - server.setHandler(new EchoHandler()); - final byte[] valuableData = randomAlpha().getBytes(StandardCharsets.UTF_8); - final Response response = client().target(baseUri()).request() - .post(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)); - - assertEquals(200, response.getStatus()); - assertArrayEquals(valuableData, response.readEntity(byte[].class)); - } - - @Test - public void testFutureResponse() throws Exception { - server.setHandler(new EchoHandler()); - final String valuableData = randomAlpha(); - final Future response = client().target(baseUri()).request() - .buildPost(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)) - .submit(); - - final Response resp = response.get(10, TimeUnit.SECONDS); - assertEquals(200, resp.getStatus()); - assertEquals(valuableData, resp.readEntity(String.class)); - } - - @Test - public void testFutureString() throws Exception { - server.setHandler(new EchoHandler()); - final String valuableData = randomAlpha(); - final Future response = client().target(baseUri()).request() - .buildPost(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)) - .submit(String.class); - - final String result = response.get(10, TimeUnit.SECONDS); - assertEquals(valuableData, result); - } - - private String randomAlpha() { - final StringBuilder builder = new StringBuilder(); - final Random r = new Random(); - for (int i = 0; i < 20 * 1024 * 1024; i++) { - builder.append((char) ('a' + (char) r.nextInt('z' - 'a'))); - if (i % 100 == 0) builder.append('\n'); - } - return builder.toString(); - } - - @Test - public void testTimeout() throws Exception { - server.setHandler(new AbstractHandler() { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new AssertionError(e); - } - baseRequest.setHandled(true); - } - }); - - try { - client().target(baseUri()).request() - .property(JettyClientEngine.REQUEST_TIMEOUT_MS, Duration.ofMillis(500)) - .get(); - fail(); - } catch (ProcessingException e) { - assertTrue(e.getCause() instanceof TimeoutException); - } - } - - @Test - public void testDeferContent() throws Exception { - server.setHandler(new EchoHandler()); - final byte[] valuableData = randomAlpha().getBytes(StandardCharsets.UTF_8); - final Response response = client().target(baseUri()).request() - .post(Entity.entity(new StreamingOutput() { - @Override - public void write(OutputStream output) throws IOException, WebApplicationException { - try { - Thread.sleep(100); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new AssertionError(e); - } - output.write(valuableData); - } - }, MediaType.APPLICATION_OCTET_STREAM_TYPE)); - - assertEquals(200, response.getStatus()); - assertArrayEquals(valuableData, response.readEntity(byte[].class)); - } - - @Test - public void testFilterBufferReplay() throws Exception { - final String greeting = "Success"; - final byte[] expected = (greeting + '\n').getBytes(StandardCharsets.UTF_8); - server.setHandler(new AbstractHandler() { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { - baseRequest.setHandled(true); - response.setStatus(200); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println(greeting); + Server server = new Server(0); + Client client; + + @After + public void stop() throws Exception { + if (client != null) { + client.close(); + } + server.stop(); + } + + private Client client() throws Exception { + if (!server.isStarted()) { + server.start(); + } + if (client == null) { + final HttpClient hc = new HttpClient(); + client = new ResteasyClientBuilder().httpEngine(new JettyClientEngine(hc)).build(); + } + return client; + } + + @Test + public void testSimple() throws Exception { + server.setHandler(new AbstractHandler() { + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { + baseRequest.setHandled(true); + if (baseRequest.getHeader("User-Agent").contains("Apache")) { + response.setStatus(503); + } else if (!"abracadabra".equals(baseRequest.getHeader("Password"))) { + response.setStatus(403); + } else { + response.setStatus(200); + response.getWriter().println("Success"); } - }); - - final byte[] content = new byte[expected.length]; - final ClientResponseFilter capturer = new ClientResponseFilter() { - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - responseContext.getEntityStream().read(content); + } + }); + + final Response response = client().target(baseUri()).request() + .header("Password", "abracadabra") + .get(); + + assertEquals(200, response.getStatus()); + assertEquals("Success\n", response.readEntity(String.class)); + } + + @Test + public void testBigly() throws Exception { + server.setHandler(new EchoHandler()); + final byte[] valuableData = randomAlpha().getBytes(StandardCharsets.UTF_8); + final Response response = client().target(baseUri()).request() + .post(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + + assertEquals(200, response.getStatus()); + assertArrayEquals(valuableData, response.readEntity(byte[].class)); + } + + @Test + public void testFutureResponse() throws Exception { + server.setHandler(new EchoHandler()); + final String valuableData = randomAlpha(); + final Future response = client().target(baseUri()).request() + .buildPost(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)) + .submit(); + + final Response resp = response.get(10, TimeUnit.SECONDS); + assertEquals(200, resp.getStatus()); + assertEquals(valuableData, resp.readEntity(String.class)); + } + + @Test + public void testFutureString() throws Exception { + server.setHandler(new EchoHandler()); + final String valuableData = randomAlpha(); + final Future response = client().target(baseUri()).request() + .buildPost(Entity.entity(valuableData, MediaType.APPLICATION_OCTET_STREAM_TYPE)) + .submit(String.class); + + final String result = response.get(10, TimeUnit.SECONDS); + assertEquals(valuableData, result); + } + + private String randomAlpha() { + final StringBuilder builder = new StringBuilder(); + final Random r = new Random(); + for (int i = 0; i < 20 * 1024 * 1024; i++) { + builder.append((char) ('a' + (char) r.nextInt('z' - 'a'))); + if (i % 100 == 0) builder.append('\n'); + } + return builder.toString(); + } + + @Test + public void testTimeout() throws Exception { + server.setHandler(new AbstractHandler() { + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); } - }; - - try (InputStream response = client().register(capturer).target(baseUri()).request() - .get(InputStream.class)) { - // ignored, we are checking filter - } - - assertArrayEquals(expected, content); - } - - public URI baseUri() { - return URI.create("http://localhost:" + ((ServerConnector) server.getConnectors()[0]).getLocalPort()); - } - - static class EchoHandler extends AbstractHandler { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { baseRequest.setHandled(true); - String type = request.getContentType(); - if (type == null) { - type = MediaType.TEXT_PLAIN; - } + } + }); - response.setContentType(type); + try { + client().target(baseUri()).request() + .property(JettyClientEngine.REQUEST_TIMEOUT_MS, Duration.ofMillis(500)) + .get(); + fail(); + } catch (ProcessingException e) { + assertTrue(e.getCause() instanceof TimeoutException); + } + } + + @Test + public void testDeferContent() throws Exception { + server.setHandler(new EchoHandler()); + final byte[] valuableData = randomAlpha().getBytes(StandardCharsets.UTF_8); + final Response response = client().target(baseUri()).request() + .post(Entity.entity(new StreamingOutput() { + @Override + public void write(OutputStream output) throws IOException, WebApplicationException { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + output.write(valuableData); + } + }, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + + assertEquals(200, response.getStatus()); + assertArrayEquals(valuableData, response.readEntity(byte[].class)); + } + + @Test + public void testFilterBufferReplay() throws Exception { + final String greeting = "Success"; + final byte[] expected = (greeting + '\n').getBytes(StandardCharsets.UTF_8); + server.setHandler(new AbstractHandler() { + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { + baseRequest.setHandled(true); response.setStatus(200); - int read; - final byte[] data = new byte[1024]; - final ServletInputStream in = request.getInputStream(); - final ServletOutputStream out = response.getOutputStream(); - while ((read = in.read(data)) != -1) { - out.write(data, 0, read); - } - } - } + response.setContentType(MediaType.TEXT_PLAIN); + response.getWriter().println(greeting); + } + }); + + final byte[] content = new byte[expected.length]; + final ClientResponseFilter capturer = new ClientResponseFilter() { + @Override + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + responseContext.getEntityStream().read(content); + } + }; + + try (InputStream response = client().register(capturer).target(baseUri()).request() + .get(InputStream.class)) { + // ignored, we are checking filter + } + + assertArrayEquals(expected, content); + } + + public URI baseUri() { + return URI.create("http://localhost:" + ((ServerConnector) server.getConnectors()[0]).getLocalPort()); + } + + static class EchoHandler extends AbstractHandler { + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { + baseRequest.setHandled(true); + String type = request.getContentType(); + if (type == null) { + type = MediaType.TEXT_PLAIN; + } + + response.setContentType(type); + response.setStatus(200); + int read; + final byte[] data = new byte[1024]; + final ServletInputStream in = request.getInputStream(); + final ServletOutputStream out = response.getOutputStream(); + while ((read = in.read(data)) != -1) { + out.write(data, 0, read); + } + } + } } diff --git a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientDelegateBean.java b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientDelegateBean.java index 83d2eb4c44d..3610e535144 100644 --- a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientDelegateBean.java +++ b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientDelegateBean.java @@ -27,129 +27,129 @@ public class RestClientDelegateBean implements Bean, PassivationCapable { - public static final String REST_URL_FORMAT = "%s/mp-rest/url"; - - public static final String REST_SCOPE_FORMAT = "%s/mp-rest/scope"; - - private final Class proxyType; - - private final Class scope; - - private final BeanManager beanManager; - - private final Config config; - - RestClientDelegateBean(Class proxyType, BeanManager beanManager) { - this.proxyType = proxyType; - this.beanManager = beanManager; - this.config = ConfigProvider.getConfig(); // TODO should this be injected? - this.scope = this.resolveScope(); - } - @Override - public String getId() { - return proxyType.getName(); - } - - @Override - public Class getBeanClass() { - return proxyType; - } - - @Override - public Set getInjectionPoints() { - return Collections.emptySet(); - } - - @Override - public boolean isNullable() { - return false; - } - - @Override - public Object create(CreationalContext creationalContext) { - RestClientBuilder builder = RestClientBuilder.newBuilder(); - String baseUrl = getBaseUrl(); - try { - return builder.baseUrl(new URL(baseUrl)).build(proxyType); - } catch (MalformedURLException e) { - throw new IllegalArgumentException("The value of URL was invalid "+baseUrl); - } - } - - @Override - public void destroy(Object instance, CreationalContext creationalContext) { - - } - - @Override - public Set getTypes() { - return Collections.singleton(proxyType); - } - - @Override - public Set getQualifiers() { - //return Collections.singleton(RestClient.LITERAL); - Set qualifiers = new HashSet(); - qualifiers.add( new AnnotationLiteral() {} ); - qualifiers.add( new AnnotationLiteral() {} ); - qualifiers.add(RestClient.LITERAL); - return qualifiers; - } - - @Override - public Class getScope() { - return scope; - } - - @Override - public String getName() { - return proxyType.getName(); - } - - @Override - public Set> getStereotypes() { - return Collections.emptySet(); - } - - @Override - public boolean isAlternative() { - return false; - } - - private String getBaseUrl() { - String property = String.format(REST_URL_FORMAT, proxyType.getName()); - return config.getValue(property, String.class); - } - - @SuppressWarnings("unchecked") - private Class resolveScope() { - - String property = String.format(REST_SCOPE_FORMAT, proxyType.getName()); - String configuredScope = config.getOptionalValue(property, String.class).orElse(null); - - if(configuredScope != null) { - try { - return (Class)Class.forName(configuredScope); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid scope: " + configuredScope ,e); - } - } - - List possibleScopes = new ArrayList<>(); - Annotation[] annotations = proxyType.getDeclaredAnnotations(); - for(Annotation annotation : annotations) { - if(beanManager.isScope(annotation.annotationType())) { - possibleScopes.add(annotation); - } - } - if(possibleScopes.isEmpty()) { - return Dependent.class; - } - else if(possibleScopes.size() == 1) { - return possibleScopes.get(0).annotationType(); - } - else { - throw new IllegalArgumentException("Ambiguous scope definition on "+ proxyType +": " + possibleScopes); - } - } + public static final String REST_URL_FORMAT = "%s/mp-rest/url"; + + public static final String REST_SCOPE_FORMAT = "%s/mp-rest/scope"; + + private final Class proxyType; + + private final Class scope; + + private final BeanManager beanManager; + + private final Config config; + + RestClientDelegateBean(Class proxyType, BeanManager beanManager) { + this.proxyType = proxyType; + this.beanManager = beanManager; + this.config = ConfigProvider.getConfig(); // TODO should this be injected? + this.scope = this.resolveScope(); + } + @Override + public String getId() { + return proxyType.getName(); + } + + @Override + public Class getBeanClass() { + return proxyType; + } + + @Override + public Set getInjectionPoints() { + return Collections.emptySet(); + } + + @Override + public boolean isNullable() { + return false; + } + + @Override + public Object create(CreationalContext creationalContext) { + RestClientBuilder builder = RestClientBuilder.newBuilder(); + String baseUrl = getBaseUrl(); + try { + return builder.baseUrl(new URL(baseUrl)).build(proxyType); + } catch (MalformedURLException e) { + throw new IllegalArgumentException("The value of URL was invalid "+baseUrl); + } + } + + @Override + public void destroy(Object instance, CreationalContext creationalContext) { + + } + + @Override + public Set getTypes() { + return Collections.singleton(proxyType); + } + + @Override + public Set getQualifiers() { + //return Collections.singleton(RestClient.LITERAL); + Set qualifiers = new HashSet(); + qualifiers.add( new AnnotationLiteral() {} ); + qualifiers.add( new AnnotationLiteral() {} ); + qualifiers.add(RestClient.LITERAL); + return qualifiers; + } + + @Override + public Class getScope() { + return scope; + } + + @Override + public String getName() { + return proxyType.getName(); + } + + @Override + public Set> getStereotypes() { + return Collections.emptySet(); + } + + @Override + public boolean isAlternative() { + return false; + } + + private String getBaseUrl() { + String property = String.format(REST_URL_FORMAT, proxyType.getName()); + return config.getValue(property, String.class); + } + + @SuppressWarnings("unchecked") + private Class resolveScope() { + + String property = String.format(REST_SCOPE_FORMAT, proxyType.getName()); + String configuredScope = config.getOptionalValue(property, String.class).orElse(null); + + if(configuredScope != null) { + try { + return (Class)Class.forName(configuredScope); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid scope: " + configuredScope ,e); + } + } + + List possibleScopes = new ArrayList<>(); + Annotation[] annotations = proxyType.getDeclaredAnnotations(); + for(Annotation annotation : annotations) { + if(beanManager.isScope(annotation.annotationType())) { + possibleScopes.add(annotation); + } + } + if(possibleScopes.isEmpty()) { + return Dependent.class; + } + else if(possibleScopes.size() == 1) { + return possibleScopes.get(0).annotationType(); + } + else { + throw new IllegalArgumentException("Ambiguous scope definition on "+ proxyType +": " + possibleScopes); + } + } } diff --git a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientExtension.java b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientExtension.java index a0f08b66c8c..d640edd7094 100644 --- a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientExtension.java +++ b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/cdi/microprofile/RestClientExtension.java @@ -18,29 +18,29 @@ */ public class RestClientExtension implements Extension { - private static Set> proxyTypes = new LinkedHashSet<>(); - - private static Set errors = new LinkedHashSet<>(); - - public void registerClient(@Observes @WithAnnotations({RegisterRestClient.class}) ProcessAnnotatedType pat) { - Class typeDef = pat.getAnnotatedType().getJavaClass(); - if(typeDef.isInterface()) { - proxyTypes.add(typeDef); - pat.veto(); - } else { - errors.add(new IllegalArgumentException("Rest client needs to be interface: " + typeDef)); - } - } - - public void createProxy(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { - for (Class proxyType : proxyTypes) { - afterBeanDiscovery.addBean(new RestClientDelegateBean(proxyType, beanManager)); - } - } - - public void reportErrors(@Observes AfterDeploymentValidation afterDeploymentValidation) { - for (Throwable error : errors) { - afterDeploymentValidation.addDeploymentProblem(error); - } - } + private static Set> proxyTypes = new LinkedHashSet<>(); + + private static Set errors = new LinkedHashSet<>(); + + public void registerClient(@Observes @WithAnnotations({RegisterRestClient.class}) ProcessAnnotatedType pat) { + Class typeDef = pat.getAnnotatedType().getJavaClass(); + if(typeDef.isInterface()) { + proxyTypes.add(typeDef); + pat.veto(); + } else { + errors.add(new IllegalArgumentException("Rest client needs to be interface: " + typeDef)); + } + } + + public void createProxy(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { + for (Class proxyType : proxyTypes) { + afterBeanDiscovery.addBean(new RestClientDelegateBean(proxyType, beanManager)); + } + } + + public void reportErrors(@Observes AfterDeploymentValidation afterDeploymentValidation) { + for (Throwable error : errors) { + afterDeploymentValidation.addDeploymentProblem(error); + } + } } diff --git a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilder.java b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilder.java index 3bbfb91da22..7269a9b4b30 100644 --- a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilder.java +++ b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilder.java @@ -45,71 +45,71 @@ class MicroprofileClientBuilder implements RestClientBuilder { private static final Logger LOG = Logger.getLogger(MicroprofileClientBuilder.class); MicroprofileClientBuilder() { - ClientBuilder availableBuilder = ClientBuilder.newBuilder(); - - if (availableBuilder instanceof ResteasyClientBuilder) { - this.builderDelegate = (ResteasyClientBuilder) availableBuilder; - this.configurationWrapper = new ConfigurationWrapper(this.builderDelegate.getConfiguration()); - Config cfg = null; - try { - ConfigProviderResolver.instance(); - cfg = ConfigProvider.getConfig(); - } catch (IllegalStateException ise) { - //ignore - } - this.config = cfg; - } else { - throw new IllegalStateException("Incompatible client builder found " + availableBuilder.getClass()); - } + ClientBuilder availableBuilder = ClientBuilder.newBuilder(); + + if (availableBuilder instanceof ResteasyClientBuilder) { + this.builderDelegate = (ResteasyClientBuilder) availableBuilder; + this.configurationWrapper = new ConfigurationWrapper(this.builderDelegate.getConfiguration()); + Config cfg = null; + try { + ConfigProviderResolver.instance(); + cfg = ConfigProvider.getConfig(); + } catch (IllegalStateException ise) { + //ignore + } + this.config = cfg; + } else { + throw new IllegalStateException("Incompatible client builder found " + availableBuilder.getClass()); + } } public Configuration getConfigurationWrapper() { - return this.configurationWrapper; + return this.configurationWrapper; } @Override public RestClientBuilder baseUrl(URL url) { - try { - this.baseURI = url.toURI(); - return this; - } catch (URISyntaxException e) { - throw new RuntimeException(e.getMessage()); - } + try { + this.baseURI = url.toURI(); + return this; + } catch (URISyntaxException e) { + throw new RuntimeException(e.getMessage()); + } } @SuppressWarnings("unchecked") @Override public T build(Class aClass) throws IllegalStateException, RestClientDefinitionException { - // Interface validity - verifyInterface(aClass); + // Interface validity + verifyInterface(aClass); - // Provider annotations - RegisterProvider[] providers = aClass.getAnnotationsByType(RegisterProvider.class); + // Provider annotations + RegisterProvider[] providers = aClass.getAnnotationsByType(RegisterProvider.class); - for (RegisterProvider provider : providers) { - register(provider.value(), provider.priority()); - } + for (RegisterProvider provider : providers) { + register(provider.value(), provider.priority()); + } - // Default exception mapper - if (!isMapperDisabled()) { - register(DefaultResponseExceptionMapper.class); - } + // Default exception mapper + if (!isMapperDisabled()) { + register(DefaultResponseExceptionMapper.class); + } - this.builderDelegate.register(new ExceptionMapping(localProviderInstances), 1); + this.builderDelegate.register(new ExceptionMapping(localProviderInstances), 1); - ClassLoader classLoader = aClass.getClassLoader(); + ClassLoader classLoader = aClass.getClassLoader(); - List noProxyHosts = Arrays.asList( + List noProxyHosts = Arrays.asList( System.getProperty("http.nonProxyHosts", "localhost|127.*|[::1]").split("|")); - final T actualClient; + final T actualClient; - final String proxyHost = System.getProperty("http.proxyHost"); + final String proxyHost = System.getProperty("http.proxyHost"); - if (proxyHost != null && !noProxyHosts.contains(this.baseURI.getHost())) { - // Use proxy, if defined - actualClient = this.builderDelegate.defaultProxy( + if (proxyHost != null && !noProxyHosts.contains(this.baseURI.getHost())) { + // Use proxy, if defined + actualClient = this.builderDelegate.defaultProxy( proxyHost, Integer.parseInt(System.getProperty("http.proxyPort", "80"))) .build() @@ -119,249 +119,249 @@ public T build(Class aClass) throws IllegalStateException, RestClientDefi .defaultConsumes(MediaType.TEXT_PLAIN) .defaultProduces(MediaType.TEXT_PLAIN) .build(); - } else { - actualClient = this.builderDelegate.build() + } else { + actualClient = this.builderDelegate.build() .target(this.baseURI) .proxyBuilder(aClass) .classloader(classLoader) .defaultConsumes(MediaType.TEXT_PLAIN) .defaultProduces(MediaType.TEXT_PLAIN) .build(); - } + } - return (T) Proxy.newProxyInstance( + return (T) Proxy.newProxyInstance( classLoader, new Class[] {aClass}, new ProxyInvocationHandler(actualClient, getLocalProviderInstances()) - ); + ); } private boolean isMapperDisabled() { - boolean disabled = false; - Optional defaultMapperProp = this.config != null ? this.config.getOptionalValue(DEFAULT_MAPPER_PROP, Boolean.class) : Optional.empty(); - - // disabled through config api - if (defaultMapperProp.isPresent() && defaultMapperProp.get().equals(Boolean.TRUE)) { - disabled = true; - } else if (!defaultMapperProp.isPresent()) { - - // disabled through jaxrs property - try { - Object property = this.builderDelegate.getConfiguration().getProperty(DEFAULT_MAPPER_PROP); - if (property != null) { - disabled = (Boolean)property; - } - } catch (Throwable e) { + boolean disabled = false; + Optional defaultMapperProp = this.config != null ? this.config.getOptionalValue(DEFAULT_MAPPER_PROP, Boolean.class) : Optional.empty(); + + // disabled through config api + if (defaultMapperProp.isPresent() && defaultMapperProp.get().equals(Boolean.TRUE)) { + disabled = true; + } else if (!defaultMapperProp.isPresent()) { + + // disabled through jaxrs property + try { + Object property = this.builderDelegate.getConfiguration().getProperty(DEFAULT_MAPPER_PROP); + if (property != null) { + disabled = (Boolean)property; + } + } catch (Throwable e) { // ignore cast exception - } - } - return disabled; + } + } + return disabled; } private void verifyInterface(Class typeDef) { - Method[] methods = typeDef.getMethods(); - - // multiple verbs - for (Method method : methods) { - boolean hasHttpMethod = false; - for (Annotation annotation : method.getAnnotations()) { - boolean isHttpMethod = (annotation.annotationType().getAnnotation(HttpMethod.class) != null); - if (!hasHttpMethod && isHttpMethod) { - hasHttpMethod = true; - } else if (hasHttpMethod && isHttpMethod) { - throw new RestClientDefinitionException("Ambiguous @Httpmethod defintion on type " + typeDef); - } - } - } - - // invalid parameter - Path classPathAnno = typeDef.getAnnotation(Path.class); - - final Set classLevelVariables = new HashSet<>(); - ResteasyUriBuilder classTemplate = null; - if (classPathAnno != null) { - classTemplate = (ResteasyUriBuilder) UriBuilder.fromUri(classPathAnno.value()); - classLevelVariables.addAll(classTemplate.getPathParamNamesInDeclarationOrder()); - } - ResteasyUriBuilder template; - for (Method method : methods) { - - Path methodPathAnno = method.getAnnotation(Path.class); - if (methodPathAnno != null) { - template = classPathAnno == null ? (ResteasyUriBuilder)UriBuilder.fromUri(methodPathAnno.value()) + Method[] methods = typeDef.getMethods(); + + // multiple verbs + for (Method method : methods) { + boolean hasHttpMethod = false; + for (Annotation annotation : method.getAnnotations()) { + boolean isHttpMethod = (annotation.annotationType().getAnnotation(HttpMethod.class) != null); + if (!hasHttpMethod && isHttpMethod) { + hasHttpMethod = true; + } else if (hasHttpMethod && isHttpMethod) { + throw new RestClientDefinitionException("Ambiguous @Httpmethod defintion on type " + typeDef); + } + } + } + + // invalid parameter + Path classPathAnno = typeDef.getAnnotation(Path.class); + + final Set classLevelVariables = new HashSet<>(); + ResteasyUriBuilder classTemplate = null; + if (classPathAnno != null) { + classTemplate = (ResteasyUriBuilder) UriBuilder.fromUri(classPathAnno.value()); + classLevelVariables.addAll(classTemplate.getPathParamNamesInDeclarationOrder()); + } + ResteasyUriBuilder template; + for (Method method : methods) { + + Path methodPathAnno = method.getAnnotation(Path.class); + if (methodPathAnno != null) { + template = classPathAnno == null ? (ResteasyUriBuilder)UriBuilder.fromUri(methodPathAnno.value()) : (ResteasyUriBuilder)UriBuilder.fromUri(classPathAnno.value() + "/" + methodPathAnno.value()); - } else { - template = classTemplate; - } - if (template == null) { - continue; - } - - // it's not executed, so this can be anything - but a hostname needs to present - template.host("localhost"); - - Set allVariables = new HashSet<>(template.getPathParamNamesInDeclarationOrder()); - Map paramMap = new HashMap<>(); - for (Parameter p : method.getParameters()) { - PathParam pathParam = p.getAnnotation(PathParam.class); - if (pathParam != null) { - paramMap.put(pathParam.value(), "foobar"); - } - } - - if (allVariables.size() != paramMap.size()) { - throw new RestClientDefinitionException("Parameters and variables don't match on " + typeDef + "::" + method.getName()); - } - - try { - template.resolveTemplates(paramMap, false).build(); - } catch (IllegalArgumentException ex) { - throw new RestClientDefinitionException("Parameter names don't match variable names on " + typeDef + "::" + method.getName(), ex); - } - - } + } else { + template = classTemplate; + } + if (template == null) { + continue; + } + + // it's not executed, so this can be anything - but a hostname needs to present + template.host("localhost"); + + Set allVariables = new HashSet<>(template.getPathParamNamesInDeclarationOrder()); + Map paramMap = new HashMap<>(); + for (Parameter p : method.getParameters()) { + PathParam pathParam = p.getAnnotation(PathParam.class); + if (pathParam != null) { + paramMap.put(pathParam.value(), "foobar"); + } + } + + if (allVariables.size() != paramMap.size()) { + throw new RestClientDefinitionException("Parameters and variables don't match on " + typeDef + "::" + method.getName()); + } + + try { + template.resolveTemplates(paramMap, false).build(); + } catch (IllegalArgumentException ex) { + throw new RestClientDefinitionException("Parameter names don't match variable names on " + typeDef + "::" + method.getName(), ex); + } + + } } @Override public Configuration getConfiguration() { - return getConfigurationWrapper(); + return getConfigurationWrapper(); } @Override public RestClientBuilder property(String name, Object value) { - this.builderDelegate.property(name, value); - return this; + this.builderDelegate.property(name, value); + return this; } private static Object newInstanceOf(Class clazz) { - try { - return clazz.newInstance(); - } catch (Throwable t) { - throw new RuntimeException("Failed to register " + clazz, t); - } + try { + return clazz.newInstance(); + } catch (Throwable t) { + throw new RuntimeException("Failed to register " + clazz, t); + } } @Override public RestClientBuilder register(Class aClass) { - this.register(newInstanceOf(aClass)); - return this; + this.register(newInstanceOf(aClass)); + return this; } @Override public RestClientBuilder register(Class aClass, int i) { - this.register(newInstanceOf(aClass), i); - return this; + this.register(newInstanceOf(aClass), i); + return this; } @Override public RestClientBuilder register(Class aClass, Class[] classes) { - this.register(newInstanceOf(aClass), classes); - return this; + this.register(newInstanceOf(aClass), classes); + return this; } @Override public RestClientBuilder register(Class aClass, Map, Integer> map) { - this.register(newInstanceOf(aClass), map); - return this; + this.register(newInstanceOf(aClass), map); + return this; } @Override public RestClientBuilder register(Object o) { - if (o instanceof ResponseExceptionMapper) { - ResponseExceptionMapper mapper = (ResponseExceptionMapper)o; - register(mapper, mapper.getPriority()); - } else if (o instanceof ParamConverterProvider) { - register(o, Priorities.USER); - } else { - this.builderDelegate.register(o); - } - return this; + if (o instanceof ResponseExceptionMapper) { + ResponseExceptionMapper mapper = (ResponseExceptionMapper)o; + register(mapper, mapper.getPriority()); + } else if (o instanceof ParamConverterProvider) { + register(o, Priorities.USER); + } else { + this.builderDelegate.register(o); + } + return this; } @Override public RestClientBuilder register(Object o, int i) { - if (o instanceof ResponseExceptionMapper) { + if (o instanceof ResponseExceptionMapper) { - // local - ResponseExceptionMapper mapper = (ResponseExceptionMapper)o; - HashMap, Integer> contracts = new HashMap<>(); - contracts.put(ResponseExceptionMapper.class, i); - registerLocalProviderInstance(mapper, contracts); + // local + ResponseExceptionMapper mapper = (ResponseExceptionMapper)o; + HashMap, Integer> contracts = new HashMap<>(); + contracts.put(ResponseExceptionMapper.class, i); + registerLocalProviderInstance(mapper, contracts); - // delegate - this.builderDelegate.register(mapper, i); + // delegate + this.builderDelegate.register(mapper, i); - } else if (o instanceof ParamConverterProvider) { + } else if (o instanceof ParamConverterProvider) { - // local - ParamConverterProvider converter = (ParamConverterProvider)o; - HashMap, Integer> contracts = new HashMap<>(); - contracts.put(ParamConverterProvider.class, i); - registerLocalProviderInstance(converter, contracts); + // local + ParamConverterProvider converter = (ParamConverterProvider)o; + HashMap, Integer> contracts = new HashMap<>(); + contracts.put(ParamConverterProvider.class, i); + registerLocalProviderInstance(converter, contracts); - // delegate - this.builderDelegate.register(converter, i); + // delegate + this.builderDelegate.register(converter, i); - } else { - this.builderDelegate.register(o, i); - } - return this; + } else { + this.builderDelegate.register(o, i); + } + return this; } @Override public RestClientBuilder register(Object o, Class[] classes) { - // local - for (Class aClass : classes) { - if (aClass.isAssignableFrom(ResponseExceptionMapper.class)) { - register(o); - } - } + // local + for (Class aClass : classes) { + if (aClass.isAssignableFrom(ResponseExceptionMapper.class)) { + register(o); + } + } - // other - this.builderDelegate.register(o, classes); - return this; + // other + this.builderDelegate.register(o, classes); + return this; } @Override public RestClientBuilder register(Object o, Map, Integer> map) { - if (o instanceof ResponseExceptionMapper) { + if (o instanceof ResponseExceptionMapper) { - //local - ResponseExceptionMapper mapper = (ResponseExceptionMapper)o; - HashMap, Integer> contracts = new HashMap<>(); - contracts.put(ResponseExceptionMapper.class, map.get(ResponseExceptionMapper.class)); - registerLocalProviderInstance(mapper, contracts); + //local + ResponseExceptionMapper mapper = (ResponseExceptionMapper)o; + HashMap, Integer> contracts = new HashMap<>(); + contracts.put(ResponseExceptionMapper.class, map.get(ResponseExceptionMapper.class)); + registerLocalProviderInstance(mapper, contracts); - // other - this.builderDelegate.register(o, map); + // other + this.builderDelegate.register(o, map); - } else { - this.builderDelegate.register(o, map); - } + } else { + this.builderDelegate.register(o, map); + } - return this; + return this; } public Set getLocalProviderInstances() { - return localProviderInstances; + return localProviderInstances; } public void registerLocalProviderInstance(Object provider, Map, Integer> contracts) { - for (Object registered : getLocalProviderInstances()) { - if (registered == provider) { - LOG.infov("Provider already registered {0}", provider.getClass().getName()); - return; - } - } - - localProviderInstances.add(provider); - configurationWrapper.registerLocalContract(provider.getClass(), contracts); + for (Object registered : getLocalProviderInstances()) { + if (registered == provider) { + LOG.infov("Provider already registered {0}", provider.getClass().getName()); + return; + } + } + + localProviderInstances.add(provider); + configurationWrapper.registerLocalContract(provider.getClass(), contracts); } private final ResteasyClientBuilder builderDelegate; diff --git a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilderResolver.java b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilderResolver.java index db67dd3558e..d5249a4a572 100644 --- a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilderResolver.java +++ b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/MicroprofileClientBuilderResolver.java @@ -7,9 +7,8 @@ * Created by hbraun on 15.01.18. */ public class MicroprofileClientBuilderResolver extends RestClientBuilderResolver { - @Override - public RestClientBuilder newBuilder() { - return new MicroprofileClientBuilder(); - } + @Override + public RestClientBuilder newBuilder() { + return new MicroprofileClientBuilder(); + } } - diff --git a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/PartialResponse.java b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/PartialResponse.java index 5d944951166..c49d0bbe52d 100644 --- a/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/PartialResponse.java +++ b/resteasy-client-microprofile/src/main/java/org/jboss/resteasy/client/microprofile/PartialResponse.java @@ -141,9 +141,9 @@ public synchronized void close() { try { responseContext.getEntityStream().close(); - } catch (Throwable e) { + } catch (Throwable e) { // ignore - } + } } @Override diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder4.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder4.java index 348f7df5951..468a633a3ed 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder4.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder4.java @@ -39,114 +39,112 @@ public ClientHttpEngineBuilder resteasyClientBuilder(ResteasyClientBuilder reste @Override public ClientHttpEngine build() - { - X509HostnameVerifier verifier = null; - if (that.verifier != null) { - verifier = new VerifierWrapper(that.verifier); - } - else - { - switch (that.policy) - { - case ANY: - verifier = new AllowAllHostnameVerifier(); - break; - case WILDCARD: - verifier = new BrowserCompatHostnameVerifier(); - break; - case STRICT: - verifier = new StrictHostnameVerifier(); - break; - } - } - try - { - SSLSocketFactory sslsf = null; - SSLContext theContext = that.sslContext; - if (that.disableTrustManager) - { - theContext = SSLContext.getInstance("SSL"); - theContext.init(null, new TrustManager[]{new PassthroughTrustManager()}, - new SecureRandom()); - verifier = new AllowAllHostnameVerifier(); - sslsf = new SSLSocketFactory(theContext, verifier); - } - else if (theContext != null) - { - sslsf = new SSLSocketFactory(theContext, verifier) { - @Override - protected void prepareSocket(SSLSocket socket) throws IOException - { - that.prepareSocketForSni(socket); - } - }; - } - else if (that.clientKeyStore != null || that.truststore != null) - { - sslsf = new SSLSocketFactory(SSLSocketFactory.TLS, - that.clientKeyStore, that.clientPrivateKeyPassword, - that.truststore, null, verifier) { - @Override - protected void prepareSocket(SSLSocket socket) throws IOException - { - that.prepareSocketForSni(socket); - } - }; - } - else - { - final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS); - tlsContext.init(null, null, null); - sslsf = new SSLSocketFactory(tlsContext, verifier); - } - SchemeRegistry registry = new SchemeRegistry(); - registry.register( - new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); - Scheme httpsScheme = new Scheme("https", 443, sslsf); - registry.register(httpsScheme); - ClientConnectionManager cm = null; - if (that.connectionPoolSize > 0) - { - PoolingClientConnectionManager tcm = - new PoolingClientConnectionManager(registry, + { + X509HostnameVerifier verifier = null; + if (that.verifier != null) { + verifier = new VerifierWrapper(that.verifier); + } + else + { + switch (that.policy) + { + case ANY: + verifier = new AllowAllHostnameVerifier(); + break; + case WILDCARD: + verifier = new BrowserCompatHostnameVerifier(); + break; + case STRICT: + verifier = new StrictHostnameVerifier(); + break; + } + } + try + { + SSLSocketFactory sslsf = null; + SSLContext theContext = that.sslContext; + if (that.disableTrustManager) + { + theContext = SSLContext.getInstance("SSL"); + theContext.init(null, new TrustManager[]{new PassthroughTrustManager()}, + new SecureRandom()); + verifier = new AllowAllHostnameVerifier(); + sslsf = new SSLSocketFactory(theContext, verifier); + } + else if (theContext != null) + { + sslsf = new SSLSocketFactory(theContext, verifier) { + @Override + protected void prepareSocket(SSLSocket socket) throws IOException + { + that.prepareSocketForSni(socket); + } + }; + } + else if (that.clientKeyStore != null || that.truststore != null) + { + sslsf = new SSLSocketFactory(SSLSocketFactory.TLS, + that.clientKeyStore, that.clientPrivateKeyPassword, + that.truststore, null, verifier) { + @Override + protected void prepareSocket(SSLSocket socket) throws IOException + { + that.prepareSocketForSni(socket); + } + }; + } + else + { + final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS); + tlsContext.init(null, null, null); + sslsf = new SSLSocketFactory(tlsContext, verifier); + } + SchemeRegistry registry = new SchemeRegistry(); + registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); + Scheme httpsScheme = new Scheme("https", 443, sslsf); + registry.register(httpsScheme); + ClientConnectionManager cm = null; + if (that.connectionPoolSize > 0) + { + PoolingClientConnectionManager tcm = + new PoolingClientConnectionManager(registry, that.connectionTTL, that.connectionTTLUnit); - tcm.setMaxTotal(that.connectionPoolSize); - if (that.maxPooledPerRoute == 0) that.maxPooledPerRoute = that.connectionPoolSize; - tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute); - cm = tcm; + tcm.setMaxTotal(that.connectionPoolSize); + if (that.maxPooledPerRoute == 0) that.maxPooledPerRoute = that.connectionPoolSize; + tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute); + cm = tcm; - } - else - { - cm = new BasicClientConnectionManager(registry); - } - BasicHttpParams params = new BasicHttpParams(); - if (that.socketTimeout > -1) - { - HttpConnectionParams.setSoTimeout(params, - (int) that.socketTimeoutUnits.toMillis(that.socketTimeout)); + } + else + { + cm = new BasicClientConnectionManager(registry); + } + BasicHttpParams params = new BasicHttpParams(); + if (that.socketTimeout > -1) + { + HttpConnectionParams.setSoTimeout(params, + (int) that.socketTimeoutUnits.toMillis(that.socketTimeout)); - } - if (that.establishConnectionTimeout > -1) - { - HttpConnectionParams.setConnectionTimeout(params, - (int)that.establishConnectionTimeoutUnits.toMillis( - that.establishConnectionTimeout)); - } - if (that.connectionCheckoutTimeoutMs > -1) - { - HttpClientParams.setConnectionManagerTimeout(params, - that.connectionCheckoutTimeoutMs); - } - params.setParameter(ConnRoutePNames.DEFAULT_PROXY, that.defaultProxy); + } + if (that.establishConnectionTimeout > -1) + { + HttpConnectionParams.setConnectionTimeout(params, + (int)that.establishConnectionTimeoutUnits.toMillis( + that.establishConnectionTimeout)); + } + if (that.connectionCheckoutTimeoutMs > -1) + { + HttpClientParams.setConnectionManagerTimeout(params, that.connectionCheckoutTimeoutMs); + } + params.setParameter(ConnRoutePNames.DEFAULT_PROXY, that.defaultProxy); - return createEngine(cm, params, verifier, theContext, that.responseBufferSize); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } + return createEngine(cm, params, verifier, theContext, that.responseBufferSize); + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } protected ClientHttpEngine createEngine(ClientConnectionManager cm, BasicHttpParams params, X509HostnameVerifier verifier, SSLContext theContext, int responseBufferSize) diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder43.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder43.java index ac977d57f4b..f9f44381884 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder43.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ClientHttpEngineBuilder43.java @@ -47,160 +47,160 @@ public ClientHttpEngineBuilder resteasyClientBuilder(ResteasyClientBuilder reste @Override public ClientHttpEngine build() - { - HostnameVerifier verifier = null; - if (that.verifier != null) { - verifier = new VerifierWrapper(that.verifier); - } - else - { - switch (that.policy) - { - case ANY: - verifier = new NoopHostnameVerifier(); - break; - case WILDCARD: - verifier = new DefaultHostnameVerifier(); - break; - case STRICT: - verifier = new DefaultHostnameVerifier(); - break; - } - } - try - { - SSLConnectionSocketFactory sslsf = null; - SSLContext theContext = that.sslContext; - if (that.disableTrustManager) - { - theContext = SSLContext.getInstance("SSL"); - theContext.init(null, new TrustManager[]{new PassthroughTrustManager()}, - new SecureRandom()); - verifier = new NoopHostnameVerifier(); - sslsf = new SSLConnectionSocketFactory(theContext, verifier); - } - else if (theContext != null) - { - sslsf = new SSLConnectionSocketFactory(theContext, verifier) { - @Override - protected void prepareSocket(SSLSocket socket) throws IOException - { - if(!that.sniHostNames.isEmpty()) { - List sniNames = new ArrayList<>(that.sniHostNames.size()); - for(String sniHostName : that.sniHostNames) { - sniNames.add(new SNIHostName(sniHostName)); - } + { + HostnameVerifier verifier = null; + if (that.verifier != null) { + verifier = new VerifierWrapper(that.verifier); + } + else + { + switch (that.policy) + { + case ANY: + verifier = new NoopHostnameVerifier(); + break; + case WILDCARD: + verifier = new DefaultHostnameVerifier(); + break; + case STRICT: + verifier = new DefaultHostnameVerifier(); + break; + } + } + try + { + SSLConnectionSocketFactory sslsf = null; + SSLContext theContext = that.sslContext; + if (that.disableTrustManager) + { + theContext = SSLContext.getInstance("SSL"); + theContext.init(null, new TrustManager[]{new PassthroughTrustManager()}, + new SecureRandom()); + verifier = new NoopHostnameVerifier(); + sslsf = new SSLConnectionSocketFactory(theContext, verifier); + } + else if (theContext != null) + { + sslsf = new SSLConnectionSocketFactory(theContext, verifier) { + @Override + protected void prepareSocket(SSLSocket socket) throws IOException + { + if(!that.sniHostNames.isEmpty()) { + List sniNames = new ArrayList<>(that.sniHostNames.size()); + for(String sniHostName : that.sniHostNames) { + sniNames.add(new SNIHostName(sniHostName)); + } - SSLParameters sslParameters = socket.getSSLParameters(); - sslParameters.setServerNames(sniNames); - socket.setSSLParameters(sslParameters); - } - } - }; - } - else if (that.clientKeyStore != null || that.truststore != null) - { - SSLContext ctx = SSLContexts.custom() - .useProtocol(SSLConnectionSocketFactory.TLS) - .setSecureRandom(null) - .loadKeyMaterial(that.clientKeyStore, + SSLParameters sslParameters = socket.getSSLParameters(); + sslParameters.setServerNames(sniNames); + socket.setSSLParameters(sslParameters); + } + } + }; + } + else if (that.clientKeyStore != null || that.truststore != null) + { + SSLContext ctx = SSLContexts.custom() + .useProtocol(SSLConnectionSocketFactory.TLS) + .setSecureRandom(null) + .loadKeyMaterial(that.clientKeyStore, that.clientPrivateKeyPassword != null ? that.clientPrivateKeyPassword.toCharArray() : null) - .loadTrustMaterial(that.truststore, TrustSelfSignedStrategy.INSTANCE) - .build(); - sslsf = new SSLConnectionSocketFactory(ctx, verifier) { - @Override - protected void prepareSocket(SSLSocket socket) throws IOException - { - that.prepareSocketForSni(socket); - } - }; - } - else - { - final SSLContext tlsContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS); - tlsContext.init(null, null, null); - sslsf = new SSLConnectionSocketFactory(tlsContext, verifier); - } + .loadTrustMaterial(that.truststore, TrustSelfSignedStrategy.INSTANCE) + .build(); + sslsf = new SSLConnectionSocketFactory(ctx, verifier) { + @Override + protected void prepareSocket(SSLSocket socket) throws IOException + { + that.prepareSocketForSni(socket); + } + }; + } + else + { + final SSLContext tlsContext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS); + tlsContext.init(null, null, null); + sslsf = new SSLConnectionSocketFactory(tlsContext, verifier); + } - final Registry registry = RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslsf) - .build(); + final Registry registry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslsf) + .build(); - HttpClientConnectionManager cm = null; - if (that.connectionPoolSize > 0) - { - PoolingHttpClientConnectionManager tcm = new PoolingHttpClientConnectionManager( - registry, null, null ,null, that.connectionTTL, that.connectionTTLUnit); - tcm.setMaxTotal(that.connectionPoolSize); - if (that.maxPooledPerRoute == 0) { - that.maxPooledPerRoute = that.connectionPoolSize; - } - tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute); - cm = tcm; - - } - else - { - cm = new BasicHttpClientConnectionManager(registry); + HttpClientConnectionManager cm = null; + if (that.connectionPoolSize > 0) + { + PoolingHttpClientConnectionManager tcm = new PoolingHttpClientConnectionManager( + registry, null, null ,null, that.connectionTTL, that.connectionTTLUnit); + tcm.setMaxTotal(that.connectionPoolSize); + if (that.maxPooledPerRoute == 0) { + that.maxPooledPerRoute = that.connectionPoolSize; } + tcm.setDefaultMaxPerRoute(that.maxPooledPerRoute); + cm = tcm; - RequestConfig.Builder rcBuilder = RequestConfig.custom(); - if (that.socketTimeout > -1) - { - rcBuilder.setSocketTimeout((int) that.socketTimeoutUnits.toMillis(that.socketTimeout)); - } - if (that.establishConnectionTimeout > -1) - { - rcBuilder.setConnectTimeout((int)that.establishConnectionTimeoutUnits.toMillis(that.establishConnectionTimeout)); - } - if (that.connectionCheckoutTimeoutMs > -1) - { - rcBuilder.setConnectionRequestTimeout(that.connectionCheckoutTimeoutMs); - } + } + else + { + cm = new BasicHttpClientConnectionManager(registry); + } - return createEngine(cm, rcBuilder, that.defaultProxy, that.responseBufferSize, verifier, theContext); - } - catch (Exception e) - { - throw new RuntimeException(e); - } - } + RequestConfig.Builder rcBuilder = RequestConfig.custom(); + if (that.socketTimeout > -1) + { + rcBuilder.setSocketTimeout((int) that.socketTimeoutUnits.toMillis(that.socketTimeout)); + } + if (that.establishConnectionTimeout > -1) + { + rcBuilder.setConnectTimeout((int)that.establishConnectionTimeoutUnits.toMillis(that.establishConnectionTimeout)); + } + if (that.connectionCheckoutTimeoutMs > -1) + { + rcBuilder.setConnectionRequestTimeout(that.connectionCheckoutTimeoutMs); + } + + return createEngine(cm, rcBuilder, that.defaultProxy, that.responseBufferSize, verifier, theContext); + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } protected ClientHttpEngine createEngine(final HttpClientConnectionManager cm, final RequestConfig.Builder rcBuilder, final HttpHost defaultProxy, final int responseBufferSize, final HostnameVerifier verifier, final SSLContext theContext) { - final HttpClient httpClient; - if (System.getSecurityManager() == null) - { - httpClient = HttpClientBuilder.create() + final HttpClient httpClient; + if (System.getSecurityManager() == null) + { + httpClient = HttpClientBuilder.create() .setConnectionManager(cm) .setDefaultRequestConfig(rcBuilder.build()) .setProxy(defaultProxy) .disableContentCompression().build(); - } - else - { - httpClient = AccessController.doPrivileged(new PrivilegedAction() - { - @Override - public HttpClient run() - { - return HttpClientBuilder.create() - .setConnectionManager(cm) - .setDefaultRequestConfig(rcBuilder.build()) - .setProxy(defaultProxy) - .disableContentCompression().build(); - } - }); - } + } + else + { + httpClient = AccessController.doPrivileged(new PrivilegedAction() + { + @Override + public HttpClient run() + { + return HttpClientBuilder.create() + .setConnectionManager(cm) + .setDefaultRequestConfig(rcBuilder.build()) + .setProxy(defaultProxy) + .disableContentCompression().build(); + } + }); + } - ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient, + ApacheHttpClient43Engine engine = (ApacheHttpClient43Engine) ApacheHttpClient4EngineFactory.create(httpClient, true); engine.setResponseBufferSize(responseBufferSize); engine.setHostnameVerifier(verifier); // this may be null. We can't really support this with Apache Client. engine.setSslContext(theContext); return engine; - } + } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/HTTPClientVersionCheck.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/HTTPClientVersionCheck.java index 737d7fee8e1..634d3edc253 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/HTTPClientVersionCheck.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/HTTPClientVersionCheck.java @@ -12,23 +12,23 @@ * Date: 5/4/17 */ public class HTTPClientVersionCheck { - private static final boolean useOldHTTPClient = Boolean.getBoolean("org.jboss.resteasy.client.useOldHTTPClient"); - private static final boolean newHTTPClientAvailable; - static { - boolean res = true; - try { - Class.forName(ClientHttpEngineBuilder43.class.getName()); - } catch (Throwable t) { - res = false; - } - newHTTPClientAvailable = res; - } + private static final boolean useOldHTTPClient = Boolean.getBoolean("org.jboss.resteasy.client.useOldHTTPClient"); + private static final boolean newHTTPClientAvailable; + static { + boolean res = true; + try { + Class.forName(ClientHttpEngineBuilder43.class.getName()); + } catch (Throwable t) { + res = false; + } + newHTTPClientAvailable = res; + } - static public boolean isUseOldHTTPClient () { - return useOldHTTPClient; - } + static public boolean isUseOldHTTPClient () { + return useOldHTTPClient; + } - static public boolean isNewHTTPClientAvailable() { - return newHTTPClientAvailable; - } + static public boolean isNewHTTPClientAvailable() { + return newHTTPClientAvailable; + } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyBuilder.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyBuilder.java index 49f28536e45..77b23e9070a 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyBuilder.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyBuilder.java @@ -24,20 +24,20 @@ public class ProxyBuilder { private static final Class[] cClassArgArray = {Class.class}; - private final Class iface; - private final ResteasyWebTarget webTarget; - private ClassLoader loader; - private MediaType serverConsumes; - private MediaType serverProduces; + private final Class iface; + private final ResteasyWebTarget webTarget; + private ClassLoader loader; + private MediaType serverConsumes; + private MediaType serverProduces; public static ProxyBuilder builder(Class iface, WebTarget webTarget) { return new ProxyBuilder(iface, (ResteasyWebTarget)webTarget); } - @SuppressWarnings("unchecked") - public static T proxy(final Class iface, WebTarget base, final ProxyConfig config) - { + @SuppressWarnings("unchecked") + public static T proxy(final Class iface, WebTarget base, final ProxyConfig config) + { if (iface.isAnnotationPresent(Path.class)) { Path path = iface.getAnnotation(Path.class); @@ -46,14 +46,14 @@ public static T proxy(final Class iface, WebTarget base, final ProxyConfi base = base.path(path.value()); } } - HashMap methodMap = new HashMap(); - for (Method method : iface.getMethods()) - { + HashMap methodMap = new HashMap(); + for (Method method : iface.getMethods()) + { // ignore the as method to allow declaration in client interfaces - if ("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), cClassArgArray)) - { - continue; - } + if ("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), cClassArgArray)) + { + continue; + } MethodInvoker invoker; Set httpMethods = IsHttpMethod.getHttpMethods(method); if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) @@ -69,21 +69,21 @@ else if (httpMethods == null) { invoker = createClientInvoker(iface, method, (ResteasyWebTarget)base, config); } methodMap.put(method, invoker); - } + } - Class[] intfs = - { - iface, ResteasyClientProxy.class - }; + Class[] intfs = + { + iface, ResteasyClientProxy.class + }; - ClientProxy clientProxy = new ClientProxy(methodMap, base, config); - // this is done so that equals and hashCode work ok. Adding the proxy to a - // Collection will cause equals and hashCode to be invoked. The Spring - // infrastructure had some problems without this. - clientProxy.setClazz(iface); + ClientProxy clientProxy = new ClientProxy(methodMap, base, config); + // this is done so that equals and hashCode work ok. Adding the proxy to a + // Collection will cause equals and hashCode to be invoked. The Spring + // infrastructure had some problems without this. + clientProxy.setClazz(iface); - return (T) Proxy.newProxyInstance(config.getLoader(), intfs, clientProxy); - } + return (T) Proxy.newProxyInstance(config.getLoader(), intfs, clientProxy); + } private static ClientInvoker createClientInvoker(Class clazz, Method method, ResteasyWebTarget base, ProxyConfig config) { @@ -101,40 +101,40 @@ private ProxyBuilder(Class iface, ResteasyWebTarget webTarget) { if (System.getSecurityManager() == null) { - this.loader = Thread.currentThread().getContextClassLoader(); + this.loader = Thread.currentThread().getContextClassLoader(); } else { - this.loader = AccessController.doPrivileged(new PrivilegedAction() - { - @Override - public ClassLoader run() - { - return Thread.currentThread().getContextClassLoader(); - } - }); + this.loader = AccessController.doPrivileged(new PrivilegedAction() + { + @Override + public ClassLoader run() + { + return Thread.currentThread().getContextClassLoader(); + } + }); } this.iface = iface; this.webTarget = webTarget; } public ProxyBuilder classloader(ClassLoader cl) - { - this.loader = cl; - return this; - } - - public ProxyBuilder defaultProduces(MediaType type) - { - this.serverProduces = type; - return this; - } - - public ProxyBuilder defaultConsumes(MediaType type) - { - this.serverConsumes = type; - return this; - } + { + this.loader = cl; + return this; + } + + public ProxyBuilder defaultProduces(MediaType type) + { + this.serverProduces = type; + return this; + } + + public ProxyBuilder defaultConsumes(MediaType type) + { + this.serverConsumes = type; + return this; + } public ProxyBuilder defaultProduces(String type) { @@ -147,10 +147,10 @@ public ProxyBuilder defaultConsumes(String type) this.serverConsumes = MediaType.valueOf(type); return this; } - public T build() - { + public T build() + { return proxy(iface, webTarget, new ProxyConfig(loader, serverConsumes, serverProduces)); - } + } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyConfig.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyConfig.java index 07cd5d2da54..517885c0f42 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyConfig.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyConfig.java @@ -4,30 +4,30 @@ public class ProxyConfig { - private final ClassLoader loader; - private final MediaType defaultConsumes; - private final MediaType defaultProduces; + private final ClassLoader loader; + private final MediaType defaultConsumes; + private final MediaType defaultProduces; - public ProxyConfig(ClassLoader loader, MediaType defaultConsumes, MediaType defaultProduces) - { - super(); - this.loader = loader; - this.defaultConsumes = defaultConsumes; - this.defaultProduces = defaultProduces; - } + public ProxyConfig(ClassLoader loader, MediaType defaultConsumes, MediaType defaultProduces) + { + super(); + this.loader = loader; + this.defaultConsumes = defaultConsumes; + this.defaultProduces = defaultProduces; + } - public ClassLoader getLoader() - { - return loader; - } + public ClassLoader getLoader() + { + return loader; + } - public MediaType getDefaultConsumes() - { - return defaultConsumes; - } + public MediaType getDefaultConsumes() + { + return defaultConsumes; + } - public MediaType getDefaultProduces() - { - return defaultProduces; - } + public MediaType getDefaultProduces() + { + return defaultProduces; + } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ResteasyClientBuilder.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ResteasyClientBuilder.java index fd99cd4adb7..b82facf0885 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ResteasyClientBuilder.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ResteasyClientBuilder.java @@ -196,8 +196,8 @@ public ResteasyClientBuilder maxPooledPerRoute(int maxPooledPerRoute) */ public ResteasyClientBuilder connectionCheckoutTimeout(long timeout, TimeUnit unit) { - this.connectionCheckoutTimeoutMs = (int) TimeUnit.MILLISECONDS.convert(timeout, unit); - return this; + this.connectionCheckoutTimeoutMs = (int) TimeUnit.MILLISECONDS.convert(timeout, unit); + return this; } /** @@ -305,12 +305,12 @@ public ResteasyClientBuilder property(String name, Object value) return this; } - /** - * Adds a TLS/SSL SNI Host Name for authentication. - * - * @param sniHostNames host names - * @return an updated client builder instance - */ + /** + * Adds a TLS/SSL SNI Host Name for authentication. + * + * @param sniHostNames host names + * @return an updated client builder instance + */ public ResteasyClientBuilder sniHostNames(String... sniHostNames) { this.sniHostNames.addAll(Arrays.asList(sniHostNames)); return this; @@ -350,7 +350,7 @@ public ResteasyClientBuilder defaultProxy(String hostname, int port) public ResteasyClientBuilder defaultProxy(String hostname, int port, final String scheme) { this.defaultProxy = new HttpHost(hostname, port, scheme); - return this; + return this; } protected ResteasyProviderFactory getProviderFactory() diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/VerifierWrapper.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/VerifierWrapper.java index cd4a8c7ff28..027ef9242c0 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/VerifierWrapper.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/VerifierWrapper.java @@ -11,34 +11,34 @@ public class VerifierWrapper implements X509HostnameVerifier { - protected HostnameVerifier verifier; + protected HostnameVerifier verifier; - VerifierWrapper(HostnameVerifier verifier) - { - this.verifier = verifier; - } + VerifierWrapper(HostnameVerifier verifier) + { + this.verifier = verifier; + } - @Override - public void verify(String host, SSLSocket ssl) throws IOException - { - if (!verifier.verify(host, ssl.getSession())) throw new SSLException(Messages.MESSAGES.hostnameVerificationFailure()); - } + @Override + public void verify(String host, SSLSocket ssl) throws IOException + { + if (!verifier.verify(host, ssl.getSession())) throw new SSLException(Messages.MESSAGES.hostnameVerificationFailure()); + } - @Override - public void verify(String host, X509Certificate cert) throws SSLException - { - throw new SSLException(Messages.MESSAGES.verificationPathNotImplemented()); - } + @Override + public void verify(String host, X509Certificate cert) throws SSLException + { + throw new SSLException(Messages.MESSAGES.verificationPathNotImplemented()); + } - @Override - public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException - { - throw new SSLException(Messages.MESSAGES.verificationPathNotImplemented()); - } + @Override + public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException + { + throw new SSLException(Messages.MESSAGES.verificationPathNotImplemented()); + } - @Override - public boolean verify(String s, SSLSession sslSession) - { - return verifier.verify(s, sslSession); - } + @Override + public boolean verify(String s, SSLSession sslSession) + { + return verifier.verify(s, sslSession); + } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/CacheInterceptor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/CacheInterceptor.java index 443e7d066b2..2c0ecd4eb59 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/CacheInterceptor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/CacheInterceptor.java @@ -207,7 +207,7 @@ else if (exp != null) MediaType mediaType = MediaType.valueOf(contentType); final BrowserCache.Entry entry = cache.put(request.getUri().toString(), mediaType, - response.getHeaders(), cached, expires, etag, lastModified); + response.getHeaders(), cached, expires, etag, lastModified); response.setEntityStream(new ByteArrayInputStream(cached)); } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/LightweightBrowserCache.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/LightweightBrowserCache.java index 03b96515b7c..5c049ba8588 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/LightweightBrowserCache.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/LightweightBrowserCache.java @@ -78,8 +78,8 @@ public Entry get(String key, MediaType accept) } public Entry put(String key, MediaType mediaType, - MultivaluedMap headers, byte[] cached, int expires, - String etag, String lastModified) + MultivaluedMap headers, byte[] cached, int expires, + String etag, String lastModified) { Entry previousValue = internalCache.get(key, mediaType); diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/MapCache.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/MapCache.java index c6db2a2c6f8..42d64c15311 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/MapCache.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/cache/MapCache.java @@ -95,8 +95,8 @@ public Entry put(CacheEntry cacheEntry) } public Entry put(String key, MediaType mediaType, - MultivaluedMap headers, byte[] cached, int expires, - String etag, String lastModified) + MultivaluedMap headers, byte[] cached, int expires, + String etag, String lastModified) { return put(new CacheEntry(key, headers, cached, expires, etag, lastModified, mediaType)); } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpAsyncClient4Engine.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpAsyncClient4Engine.java index bd1535305e0..8b8f4d8511b 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpAsyncClient4Engine.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpAsyncClient4Engine.java @@ -201,7 +201,7 @@ private static class StreamingResponseConsumer implements HttpAsyncResponseCo public synchronized Throwable fillInStackTrace() { //do nothing and return return this; - } + } }; private ClientConfiguration configuration; @@ -653,7 +653,7 @@ public synchronized InputStream getInputStream() @Override public synchronized void releaseConnection() throws IOException { - releaseConnection(false); + releaseConnection(false); } @Override diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient43Engine.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient43Engine.java index 88bbe274d6f..125c85a71ba 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient43Engine.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient43Engine.java @@ -19,102 +19,102 @@ public class ApacheHttpClient43Engine extends ApacheHttpClient4Engine { - public ApacheHttpClient43Engine() - { - super(); - } + public ApacheHttpClient43Engine() + { + super(); + } - public ApacheHttpClient43Engine(final HttpHost defaultProxy) { - super(defaultProxy); - } + public ApacheHttpClient43Engine(final HttpHost defaultProxy) { + super(defaultProxy); + } - public ApacheHttpClient43Engine(final HttpClient httpClient) { - super(httpClient); - } + public ApacheHttpClient43Engine(final HttpClient httpClient) { + super(httpClient); + } - public ApacheHttpClient43Engine(final HttpClient httpClient, final boolean closeHttpClient) - { - super(httpClient, closeHttpClient); - } + public ApacheHttpClient43Engine(final HttpClient httpClient, final boolean closeHttpClient) + { + super(httpClient, closeHttpClient); + } - /** - * Creates a client engine instance using the specified {@link org.apache.http.client.HttpClient} - * and {@link org.apache.http.protocol.HttpContext} instances. - * Note that the same instance of httpContext is passed to the engine, which may store thread unsafe - * attributes in it. It is hence recommended to override the HttpClient - *
execute(HttpUriRequest request, HttpContext context)
method to perform a deep - * copy of the context before executing the request. - * - * @param httpClient The http client - * @param httpContext The context to be used for executing requests - */ - @Deprecated - public ApacheHttpClient43Engine(final HttpClient httpClient, final HttpContext httpContext) - { - super(httpClient, httpContext); - } + /** + * Creates a client engine instance using the specified {@link org.apache.http.client.HttpClient} + * and {@link org.apache.http.protocol.HttpContext} instances. + * Note that the same instance of httpContext is passed to the engine, which may store thread unsafe + * attributes in it. It is hence recommended to override the HttpClient + *
execute(HttpUriRequest request, HttpContext context)
method to perform a deep + * copy of the context before executing the request. + * + * @param httpClient The http client + * @param httpContext The context to be used for executing requests + */ + @Deprecated + public ApacheHttpClient43Engine(final HttpClient httpClient, final HttpContext httpContext) + { + super(httpClient, httpContext); + } - public ApacheHttpClient43Engine(HttpClient httpClient, HttpContextProvider httpContextProvider) - { - this.httpClient = httpClient; - this.httpContextProvider = httpContextProvider; - } + public ApacheHttpClient43Engine(HttpClient httpClient, HttpContextProvider httpContextProvider) + { + this.httpClient = httpClient; + this.httpContextProvider = httpContextProvider; + } - @Override - protected HttpClient createDefaultHttpClient() - { - final HttpClientBuilder builder = HttpClientBuilder.create(); - RequestConfig.Builder requestBuilder = RequestConfig.custom(); - if(defaultProxy != null) - { - requestBuilder.setProxy(defaultProxy); - } - builder.disableContentCompression(); - builder.setDefaultRequestConfig(requestBuilder.build()); - return builder.build(); - } + @Override + protected HttpClient createDefaultHttpClient() + { + final HttpClientBuilder builder = HttpClientBuilder.create(); + RequestConfig.Builder requestBuilder = RequestConfig.custom(); + if(defaultProxy != null) + { + requestBuilder.setProxy(defaultProxy); + } + builder.disableContentCompression(); + builder.setDefaultRequestConfig(requestBuilder.build()); + return builder.build(); + } - @Override - public HttpHost getDefaultProxy() - { - Configurable clientConfiguration = (Configurable) httpClient; - return clientConfiguration.getConfig().getProxy(); - } + @Override + public HttpHost getDefaultProxy() + { + Configurable clientConfiguration = (Configurable) httpClient; + return clientConfiguration.getConfig().getProxy(); + } - @Override - protected void setRedirectRequired(final ClientInvocation request, final HttpRequestBase httpMethod) - { - RequestConfig.Builder requestBuilder = RequestConfig.copy(getCurrentConfiguration(request, httpMethod)); - requestBuilder.setRedirectsEnabled(true); - httpMethod.setConfig(requestBuilder.build()); - } + @Override + protected void setRedirectRequired(final ClientInvocation request, final HttpRequestBase httpMethod) + { + RequestConfig.Builder requestBuilder = RequestConfig.copy(getCurrentConfiguration(request, httpMethod)); + requestBuilder.setRedirectsEnabled(true); + httpMethod.setConfig(requestBuilder.build()); + } - @Override - protected void setRedirectNotRequired(final ClientInvocation request, final HttpRequestBase httpMethod) - { - RequestConfig.Builder requestBuilder = RequestConfig.copy(getCurrentConfiguration(request, httpMethod)); - requestBuilder.setRedirectsEnabled(false); - httpMethod.setConfig(requestBuilder.build()); - } + @Override + protected void setRedirectNotRequired(final ClientInvocation request, final HttpRequestBase httpMethod) + { + RequestConfig.Builder requestBuilder = RequestConfig.copy(getCurrentConfiguration(request, httpMethod)); + requestBuilder.setRedirectsEnabled(false); + httpMethod.setConfig(requestBuilder.build()); + } - private RequestConfig getCurrentConfiguration(final ClientInvocation request, + private RequestConfig getCurrentConfiguration(final ClientInvocation request, final HttpRequestBase httpMethod) - { - RequestConfig baseConfig; - if (httpMethod != null && httpMethod.getConfig() != null) - { - baseConfig = httpMethod.getConfig(); - } - else - { - ApacheHttpClient43Engine engine = - ((ApacheHttpClient43Engine)request.getClient().httpEngine()); - baseConfig = ((Configurable)engine.getHttpClient()).getConfig(); - if (baseConfig == null) { - Configurable clientConfiguration = (Configurable) httpClient; - baseConfig = clientConfiguration.getConfig(); - } - } - return baseConfig; - } + { + RequestConfig baseConfig; + if (httpMethod != null && httpMethod.getConfig() != null) + { + baseConfig = httpMethod.getConfig(); + } + else + { + ApacheHttpClient43Engine engine = + ((ApacheHttpClient43Engine)request.getClient().httpEngine()); + baseConfig = ((Configurable)engine.getHttpClient()).getConfig(); + if (baseConfig == null) { + Configurable clientConfiguration = (Configurable) httpClient; + baseConfig = clientConfiguration.getConfig(); + } + } + return baseConfig; + } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient4Engine.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient4Engine.java index 7e7cc5b11a5..fa3a1366707 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient4Engine.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/ApacheHttpClient4Engine.java @@ -158,7 +158,7 @@ public ApacheHttpClient4Engine(HttpClient httpClient, boolean closeHttpClient) * attributes in it. It is hence recommended to override the HttpClient *
execute(HttpUriRequest request, HttpContext context)
method to perform a deep * copy of the context before executing the request. - * + * * @param httpClient The http client * @param httpContext The context to be used for executing requests */ @@ -272,11 +272,11 @@ public void setHostnameVerifier(HostnameVerifier hostnameVerifier) public HttpHost getDefaultProxy() { - return (HttpHost) httpClient.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY); + return (HttpHost) httpClient.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY); } public static CaseInsensitiveMap extractHeaders( - HttpResponse response) + HttpResponse response) { final CaseInsensitiveMap headers = new CaseInsensitiveMap(); @@ -495,7 +495,7 @@ protected void loadHttpMethod(final ClientInvocation request, HttpRequestBase ht } else { - setRedirectNotRequired(request,httpMethod); + setRedirectNotRequired(request,httpMethod); } if (request.getEntity() != null) @@ -660,7 +660,7 @@ protected HttpEntity buildEntity(final ClientInvocation request) throws IOExcept private DeferredFileOutputStream writeRequestBodyToOutputStream(final ClientInvocation request) throws IOException { DeferredFileOutputStream memoryManagedOutStream = - new DeferredFileOutputStream(this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(), + new DeferredFileOutputStream(this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(), getTempfilePrefix(), ".tmp", this.fileUploadTempFileDir); request.getDelegatingOutputStream().setDelegate(memoryManagedOutStream); request.writeRequestBody(request.getEntityStream()); diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/URLConnectionEngine.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/URLConnectionEngine.java index 0589f07e024..bb706e72e57 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/URLConnectionEngine.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/URLConnectionEngine.java @@ -26,33 +26,33 @@ public class URLConnectionEngine implements ClientHttpEngine { - protected SSLContext sslContext; - protected HostnameVerifier hostnameVerifier; + protected SSLContext sslContext; + protected HostnameVerifier hostnameVerifier; - /** - * {@inheritDoc} - */ - @Override - public ClientResponse invoke(ClientInvocation request) - { + /** + * {@inheritDoc} + */ + @Override + public ClientResponse invoke(ClientInvocation request) + { - final HttpURLConnection connection; + final HttpURLConnection connection; - final int status; - try - { + final int status; + try + { - connection = createConnection(request); + connection = createConnection(request); - executeRequest(request, connection); + executeRequest(request, connection); - status = connection.getResponseCode(); - } catch (IOException e) - { - throw new ProcessingException(Messages.MESSAGES.unableToInvokeRequest(), e); - } + status = connection.getResponseCode(); + } catch (IOException e) + { + throw new ProcessingException(Messages.MESSAGES.unableToInvokeRequest(), e); + } - //Creating response with stream content + //Creating response with stream content ClientResponse response = new ClientResponse(request.getClientConfiguration()) { private InputStream stream; @@ -108,141 +108,140 @@ public void releaseConnection(boolean consumeInputStream) throws IOException }; - //Setting attributes - response.setStatus(status); - response.setHeaders(getHeaders(connection)); - - return response; - } - - /** - * Create map with response headers. - * - * @param connection - HttpURLConnection - * @return map key - list of values - */ - protected MultivaluedMap getHeaders( - final HttpURLConnection connection) - { - MultivaluedMap headers = new CaseInsensitiveMap(); - - for (Map.Entry> header : connection.getHeaderFields() - .entrySet()) - { - if (header.getKey() != null) + //Setting attributes + response.setStatus(status); + response.setHeaders(getHeaders(connection)); + + return response; + } + + /** + * Create map with response headers. + * + * @param connection - HttpURLConnection + * @return map key - list of values + */ + protected MultivaluedMap getHeaders( + final HttpURLConnection connection) + { + MultivaluedMap headers = new CaseInsensitiveMap(); + + for (Map.Entry> header : connection.getHeaderFields() + .entrySet()) + { + if (header.getKey() != null) + { + for (String value : header.getValue()) { - for (String value : header.getValue()) - { - headers.add(header.getKey(), value); - } + headers.add(header.getKey(), value); } - } - return headers; - } - - @Override - public void close() - { - //empty - } - - /** - * Create HttpUrlConnection from ClientInvorcation and set request method. - * @param request ClientInvocation - * @return HttpURLConnection with method {@literal &} url already set - * @throws IOException if url or io exceptions - */ - protected HttpURLConnection createConnection(final ClientInvocation request) throws IOException - { - HttpURLConnection connection = (HttpURLConnection) request.getUri().toURL().openConnection(); - connection.setRequestMethod(request.getMethod()); - - return connection; - } - - /** - * Execute request using HttpURLConnection with body from invocation if needed. - * - * @param request ClientInvocation - * @param connection HttpURLConnection - */ - protected void executeRequest(final ClientInvocation request, HttpURLConnection connection) - { - connection.setInstanceFollowRedirects(request.getMethod().equals("GET")); - - if (request.getEntity() != null) - { - if (request.getMethod().equals("GET")) throw new ProcessingException(Messages.MESSAGES.getRequestCannotHaveBody()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - request.getDelegatingOutputStream().setDelegate(baos); - try - { + } + } + return headers; + } + + @Override + public void close() + { + //empty + } + + /** + * Create HttpUrlConnection from ClientInvorcation and set request method. + * @param request ClientInvocation + * @return HttpURLConnection with method {@literal &} url already set + * @throws IOException if url or io exceptions + */ + protected HttpURLConnection createConnection(final ClientInvocation request) throws IOException + { + HttpURLConnection connection = (HttpURLConnection) request.getUri().toURL().openConnection(); + connection.setRequestMethod(request.getMethod()); + + return connection; + } + + /** + * Execute request using HttpURLConnection with body from invocation if needed. + * + * @param request ClientInvocation + * @param connection HttpURLConnection + */ + protected void executeRequest(final ClientInvocation request, HttpURLConnection connection) + { + connection.setInstanceFollowRedirects(request.getMethod().equals("GET")); + + if (request.getEntity() != null) + { + if (request.getMethod().equals("GET")) throw new ProcessingException(Messages.MESSAGES.getRequestCannotHaveBody()); - request.writeRequestBody(request.getEntityStream()); - baos.close(); - commitHeaders(request, connection); - connection.setDoOutput(true); - OutputStream os = connection.getOutputStream(); - os.write(baos.toByteArray()); - os.flush(); - os.close(); - } - catch (IOException e) - { - throw new RuntimeException(e); - } - } - else // no body - { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + request.getDelegatingOutputStream().setDelegate(baos); + try + { + + request.writeRequestBody(request.getEntityStream()); + baos.close(); commitHeaders(request, connection); - } - } - - /** - * Add headers to HttpURLConnection from ClientInvocation. Should be executed before writing body. - * @param request ClientInvocation - * @param connection HttpURLConnection - */ - protected void commitHeaders(ClientInvocation request, HttpURLConnection connection) - { - MultivaluedMap headers = request.getHeaders().asMap(); - for (Map.Entry> header : headers.entrySet()) - { - List values = header.getValue(); - for (String value : values) - { - connection.addRequestProperty(header.getKey(), value); - } - } - } - - /** - * {inheritDoc} - */ - @Override - public SSLContext getSslContext() - { - return sslContext; - } - - /** - * {inheritDoc} - */ - @Override - public HostnameVerifier getHostnameVerifier() - { - return hostnameVerifier; - } - - public void setSslContext(SSLContext sslContext) - { - this.sslContext = sslContext; - } - - public void setHostnameVerifier(HostnameVerifier hostnameVerifier) - { - this.hostnameVerifier = hostnameVerifier; - } + connection.setDoOutput(true); + OutputStream os = connection.getOutputStream(); + os.write(baos.toByteArray()); + os.flush(); + os.close(); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + } + else // no body + { + commitHeaders(request, connection); + } + } + + /** + * Add headers to HttpURLConnection from ClientInvocation. Should be executed before writing body. + * @param request ClientInvocation + * @param connection HttpURLConnection + */ + protected void commitHeaders(ClientInvocation request, HttpURLConnection connection) + { + MultivaluedMap headers = request.getHeaders().asMap(); + for (Map.Entry> header : headers.entrySet()) + { + List values = header.getValue(); + for (String value : values) + { + connection.addRequestProperty(header.getKey(), value); + } + } + } + + /** + * {inheritDoc} + */ + @Override + public SSLContext getSslContext() + { + return sslContext; + } + + /** + * {inheritDoc} + */ + @Override + public HostnameVerifier getHostnameVerifier() + { + return hostnameVerifier; + } + + public void setSslContext(SSLContext sslContext) + { + this.sslContext = sslContext; + } + + public void setHostnameVerifier(HostnameVerifier hostnameVerifier) + { + this.hostnameVerifier = hostnameVerifier; + } } - diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/factory/ApacheHttpClient4EngineFactory.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/factory/ApacheHttpClient4EngineFactory.java index 3c1bb68057b..8f062cb31a8 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/factory/ApacheHttpClient4EngineFactory.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/engines/factory/ApacheHttpClient4EngineFactory.java @@ -15,111 +15,111 @@ */ public class ApacheHttpClient4EngineFactory { - private ApacheHttpClient4EngineFactory() - { + private ApacheHttpClient4EngineFactory() + { - } + } - public static ClientHttpEngine createWithDefaultProxy(HttpHost defaultProxy) - { - if(isConfigurableAvailable()) - { - ApacheHttpClient4Engine engine = new ApacheHttpClient43Engine(defaultProxy); - //We have to check that the HttpClient to be used has the configurable interface - if(isUsingOldStyleConfiguration(engine.getHttpClient())) - { - LogMessages.LOGGER.warn(Messages.MESSAGES.pleaseConsiderUnpdating()); - engine.close(); - return new ApacheHttpClient4Engine(defaultProxy); - } - return engine; - } - else - { + public static ClientHttpEngine createWithDefaultProxy(HttpHost defaultProxy) + { + if(isConfigurableAvailable()) + { + ApacheHttpClient4Engine engine = new ApacheHttpClient43Engine(defaultProxy); + //We have to check that the HttpClient to be used has the configurable interface + if(isUsingOldStyleConfiguration(engine.getHttpClient())) + { + LogMessages.LOGGER.warn(Messages.MESSAGES.pleaseConsiderUnpdating()); + engine.close(); return new ApacheHttpClient4Engine(defaultProxy); - } - } + } + return engine; + } + else + { + return new ApacheHttpClient4Engine(defaultProxy); + } + } - public static ClientHttpEngine create() - { - return createWithDefaultProxy(null); - } + public static ClientHttpEngine create() + { + return createWithDefaultProxy(null); + } - public static ClientHttpEngine create(HttpClient httpClient) - { - if(isUsingOldStyleConfiguration(httpClient)) - { - return new ApacheHttpClient4Engine(httpClient); - } - else - { - return new ApacheHttpClient43Engine(httpClient); - } - } + public static ClientHttpEngine create(HttpClient httpClient) + { + if(isUsingOldStyleConfiguration(httpClient)) + { + return new ApacheHttpClient4Engine(httpClient); + } + else + { + return new ApacheHttpClient43Engine(httpClient); + } + } - public static ClientHttpEngine create(HttpClient httpClient, boolean closeHttpClient) - { - if(isUsingOldStyleConfiguration(httpClient)) - { - return new ApacheHttpClient4Engine(httpClient,closeHttpClient); - } - else - { - return new ApacheHttpClient43Engine(httpClient, closeHttpClient); - } - } + public static ClientHttpEngine create(HttpClient httpClient, boolean closeHttpClient) + { + if(isUsingOldStyleConfiguration(httpClient)) + { + return new ApacheHttpClient4Engine(httpClient,closeHttpClient); + } + else + { + return new ApacheHttpClient43Engine(httpClient, closeHttpClient); + } + } - public static ClientHttpEngine create(HttpClient httpClient, HttpContext httpContext) - { - if(isUsingOldStyleConfiguration(httpClient)) - { - return new ApacheHttpClient4Engine(httpClient,httpContext); - } - else - { - return new ApacheHttpClient43Engine(httpClient, httpContext); - } - } + public static ClientHttpEngine create(HttpClient httpClient, HttpContext httpContext) + { + if(isUsingOldStyleConfiguration(httpClient)) + { + return new ApacheHttpClient4Engine(httpClient,httpContext); + } + else + { + return new ApacheHttpClient43Engine(httpClient, httpContext); + } + } - private static boolean isUsingOldStyleConfiguration(HttpClient client) - { - /** - if(!isConfigurableAvailable()) - { - return true; - } + private static boolean isUsingOldStyleConfiguration(HttpClient client) + { + /** + if(!isConfigurableAvailable()) + { + return true; + } - if(!(client instanceof Configurable)) // Yep, they could be using a new style config with a client that we can't actually use - { - LogMessages.LOGGER.warn("Please consider updating the version of Apache HttpClient being used. Version 4.3.6+ is recommended."); - return true; - } + if(!(client instanceof Configurable)) // Yep, they could be using a new style config with a client that we can't actually use + { + LogMessages.LOGGER.warn("Please consider updating the version of Apache HttpClient being used. Version 4.3.6+ is recommended."); + return true; + } - RequestConfig config = ((Configurable) client).getConfig(); - return config == null; - **/ - boolean isOld = true; - try { - client.getParams(); - LogMessages.LOGGER.warn(Messages.MESSAGES.pleaseConsiderUnpdating()); + RequestConfig config = ((Configurable) client).getConfig(); + return config == null; + **/ + boolean isOld = true; + try { + client.getParams(); + LogMessages.LOGGER.warn(Messages.MESSAGES.pleaseConsiderUnpdating()); - } catch (UnsupportedOperationException e) { - isOld = false; - } + } catch (UnsupportedOperationException e) { + isOld = false; + } - return isOld; - } + return isOld; + } - private static boolean isConfigurableAvailable() - { - try - { - Class.forName("org.apache.http.client.methods.Configurable"); - return true; - } - catch (ClassNotFoundException e) - { - return false; - } - } + private static boolean isConfigurableAvailable() + { + try + { + Class.forName("org.apache.http.client.methods.Configurable"); + return true; + } + catch (ClassNotFoundException e) + { + return false; + } + } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/AbortedResponse.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/AbortedResponse.java index 483a3a1f375..a4598440098 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/AbortedResponse.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/AbortedResponse.java @@ -35,7 +35,7 @@ public AbortedResponse(ClientConfiguration configuration, Response response) { for (Object obj : entry.getValue()) { - getMetadata().add(entry.getKey(), configuration.toHeaderString(obj)); + getMetadata().add(entry.getKey(), configuration.toHeaderString(obj)); } } setStatus(response.getStatus()); @@ -60,8 +60,8 @@ public AbortedResponse(ClientConfiguration configuration, Response response) @SuppressWarnings("rawtypes") MessageBodyWriter writer = configuration - .getMessageBodyWriter(getEntityClass(), getGenericType(), - null, mediaType); + .getMessageBodyWriter(getEntityClass(), getGenericType(), + null, mediaType); if (writer == null) { throw new ProcessingException(Messages.MESSAGES.failedToBufferAbortedResponseNoWriter(mediaType, entityClass.getName())); } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientConfiguration.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientConfiguration.java index 487440432ea..e291d5d6932 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientConfiguration.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientConfiguration.java @@ -84,7 +84,7 @@ public MessageBodyWriter getMessageBodyWriter(Class type, Type generic { MessageBodyWriter writer = providerFactory.getClientMessageBodyWriter(type, genericType, annotations, mediaType); if (writer!=null) - LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); return writer; } @@ -92,7 +92,7 @@ public MessageBodyReader getMessageBodyReader(Class type, Type generic { MessageBodyReader reader = providerFactory.getClientMessageBodyReader(type, genericType, annotations, mediaType); if (reader!=null) - LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); return reader; } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java index 55ce9ffb117..346955ff7ae 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocation.java @@ -516,8 +516,7 @@ public T extractResult(ClientResponse response) }); } - @SuppressWarnings( - {"rawtypes", "unchecked"}) + @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Future submit(final InvocationCallback callback) { diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocationBuilder.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocationBuilder.java index 648f7193583..ddcac1bdbc6 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocationBuilder.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientInvocationBuilder.java @@ -265,7 +265,7 @@ public Response options() public T options(Class responseType) { return build(HttpMethod.OPTIONS).invoke(responseType); - } + } @Override public T options(GenericType responseType) @@ -380,7 +380,7 @@ public URI getURI() { return uri; } - + public WebTarget getTarget() { return target; diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientResponse.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientResponse.java index 11ee1aee6c2..ede6540f2e5 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientResponse.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientResponse.java @@ -216,7 +216,7 @@ public void close() throws IOException { /** * Release underlying connection but do not close. - * + * * @param consumeInputStream boolean to indicate either the underlying input stream must be fully read before releasing the connection or not. *

* For most HTTP connection implementations, consuming the underlying input stream before releasing the connection will help to ensure connection reusability with respect of Keep-Alive policy. @@ -260,9 +260,9 @@ else if (bufferedEntity == null) { entity = readFrom(type, genericType, getMediaType(), anns); if (entity == null || (entity != null - && !InputStream.class.isInstance(entity) - && !Reader.class.isInstance(entity) - && bufferedEntity == null)) + && !InputStream.class.isInstance(entity) + && !Reader.class.isInstance(entity) + && bufferedEntity == null)) { try { @@ -409,15 +409,15 @@ public boolean bufferEntity() protected void resetEntity() { - entity = null; - bufferedEntity = null; - streamFullyRead = false; + entity = null; + bufferedEntity = null; + streamFullyRead = false; } @Override public void abortIfClosed() { - if (bufferedEntity == null) super.abortIfClosed(); + if (bufferedEntity == null) super.abortIfClosed(); } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientWebTarget.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientWebTarget.java index e9af66c5434..fb50aad36dd 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientWebTarget.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/ClientWebTarget.java @@ -57,18 +57,18 @@ public ClientWebTarget(ResteasyClient client, UriBuilder uriBuilder, ClientConfi * Get a new UriBuilder explicitly using RESTEasy implementation * (instead of running UriBuilder.fromUri(uri) which relies on * current registered JAX-RS implementation) - * + * * @param uri * @return */ private static UriBuilder uriBuilderFromUri(URI uri) { - return new ResteasyUriBuilder().uri(uri); + return new ResteasyUriBuilder().uri(uri); } private static UriBuilder uriBuilderFromUri(String uri) { - return new ResteasyUriBuilder().uri(uri); + return new ResteasyUriBuilder().uri(uri); } @Override @@ -312,9 +312,9 @@ public ResteasyWebTarget queryParamNoTemplate(String name, Object... values) thr String[] stringValues = toStringValues(values); ResteasyUriBuilder copy; if (uriBuilder instanceof ResteasyUriBuilder) { - copy = (ResteasyUriBuilder)uriBuilder.clone(); + copy = (ResteasyUriBuilder)uriBuilder.clone(); } else { - copy = (ResteasyUriBuilder)ResteasyUriBuilder.fromTemplate(uriBuilder.toTemplate()); + copy = (ResteasyUriBuilder)ResteasyUriBuilder.fromTemplate(uriBuilder.toTemplate()); } for (String obj : stringValues) { @@ -330,9 +330,9 @@ public ResteasyWebTarget queryParamsNoTemplate(MultivaluedMap pa if (parameters == null) throw new NullPointerException(Messages.MESSAGES.parametersWasNull()); ResteasyUriBuilder copy; if (uriBuilder instanceof ResteasyUriBuilder) { - copy = (ResteasyUriBuilder)uriBuilder.clone(); + copy = (ResteasyUriBuilder)uriBuilder.clone(); } else { - copy = (ResteasyUriBuilder)ResteasyUriBuilder.fromTemplate(uriBuilder.toTemplate()); + copy = (ResteasyUriBuilder)ResteasyUriBuilder.fromTemplate(uriBuilder.toTemplate()); } for (Map.Entry> entry : parameters.entrySet()) { diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/CompletionStageRxInvokerProvider.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/CompletionStageRxInvokerProvider.java index aa446d47a00..f914bb5cfdd 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/CompletionStageRxInvokerProvider.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/CompletionStageRxInvokerProvider.java @@ -17,4 +17,4 @@ public boolean isProviderFor(Class clazz) { public CompletionStageRxInvoker getRxInvoker(SyncInvoker syncInvoker, ExecutorService executorService) { return new CompletionStageRxInvokerImpl(syncInvoker, executorService); } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientInvoker.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientInvoker.java index ebe7e7f27c1..6303a81a5f7 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientInvoker.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientInvoker.java @@ -110,7 +110,7 @@ public Class getDeclaring() public Object invoke(Object[] args) { return rxInvokerProvider != null ? invokeAsync(args) : invokeSync(args); - } + } protected Object invokeAsync(final Object[] args) { @@ -221,4 +221,4 @@ public void setSyncInvoker(SyncInvoker syncInvoker) { this.syncInvoker = syncInvoker; } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientProxy.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientProxy.java index 787f5ba6c4b..6115acb24d2 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientProxy.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/ClientProxy.java @@ -17,31 +17,31 @@ */ public class ClientProxy implements InvocationHandler { - private Map methodMap; - private Class clazz; - private final WebTarget target; - private final ProxyConfig config; + private Map methodMap; + private Class clazz; + private final WebTarget target; + private final ProxyConfig config; - public ClientProxy(Map methodMap, WebTarget target, ProxyConfig config) - { - super(); - this.methodMap = methodMap; - this.target = target; - this.config = config; - } + public ClientProxy(Map methodMap, WebTarget target, ProxyConfig config) + { + super(); + this.methodMap = methodMap; + this.target = target; + this.config = config; + } - public Class getClazz() - { - return clazz; - } + public Class getClazz() + { + return clazz; + } - public void setClazz(Class clazz) - { - this.clazz = clazz; - } + public void setClazz(Class clazz) + { + this.clazz = clazz; + } - public Object invoke(Object o, Method method, Object[] args) - throws Throwable + public Object invoke(Object o, Method method, Object[] args) + throws Throwable { // equals and hashCode were added for cases where the proxy is added to // collections. The Spring transaction management, for example, adds @@ -65,7 +65,7 @@ else if (method.getName().equals("toString") && (args == null || args.length == } else if(method.getName().equals("as") && args.length == 1 && args[0] instanceof Class) { - return ProxyBuilder.proxy((Class)args[0], target, config); + return ProxyBuilder.proxy((Class)args[0], target, config); } } @@ -76,27 +76,27 @@ else if(method.getName().equals("as") && args.length == 1 && args[0] instanceof return clientInvoker.invoke(args); } - @Override - public boolean equals(Object obj) - { - if (obj == null || !(obj instanceof ClientProxy)) - return false; - ClientProxy other = (ClientProxy) obj; - if (other == this) - return true; - if (other.clazz != this.clazz) - return false; - return super.equals(obj); - } + @Override + public boolean equals(Object obj) + { + if (obj == null || !(obj instanceof ClientProxy)) + return false; + ClientProxy other = (ClientProxy) obj; + if (other == this) + return true; + if (other.clazz != this.clazz) + return false; + return super.equals(obj); + } - @Override - public int hashCode() - { - return clazz.hashCode(); - } + @Override + public int hashCode() + { + return clazz.hashCode(); + } - public String toString() - { - return Messages.MESSAGES.resteasyClientProxyFor(clazz.getName()); - } + public String toString() + { + return Messages.MESSAGES.resteasyClientProxyFor(clazz.getName()); + } } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/MethodInvoker.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/MethodInvoker.java index 61068ac46aa..38e04a9f787 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/MethodInvoker.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/MethodInvoker.java @@ -2,5 +2,5 @@ public interface MethodInvoker { - Object invoke(Object[] args); + Object invoke(Object[] args); } diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/BodyEntityExtractor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/BodyEntityExtractor.java index d3a0ea64b41..212e6188e75 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/BodyEntityExtractor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/BodyEntityExtractor.java @@ -68,4 +68,4 @@ public Object extractEntity(ClientContext context, Object... args) response.close(); } } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/ResponseObjectEntityExtractorFactory.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/ResponseObjectEntityExtractorFactory.java index 396dd510e70..30f13c6fba6 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/ResponseObjectEntityExtractorFactory.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/extractors/ResponseObjectEntityExtractorFactory.java @@ -184,9 +184,9 @@ public WebTarget extractEntity(ClientContext context, Object... args) private ClientInvoker createClientInvoker(ClientContext context, URI uri, Method method) { ClientInvoker clientInvoker = new ClientInvoker((ResteasyWebTarget)(context.getInvocation().getClient().target(uri)), - method.getDeclaringClass(), - method, - new ProxyConfig(Thread.currentThread().getContextClassLoader(), null, null)); + method.getDeclaringClass(), + method, + new ProxyConfig(Thread.currentThread().getContextClassLoader(), null, null)); Set httpMethods = IsHttpMethod.getHttpMethods(method); clientInvoker.setHttpMethod(httpMethods.iterator().next()); diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/FormProcessor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/FormProcessor.java index 77287002a3b..fbc5cb611cc 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/FormProcessor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/FormProcessor.java @@ -52,7 +52,7 @@ public FormProcessor(Class clazz, ClientConfiguration configuration) } public static long methodHash(Method method) - throws Exception + throws Exception { Class[] parameterTypes = method.getParameterTypes(); StringBuilder methodDesc = new StringBuilder(method.getName()).append("("); @@ -65,7 +65,7 @@ public static long methodHash(Method method) } public static long createHash(String methodDesc) - throws Exception + throws Exception { long hash = 0; ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512); @@ -279,4 +279,4 @@ private void processParam(ClientInvocationBuilder invocation, Object val, Object processor.process(invocation, val); } } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/ProcessorFactory.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/ProcessorFactory.java index c51940a7459..eae447367d1 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/ProcessorFactory.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/ProcessorFactory.java @@ -39,13 +39,13 @@ public class ProcessorFactory { - public static Object[] createProcessors(Class declaringClass, Method method, ClientConfiguration configuration) - { - return createProcessors(declaringClass, method, configuration, null); - } - - public static Object[] createProcessors(Class declaringClass, Method method, ClientConfiguration configuration, MediaType defaultConsumes) - { + public static Object[] createProcessors(Class declaringClass, Method method, ClientConfiguration configuration) + { + return createProcessors(declaringClass, method, configuration, null); + } + + public static Object[] createProcessors(Class declaringClass, Method method, ClientConfiguration configuration, MediaType defaultConsumes) + { Object[] params = new Object[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { @@ -53,7 +53,7 @@ public static Object[] createProcessors(Class declaringClass, Method method, Cli Annotation[] annotations = method.getParameterAnnotations()[i]; Type genericType = method.getGenericParameterTypes()[i]; if (TypeVariable.class.isInstance(genericType) && declaringClass.isInterface() && !declaringClass.equals(method.getDeclaringClass())) { - genericType = getTypeArgument((TypeVariable)genericType, declaringClass, method.getDeclaringClass()); + genericType = getTypeArgument((TypeVariable)genericType, declaringClass, method.getDeclaringClass()); } AccessibleObject target = method; params[i] = ProcessorFactory.createProcessor(declaringClass, configuration, type, annotations, genericType, target, defaultConsumes, false); @@ -61,18 +61,18 @@ public static Object[] createProcessors(Class declaringClass, Method method, Cli return params; } - public static Object createProcessor(Class declaring, + public static Object createProcessor(Class declaring, ClientConfiguration configuration, Class type, Annotation[] annotations, Type genericType, AccessibleObject target, boolean ignoreBody) - { - return createProcessor(declaring, configuration, type, annotations, genericType, target, null, ignoreBody); - } - - public static Object createProcessor(Class declaring, - ClientConfiguration configuration, Class type, - Annotation[] annotations, Type genericType, AccessibleObject target, MediaType defaultConsumes, - boolean ignoreBody) + { + return createProcessor(declaring, configuration, type, annotations, genericType, target, null, ignoreBody); + } + + public static Object createProcessor(Class declaring, + ClientConfiguration configuration, Class type, + Annotation[] annotations, Type genericType, AccessibleObject target, MediaType defaultConsumes, + boolean ignoreBody) { Object processor = null; @@ -85,49 +85,49 @@ public static Object createProcessor(Class declaring, // Form form; boolean isEncoded = FindAnnotation.findAnnotation(annotations, - Encoded.class) != null; + Encoded.class) != null; if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) { processor = new QueryParamProcessor(query.value()); } else if ((header = FindAnnotation.findAnnotation(annotations, - HeaderParam.class)) != null) + HeaderParam.class)) != null) { processor = new HeaderParamProcessor(header.value()); } else if ((cookie = FindAnnotation.findAnnotation(annotations, - CookieParam.class)) != null) + CookieParam.class)) != null) { processor = new CookieParamProcessor(cookie.value()); } else if ((uriParam = FindAnnotation.findAnnotation(annotations, - PathParam.class)) != null) + PathParam.class)) != null) { processor = new PathParamProcessor(uriParam.value(), isEncoded); } else if ((matrix = FindAnnotation.findAnnotation(annotations, - MatrixParam.class)) != null) + MatrixParam.class)) != null) { processor = new MatrixParamProcessor(matrix.value()); } else if ((formParam = FindAnnotation.findAnnotation(annotations, - FormParam.class)) != null) + FormParam.class)) != null) { processor = new FormParamProcessor(formParam.value()); } else if ((/* form = */FindAnnotation.findAnnotation(annotations, - Form.class)) != null) + Form.class)) != null) { processor = new FormProcessor(type, configuration); } else if ((/* form = */FindAnnotation.findAnnotation(annotations, - BeanParam.class)) != null) + BeanParam.class)) != null) { processor = new FormProcessor(type, configuration); } else if ((FindAnnotation.findAnnotation(annotations, - Context.class)) != null) + Context.class)) != null) { processor = null; } @@ -144,7 +144,7 @@ else if (!ignoreBody) { MediaType mediaType = MediaTypeHelper.getConsumes(declaring, target); if(mediaType == null) - mediaType = defaultConsumes; + mediaType = defaultConsumes; if (mediaType == null) { throw new RuntimeException(Messages.MESSAGES.mustDefineConsumesType()); diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/FormParamProcessor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/FormParamProcessor.java index 1a49806629e..e5bce245ad2 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/FormParamProcessor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/FormParamProcessor.java @@ -44,4 +44,4 @@ protected ClientInvocationBuilder apply(ClientInvocationBuilder target, Object o return target; } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/HeaderParamProcessor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/HeaderParamProcessor.java index 9727d0a8044..40ba2373be0 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/HeaderParamProcessor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/HeaderParamProcessor.java @@ -20,4 +20,4 @@ protected ClientInvocationBuilder apply(ClientInvocationBuilder target, Object o return (ClientInvocationBuilder)target.header(paramName, object); } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/MessageBodyParameterProcessor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/MessageBodyParameterProcessor.java index 16e5912d9f8..99893714f90 100755 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/MessageBodyParameterProcessor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/invocation/MessageBodyParameterProcessor.java @@ -51,4 +51,4 @@ public MediaType getMediaType() return mediaType; } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/MatrixParamProcessor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/MatrixParamProcessor.java index 2de8c637a6f..8b578d39bd0 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/MatrixParamProcessor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/MatrixParamProcessor.java @@ -20,4 +20,4 @@ protected WebTarget apply(WebTarget target, Object object) return target.matrixParam(paramName, object); } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/QueryParamProcessor.java b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/QueryParamProcessor.java index 88fc9fa517d..89a3df95b71 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/QueryParamProcessor.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/internal/proxy/processors/webtarget/QueryParamProcessor.java @@ -23,4 +23,4 @@ protected WebTarget apply(WebTarget target, Object object) } -} \ No newline at end of file +} diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceImpl.java b/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceImpl.java index bc86d1f48a3..2f0995795ce 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceImpl.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceImpl.java @@ -5,11 +5,8 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; diff --git a/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceScheduler.java b/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceScheduler.java index 70cc5f355a5..dc70d95116d 100644 --- a/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceScheduler.java +++ b/resteasy-client/src/main/java/org/jboss/resteasy/plugins/providers/sse/client/SseEventSourceScheduler.java @@ -148,4 +148,4 @@ void shutdownNow() } } -} \ No newline at end of file +} diff --git a/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/ResponseBuilderProvider.java b/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/ResponseBuilderProvider.java index 638d8f9c2cc..d0e32e9f374 100644 --- a/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/ResponseBuilderProvider.java +++ b/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/ResponseBuilderProvider.java @@ -20,4 +20,4 @@ public Response.ResponseBuilder get() { return runtimeDelegate.createResponseBuilder(); } -} \ No newline at end of file +} diff --git a/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/VariantListBuilderProvider.java b/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/VariantListBuilderProvider.java index b3c5c86263c..62d480ef578 100644 --- a/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/VariantListBuilderProvider.java +++ b/resteasy-guice/src/main/java/org/jboss/resteasy/plugins/guice/ext/VariantListBuilderProvider.java @@ -20,4 +20,4 @@ public Variant.VariantListBuilder get() { return runtimeDelegate.createVariantListBuilder(); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/main/java/org/jboss/resteasy/test/resteasy_jaxrs/i18n/TestMessagesParent.java b/resteasy-jaxrs-testsuite/src/main/java/org/jboss/resteasy/test/resteasy_jaxrs/i18n/TestMessagesParent.java index 54e3733aa89..c0bfc1f7b73 100644 --- a/resteasy-jaxrs-testsuite/src/main/java/org/jboss/resteasy/test/resteasy_jaxrs/i18n/TestMessagesParent.java +++ b/resteasy-jaxrs-testsuite/src/main/java/org/jboss/resteasy/test/resteasy_jaxrs/i18n/TestMessagesParent.java @@ -36,17 +36,17 @@ static public void afterClass() public boolean before(Locale locale, String filename) throws Exception { - LOG.info("default locale: " + Locale.getDefault()); - Locale.setDefault(locale); - LOG.info("Set default locale to: " + locale); - LOG.info("Messages file: " + filename); - InputStream is = getClass().getClassLoader().getResourceAsStream(filename); - if (is == null) - { - return false; - } - properties.load(is); - return getExpectedNumberOfMethods() == properties.size(); + LOG.info("default locale: " + Locale.getDefault()); + Locale.setDefault(locale); + LOG.info("Set default locale to: " + locale); + LOG.info("Messages file: " + filename); + InputStream is = getClass().getClassLoader().getResourceAsStream(filename); + if (is == null) + { + return false; + } + properties.load(is); + return getExpectedNumberOfMethods() == properties.size(); } protected String getExpected(String id, String message, Object... args) diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/ResponseObjectTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/ResponseObjectTest.java index e584962895b..ae82c2221ce 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/ResponseObjectTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/ResponseObjectTest.java @@ -32,114 +32,114 @@ public class ResponseObjectTest { - private static ResteasyClient client; - private static ResponseObjectClient responseObjectClient; - - @Path("test") - interface ResponseObjectClient - { - @GET - BasicObject get(); - - @GET - @Path("link-header") - HateoasObject performGetBasedOnHeader(); - } - - @ResponseObject - public interface BasicObject - { - @Status - int status(); - - @Body - String body(); - - ClientResponse response(); - - @HeaderParam("Content-Type") - String contentType(); - } - - @ResponseObject - public interface HateoasObject - { - @Status - int status(); - - @LinkHeaderParam(rel = "nextLink") - URI nextLink(); - - @GET - @LinkHeaderParam(rel = "nextLink") - String followNextLink(); - } - - @Path("test") - public static class ResponseObjectResource - { - - @GET - @Produces("text/plain") - public String get() - { - return "ABC"; - } - - @GET - @Path("/link-header") - public Response getWithHeader(@Context UriInfo uri) - { - URI subUri = uri.getAbsolutePathBuilder().path("next-link").build(); - org.jboss.resteasy.spi.Link link = new org.jboss.resteasy.spi.Link(); - link.setHref(subUri.toASCIIString()); - link.setRelationship("nextLink"); - return Response.noContent().header("Link", link.toString()).build(); - } - - @GET - @Produces("text/plain") - @Path("/link-header/next-link") - public String getHeaderForward() - { - return "forwarded"; - } - } - - @BeforeClass - public static void before() throws Exception - { - final Dispatcher dispatcher = EmbeddedContainer.start().getDispatcher(); - client = new ResteasyClientBuilder().build(); - dispatcher.getRegistry().addPerRequestResource(ResponseObjectResource.class); - responseObjectClient = ProxyBuilder.builder(ResponseObjectClient.class, client.target(generateBaseUrl())).build(); - } - - @AfterClass - public static void after() throws Exception - { - client.close(); - EmbeddedContainer.stop(); - } - - @Test - public void testSimple() - { - BasicObject obj = responseObjectClient.get(); - org.junit.Assert.assertEquals(HttpResponseCodes.SC_OK, obj.status()); - org.junit.Assert.assertEquals("The response object doesn't contain the expected string", "ABC", obj.body()); - org.junit.Assert.assertEquals("The response object doesn't contain the expected header", - "text/plain;charset=UTF-8", obj.response().getHeaders().getFirst("Content-Type")); - org.junit.Assert.assertEquals("The response object doesn't contain the expected header", "text/plain;charset=UTF-8", obj.contentType()); - } - - @Test - public void testLinkFollow() - { - HateoasObject obj = responseObjectClient.performGetBasedOnHeader(); - org.junit.Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, obj.status()); - org.junit.Assert.assertTrue("The resource was not forwarded", obj.nextLink().getPath().endsWith("next-link")); - org.junit.Assert.assertEquals("The resource was not forwarded", "forwarded", obj.followNextLink()); - - } + private static ResteasyClient client; + private static ResponseObjectClient responseObjectClient; + + @Path("test") + interface ResponseObjectClient + { + @GET + BasicObject get(); + + @GET + @Path("link-header") + HateoasObject performGetBasedOnHeader(); + } + + @ResponseObject + public interface BasicObject + { + @Status + int status(); + + @Body + String body(); + + ClientResponse response(); + + @HeaderParam("Content-Type") + String contentType(); + } + + @ResponseObject + public interface HateoasObject + { + @Status + int status(); + + @LinkHeaderParam(rel = "nextLink") + URI nextLink(); + + @GET + @LinkHeaderParam(rel = "nextLink") + String followNextLink(); + } + + @Path("test") + public static class ResponseObjectResource + { + + @GET + @Produces("text/plain") + public String get() + { + return "ABC"; + } + + @GET + @Path("/link-header") + public Response getWithHeader(@Context UriInfo uri) + { + URI subUri = uri.getAbsolutePathBuilder().path("next-link").build(); + org.jboss.resteasy.spi.Link link = new org.jboss.resteasy.spi.Link(); + link.setHref(subUri.toASCIIString()); + link.setRelationship("nextLink"); + return Response.noContent().header("Link", link.toString()).build(); + } + + @GET + @Produces("text/plain") + @Path("/link-header/next-link") + public String getHeaderForward() + { + return "forwarded"; + } + } + + @BeforeClass + public static void before() throws Exception + { + final Dispatcher dispatcher = EmbeddedContainer.start().getDispatcher(); + client = new ResteasyClientBuilder().build(); + dispatcher.getRegistry().addPerRequestResource(ResponseObjectResource.class); + responseObjectClient = ProxyBuilder.builder(ResponseObjectClient.class, client.target(generateBaseUrl())).build(); + } + + @AfterClass + public static void after() throws Exception + { + client.close(); + EmbeddedContainer.stop(); + } + + @Test + public void testSimple() + { + BasicObject obj = responseObjectClient.get(); + org.junit.Assert.assertEquals(HttpResponseCodes.SC_OK, obj.status()); + org.junit.Assert.assertEquals("The response object doesn't contain the expected string", "ABC", obj.body()); + org.junit.Assert.assertEquals("The response object doesn't contain the expected header", + "text/plain;charset=UTF-8", obj.response().getHeaders().getFirst("Content-Type")); + org.junit.Assert.assertEquals("The response object doesn't contain the expected header", "text/plain;charset=UTF-8", obj.contentType()); + } + + @Test + public void testLinkFollow() + { + HateoasObject obj = responseObjectClient.performGetBasedOnHeader(); + org.junit.Assert.assertEquals(HttpResponseCodes.SC_NO_CONTENT, obj.status()); + org.junit.Assert.assertTrue("The resource was not forwarded", obj.nextLink().getPath().endsWith("next-link")); + org.junit.Assert.assertEquals("The resource was not forwarded", "forwarded", obj.followNextLink()); + + } } diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/exception/HttpClient4ClientExceptionMapperTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/exception/HttpClient4ClientExceptionMapperTest.java index 700627b8873..fcf5fb62297 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/exception/HttpClient4ClientExceptionMapperTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/exception/HttpClient4ClientExceptionMapperTest.java @@ -440,7 +440,7 @@ private void doTest(Exception resteasyException, Exception embeddedException) th after(); } } - + @Test public void testAlternativeMapperProviderInstance() throws Exception { diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ApacheHttpClient4Test.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ApacheHttpClient4Test.java index f40172cb85b..1b5aa1bafac 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ApacheHttpClient4Test.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ApacheHttpClient4Test.java @@ -272,7 +272,7 @@ private ApacheHttpClient4Executor createClient() // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register( - new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // Create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ClientExceptionInterceptorTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ClientExceptionInterceptorTest.java index 6c008854e34..81db6bf15e8 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ClientExceptionInterceptorTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/ClientExceptionInterceptorTest.java @@ -75,8 +75,8 @@ public void testExceptionInterceptorsChain() throws Exception } /* - * Test utility classes - */ + * Test utility classes + */ @Path("/test") public static class TestResource { @@ -130,4 +130,4 @@ public boolean isHandled() public static class TestException extends RuntimeException { } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/InMemoryTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/InMemoryTest.java index 5354a1d2c11..9225ce32cf8 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/InMemoryTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/InMemoryTest.java @@ -55,4 +55,4 @@ public void testSimple() throws Exception Assert.assertEquals("hello world", request.getTarget(String.class)); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestDefaultMediaTypes.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestDefaultMediaTypes.java index 09743f20aa4..b3ae8c7ea52 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestDefaultMediaTypes.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestDefaultMediaTypes.java @@ -18,68 +18,68 @@ public class TestDefaultMediaTypes extends BaseResourceTest { - public interface Foo - { - @GET - @Path("foo") - String getFoo(); + public interface Foo + { + @GET + @Path("foo") + String getFoo(); - @PUT - @Path("foo") - String setFoo(String value); - } + @PUT + @Path("foo") + String setFoo(String value); + } - @Path("foo") - public static class FooImpl implements Foo - { - @Context - HttpRequest request; - - @Override - public String getFoo() - { - return request.getHttpHeaders().getAcceptableMediaTypes().toString(); - } + @Path("foo") + public static class FooImpl implements Foo + { + @Context + HttpRequest request; - @Override - public String setFoo(String value) - { - return request.getHttpHeaders().getMediaType().toString(); - } - } + @Override + public String getFoo() + { + return request.getHttpHeaders().getAcceptableMediaTypes().toString(); + } - @Before - public void setUp() throws Exception - { - addPerRequestResource(FooImpl.class); - } + @Override + public String setFoo(String value) + { + return request.getHttpHeaders().getMediaType().toString(); + } + } - @Test(expected = RuntimeException.class) - public void testOldBehaviorContinues() throws Exception - { - String url = TestPortProvider.generateURL("/foo"); - ProxyFactory.create(Foo.class, url); - } - - @Test - public void testDefaultValues() throws Exception - { - String url = TestPortProvider.generateURL("/foo"); - Foo foo = ProxyBuilder.build(Foo.class, url).serverMediaType(MediaType.TEXT_PLAIN_TYPE).now(); - - assertEquals("[text/plain]", foo.getFoo()); - assertEquals("text/plain", foo.setFoo("SOMETHING")); - } + @Before + public void setUp() throws Exception + { + addPerRequestResource(FooImpl.class); + } - @Test - public void testMismatch() throws Exception - { - // NOTE: this doesn't fail on the server because the default */* provider matches the - // requested media type. - String url = TestPortProvider.generateURL("/foo"); - Foo foo = ProxyBuilder.build(Foo.class, url).serverMediaType(MediaType.APPLICATION_JSON_TYPE).now(); - - assertEquals("[application/json]", foo.getFoo()); - assertEquals("application/json", foo.setFoo("SOMETHING")); - } + @Test(expected = RuntimeException.class) + public void testOldBehaviorContinues() throws Exception + { + String url = TestPortProvider.generateURL("/foo"); + ProxyFactory.create(Foo.class, url); + } + + @Test + public void testDefaultValues() throws Exception + { + String url = TestPortProvider.generateURL("/foo"); + Foo foo = ProxyBuilder.build(Foo.class, url).serverMediaType(MediaType.TEXT_PLAIN_TYPE).now(); + + assertEquals("[text/plain]", foo.getFoo()); + assertEquals("text/plain", foo.setFoo("SOMETHING")); + } + + @Test + public void testMismatch() throws Exception + { + // NOTE: this doesn't fail on the server because the default */* provider matches the + // requested media type. + String url = TestPortProvider.generateURL("/foo"); + Foo foo = ProxyBuilder.build(Foo.class, url).serverMediaType(MediaType.APPLICATION_JSON_TYPE).now(); + + assertEquals("[application/json]", foo.getFoo()); + assertEquals("application/json", foo.setFoo("SOMETHING")); + } } diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestProxyCastingSimple.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestProxyCastingSimple.java index 4006f69d41a..4dc3944c92a 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestProxyCastingSimple.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/client/old/TestProxyCastingSimple.java @@ -16,102 +16,102 @@ public class TestProxyCastingSimple extends BaseResourceTest { - public interface InterfaceAorB - { - T as(Class iface); - } + public interface InterfaceAorB + { + T as(Class iface); + } - public interface InterfaceA extends InterfaceAorB - { - @GET - @Path("foo") - @Produces("text/plain") - String getFoo(); - } + public interface InterfaceA extends InterfaceAorB + { + @GET + @Path("foo") + @Produces("text/plain") + String getFoo(); + } - public interface InterfaceB extends InterfaceAorB - { - @GET - @Path("bar") - @Produces("text/plain") - String getBar(); - } + public interface InterfaceB extends InterfaceAorB + { + @GET + @Path("bar") + @Produces("text/plain") + String getBar(); + } - public interface FooBar - { - @Path("{thing}") - InterfaceAorB getThing(@PathParam("thing") String thing); - } + public interface FooBar + { + @Path("{thing}") + InterfaceAorB getThing(@PathParam("thing") String thing); + } - @Path("/foobar") - public static class FooBarImpl implements FooBar - { - @Override - public InterfaceAorB getThing(String thing) - { - if ("a".equalsIgnoreCase(thing)) - { - return new InterfaceA() - { - @Override - public String getFoo() - { - return "FOO"; - } + @Path("/foobar") + public static class FooBarImpl implements FooBar + { + @Override + public InterfaceAorB getThing(String thing) + { + if ("a".equalsIgnoreCase(thing)) + { + return new InterfaceA() + { + @Override + public String getFoo() + { + return "FOO"; + } - @Override - public T as(Class iface) - { - return iface.cast(this); - } - }; - } - else if ("b".equalsIgnoreCase(thing)) - { - return new InterfaceB() - { - @Override - public String getBar() - { - return "BAR"; - } + @Override + public T as(Class iface) + { + return iface.cast(this); + } + }; + } + else if ("b".equalsIgnoreCase(thing)) + { + return new InterfaceB() + { + @Override + public String getBar() + { + return "BAR"; + } - @Override - public T as(Class iface) - { - return iface.cast(this); - } - }; - } - else - { - throw new IllegalArgumentException("Bad arg: " + thing); - } - } - } + @Override + public T as(Class iface) + { + return iface.cast(this); + } + }; + } + else + { + throw new IllegalArgumentException("Bad arg: " + thing); + } + } + } - @Before - public void setUp() throws Exception - { - addPerRequestResource(FooBarImpl.class); - } + @Before + public void setUp() throws Exception + { + addPerRequestResource(FooBarImpl.class); + } - @Test - public void testSubresourceProxy() throws Exception - { - String url = TestPortProvider.generateURL("/foobar"); - FooBar foobar = ProxyFactory.create(FooBar.class, url); - { - InterfaceA a = ((ResteasyClientProxy) foobar.getThing("a")).as(InterfaceA.class); - assertEquals("FOO", a.getFoo()); - InterfaceB b = ((ResteasyClientProxy) foobar.getThing("b")).as(InterfaceB.class); - assertEquals("BAR", b.getBar()); - } - { - InterfaceA a = foobar.getThing("a").as(InterfaceA.class); - assertEquals("FOO", a.getFoo()); - InterfaceB b = foobar.getThing("b").as(InterfaceB.class); - assertEquals("BAR", b.getBar()); - } - } + @Test + public void testSubresourceProxy() throws Exception + { + String url = TestPortProvider.generateURL("/foobar"); + FooBar foobar = ProxyFactory.create(FooBar.class, url); + { + InterfaceA a = ((ResteasyClientProxy) foobar.getThing("a")).as(InterfaceA.class); + assertEquals("FOO", a.getFoo()); + InterfaceB b = ((ResteasyClientProxy) foobar.getThing("b")).as(InterfaceB.class); + assertEquals("BAR", b.getBar()); + } + { + InterfaceA a = foobar.getThing("a").as(InterfaceA.class); + assertEquals("FOO", a.getFoo()); + InterfaceB b = foobar.getThing("b").as(InterfaceB.class); + assertEquals("BAR", b.getBar()); + } + } } diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/InternalDispatcherTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/InternalDispatcherTest.java index 1ef9af4adf5..641c61681ad 100755 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/InternalDispatcherTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/InternalDispatcherTest.java @@ -120,8 +120,8 @@ public static class ForwardingResource @Path("/basic") public String getBasic() { - String item = uriInfo.getAbsolutePath().toString(); - uriStack.push(item); + String item = uriInfo.getAbsolutePath().toString(); + uriStack.push(item); return basic; } @@ -239,9 +239,9 @@ public int infinitFoward(@Context InternalDispatcher dispatcher, finally { Assert - .assertEquals(count, MessageBodyParameterInjector.bodyCount()); + .assertEquals(count, MessageBodyParameterInjector.bodyCount()); Assert.assertEquals(count + 1, ResteasyProviderFactory - .getContextDataLevelCount()); + .getContextDataLevelCount()); } return ResteasyProviderFactory.getContextDataLevelCount(); } @@ -257,7 +257,7 @@ public static void before() throws Exception @Before public void setup() { - forwardingResource.uriStack.clear(); + forwardingResource.uriStack.clear(); } @AfterClass @@ -304,24 +304,24 @@ public void testInfinitForward() @Test public void testUriInfoBasic() { - String baseUrl = generateBaseUrl(); - Client client = ProxyFactory.create(Client.class, baseUrl); + String baseUrl = generateBaseUrl(); + Client client = ProxyFactory.create(Client.class, baseUrl); - client.getBasic(); - Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop()); - Assert.assertTrue(forwardingResource.uriStack.isEmpty()); + client.getBasic(); + Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop()); + Assert.assertTrue(forwardingResource.uriStack.isEmpty()); } @Test public void testUriInfoForwardBasic() { String baseUrl = generateBaseUrl(); - Client client = ProxyFactory.create(Client.class, baseUrl); + Client client = ProxyFactory.create(Client.class, baseUrl); - client.getForwardBasic(); - Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop()); - Assert.assertEquals(baseUrl + "/forward/basic", forwardingResource.uriStack.pop()); - Assert.assertTrue(forwardingResource.uriStack.isEmpty()); + client.getForwardBasic(); + Assert.assertEquals(baseUrl + "/basic", forwardingResource.uriStack.pop()); + Assert.assertEquals(baseUrl + "/forward/basic", forwardingResource.uriStack.pop()); + Assert.assertTrue(forwardingResource.uriStack.isEmpty()); } @Test diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/client/ClientFormParamTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/client/ClientFormParamTest.java index 89748fcf447..a159f302bf2 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/client/ClientFormParamTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/client/ClientFormParamTest.java @@ -51,4 +51,4 @@ public void test() throws Exception } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/PathParamTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/PathParamTest.java index 98de0769120..7a829251315 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/PathParamTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/PathParamTest.java @@ -63,9 +63,9 @@ public Response triple(@PathParam("id") int id, @GET @Path("/{id}/{id1}/{id2}/{id3}") public Response quard(@PathParam("id") double id, - @PathParam("id1") boolean id1, - @PathParam("id2") byte id2, - @PathParam("id3") PathSegment id3) + @PathParam("id1") boolean id1, + @PathParam("id2") byte id2, + @PathParam("id3") PathSegment id3) { return Response.ok("quard=" + id + id1 + id2 + id3.getPath()).build(); } @@ -73,10 +73,10 @@ public Response quard(@PathParam("id") double id, @GET @Path("/{id}/{id1}/{id2}/{id3}/{id4}") public Response penta(@PathParam("id") long id, - @PathParam("id1") String id1, - @PathParam("id2") short id2, - @PathParam("id3") boolean id3, - @PathParam("id4") PathSegment id4) + @PathParam("id1") String id1, + @PathParam("id2") short id2, + @PathParam("id3") boolean id3, + @PathParam("id4") PathSegment id4) { return Response.ok("penta=" + id + id1 + id2 + id3 + id4.getPath()). build(); @@ -110,7 +110,7 @@ public Response matrixparamtest(@PathParam("id") PathSegment id) for (Object key : keys) { sb.append(";" + key.toString() + "=" + - matrix.getFirst(key.toString())); + matrix.getFirst(key.toString())); } return Response.ok(sb.toString()).build(); @@ -238,8 +238,8 @@ public String getFromPathSegment(@PathParam("make") String make, @Path("/pathsegments/{model : .+}/year/{year}") @Produces("text/plain") public String getFromMultipleSegments(@PathParam("make") String make, - @PathParam("model") List car, - @PathParam("year") String year) + @PathParam("model") List car, + @PathParam("year") String year) { String output = "A " + year + " " + make; for (PathSegment segment : car) @@ -265,8 +265,8 @@ public String getFromUriInfo(@Context UriInfo info) @GET @Path("/concat/{model: \\D+}{year: \\d+}") @Produces("text/plain") - public String getConcatenatedSegment(@Context UriInfo info, - @PathParam("model") String model, @PathParam("year") String year) { + public String getConcatenatedSegment(@Context UriInfo info, + @PathParam("model") String model, @PathParam("year") String year) { String make = info.getPathParameters().getFirst("make"); String color = info.getQueryParameters().get("color").get(0); return "A " + color + " " + year + " " + make + " " + model; @@ -275,8 +275,8 @@ public String getConcatenatedSegment(@Context UriInfo info, @GET @Path("/concat2/{model: \\$\\D+}{year: \\d+}") @Produces("text/plain") - public String getConcatenated2Segment(@Context UriInfo info, - @PathParam("model") String model, @PathParam("year") String year) { + public String getConcatenated2Segment(@Context UriInfo info, + @PathParam("model") String model, @PathParam("year") String year) { String make = info.getPathParameters().getFirst("make"); String color = info.getQueryParameters().get("color").get(0); return "A " + color + " " + year + " " + make + " " + model; @@ -285,8 +285,8 @@ public String getConcatenated2Segment(@Context UriInfo info, @GET @Path("/concat3/{model: [\\$]glk}") @Produces("text/plain") - public String getConcatenated3Segment(@Context UriInfo info, - @PathParam("model") String model) { + public String getConcatenated3Segment(@Context UriInfo info, + @PathParam("model") String model) { String make = info.getPathParameters().getFirst("make"); String color = info.getQueryParameters().get("color").get(0); return "A " + color + " " + make + " " + model; @@ -295,8 +295,8 @@ public String getConcatenated3Segment(@Context UriInfo info, @GET @Path("/group/{model: [^/()]+?}{ignore: (?:\\(\\))?}") @Produces("text/plain") - public String getGroupSegment(@Context UriInfo info, - @PathParam("model") String model) { + public String getGroupSegment(@Context UriInfo info, + @PathParam("model") String model) { String make = info.getPathParameters().getFirst("make"); String color = info.getQueryParameters().get("color").get(0); return "A " + color + " " + make + " " + model; @@ -358,4 +358,4 @@ public void testCarResource() throws Exception } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/QueryParamAsPrimitiveTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/QueryParamAsPrimitiveTest.java index b623ac5ab4a..ae87c32919e 100755 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/QueryParamAsPrimitiveTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/methodparams/QueryParamAsPrimitiveTest.java @@ -66,7 +66,7 @@ public static void before() throws Exception dispatcher.getRegistry().addPerRequestResource(ResourceQueryPrimitiveArrayDefaultOverride.class); resourceQueryPrimitives = ProxyFactory.create(IResourceQueryPrimitives.class, generateBaseUrl()); resourceQueryPrimitiveWrappers = ProxyFactory.create(IResourceQueryPrimitiveWrappers.class, - generateBaseUrl()); + generateBaseUrl()); resourceQueryPrimitiveList = ProxyFactory.create(IResourceQueryPrimitiveList.class, generateBaseUrl()); resourceQueryPrimitiveArray = ProxyFactory.create(IResourceQueryPrimitiveArray.class, generateBaseUrl()); } @@ -1232,7 +1232,7 @@ public void testGetBoolean() list.add(Boolean.TRUE); resourceQueryPrimitiveList.doGetBoolean(list); boolean[] array = - {true, true, true}; + {true, true, true}; resourceQueryPrimitiveArray.doGetBoolean(array); } @@ -1272,7 +1272,7 @@ public void testGetByte() list.add(new Byte((byte) 127)); resourceQueryPrimitiveList.doGetByte(list); byte[] array = - {(byte) 127, (byte) 127, (byte) 127}; + {(byte) 127, (byte) 127, (byte) 127}; resourceQueryPrimitiveArray.doGetByte(array); } diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/EncodedPathTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/EncodedPathTest.java index 7b8cfa74951..b5a6bc324d1 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/EncodedPathTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/EncodedPathTest.java @@ -85,4 +85,4 @@ public void testEncoded() throws Exception EmbeddedContainer.stop(); } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/InheritanceTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/InheritanceTest.java index a0eb9c2bd9e..bbd776832c5 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/InheritanceTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/finegrain/resource/InheritanceTest.java @@ -55,7 +55,7 @@ public interface ParentResource1 public static class ChildResource1 implements ParentResource1 { static String html_content = - "" + "JAX-RS Test" + + "" + "JAX-RS Test" + "Second"; @GET @@ -105,4 +105,4 @@ public void Test2() throws Exception } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/form/ClientForm.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/form/ClientForm.java index 2eece8bcfd0..2636e1b92ee 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/form/ClientForm.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/form/ClientForm.java @@ -197,4 +197,4 @@ public void setShortValue(Short shortValue) { this.shortValue = shortValue; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/encoding/EncodingTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/encoding/EncodingTest.java index e0ac1229008..6426b688c42 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/encoding/EncodingTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/encoding/EncodingTest.java @@ -49,21 +49,21 @@ public static void teardownContainer() } Character[] RESERVED_CHARACTERS = { - '?', ':', '@', '&', '=', '+', '$', ',' + '?', ':', '@', '&', '=', '+', '$', ',' }; //also includes a-zA-Z0-9 Character[] UNRESERVED_CHARACTERS = { - '-', '_', '.', '!', '~', '*', '\'', '(', ')' + '-', '_', '.', '!', '~', '*', '\'', '(', ')' }; //also includes 0x00-0x1F and 0x7F Character[] EXCLUDED_CHARACTERS = { - ' ', '<', '>', '#', '%', '\"' + ' ', '<', '>', '#', '%', '\"' }; Character[] UNWISE_CHARACTERS = { - '{', '}', '|', '\\', '^', '[', ']', '`' + '{', '}', '|', '\\', '^', '[', ']', '`' }; /** diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/finegrain/client/InputStreamResourceTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/finegrain/client/InputStreamResourceTest.java index b77896b4848..f14fee4765e 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/finegrain/client/InputStreamResourceTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/finegrain/client/InputStreamResourceTest.java @@ -96,7 +96,7 @@ public void testClientResponse() throws Exception Assert.assertEquals("hello", client.getAsString()); Response is = client.getAsInputStream(); Assert.assertEquals("hello", new String(ReadFromStream.readFromStream( - 1024, is.readEntity(InputStream.class)))); + 1024, is.readEntity(InputStream.class)))); is.close(); client.postString("new value"); Assert.assertEquals("new value", client.getAsString()); @@ -105,4 +105,4 @@ public void testClientResponse() throws Exception resteasyClient.close(); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/interceptors/GzipTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/interceptors/GzipTest.java index 8e7b575161e..17985153fba 100755 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/interceptors/GzipTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/interceptors/GzipTest.java @@ -83,7 +83,7 @@ public Response getText(@Context HttpHeaders headers) String acceptEncoding = headers.getRequestHeaders().getFirst(HttpHeaders.ACCEPT_ENCODING); LOG.info(acceptEncoding); Assert.assertEquals("gzip, deflate", acceptEncoding); - */ + */ return Response.ok("HELLO WORLD").header("Content-Encoding", "gzip").build(); } diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/security/BasicAuthTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/security/BasicAuthTest.java index 340b3f43e15..9016aa51e1a 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/security/BasicAuthTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/nextgen/security/BasicAuthTest.java @@ -168,9 +168,9 @@ public static void before() throws Exception { SimpleSecurityDomain domain = new SimpleSecurityDomain(); String[] roles = - {"admin"}; + {"admin"}; String[] basic = - {"user"}; + {"user"}; domain.addUser("bill", "password", roles); domain.addUser("mo", "password", basic); dispatcher = EmbeddedContainer.start("", domain).getDispatcher(); diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/smoke/TestWireInMemorySmoke.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/smoke/TestWireInMemorySmoke.java index 96ef8652371..9a4027d87fc 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/smoke/TestWireInMemorySmoke.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/smoke/TestWireInMemorySmoke.java @@ -97,4 +97,4 @@ public void testLocatingResource() throws Exception registry.removeRegistrations(LocatingResource.class); Assert.assertEquals(oldSize, registry.getSize()); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/tjws/ChunkedEmptyEntityTest.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/tjws/ChunkedEmptyEntityTest.java index 0dfd439e7a8..bd1d38988c9 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/tjws/ChunkedEmptyEntityTest.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/tjws/ChunkedEmptyEntityTest.java @@ -71,33 +71,33 @@ public void testNotModified() throws Exception void _run_test(String method, String path, String status) throws Exception { - // Solicit a reply with response code 204. - Socket s = new Socket("localhost", 8081); - OutputStream os = s.getOutputStream(); - writeString(os, method + " " + path + " HTTP/1.1"); - writeString(os, "Content-Length: 11"); - writeString(os, "Content-Type: text/plain"); - writeString(os, "Host: localhost:8081"); - writeString(os, ""); - os.write("hello world".getBytes()); - os.flush(); - - // Verify response code is correct and that the message - // 1. has no "transfer-encoding" header, and - // 2. consists of status line and headers but no chunks. - InputStream is = s.getInputStream(); - String line = readLine(is); - LOG.info("<<" + line); - assertTrue(line.contains(status)); - line = readLine(is); - while (line != null && is.available() > 0) - { - LOG.info("<<" + line); - int i = line.indexOf(':'); - assertTrue(i > 0); - assertFalse("transfer-encoding".equalsIgnoreCase(line.substring(0, i))); - line = readLine(is); - } + // Solicit a reply with response code 204. + Socket s = new Socket("localhost", 8081); + OutputStream os = s.getOutputStream(); + writeString(os, method + " " + path + " HTTP/1.1"); + writeString(os, "Content-Length: 11"); + writeString(os, "Content-Type: text/plain"); + writeString(os, "Host: localhost:8081"); + writeString(os, ""); + os.write("hello world".getBytes()); + os.flush(); + + // Verify response code is correct and that the message + // 1. has no "transfer-encoding" header, and + // 2. consists of status line and headers but no chunks. + InputStream is = s.getInputStream(); + String line = readLine(is); + LOG.info("<<" + line); + assertTrue(line.contains(status)); + line = readLine(is); + while (line != null && is.available() > 0) + { + LOG.info("<<" + line); + int i = line.indexOf(':'); + assertTrue(i > 0); + assertFalse("transfer-encoding".equalsIgnoreCase(line.substring(0, i))); + line = readLine(is); + } } private void writeString(OutputStream os, String s) throws IOException @@ -111,7 +111,7 @@ private void writeString(OutputStream os, String s) throws IOException */ private String readLine(InputStream in) throws IOException { - int maxLen = 1024; + int maxLen = 1024; StringBuffer buf = new StringBuffer(Math.min(1024, maxLen)); int c; @@ -181,4 +181,4 @@ public Response getNotModified() throws Exception return Response.notModified().build(); } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/xxe/TestSecureProcessing.java b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/xxe/TestSecureProcessing.java index bd7811869f2..318a390eda4 100644 --- a/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/xxe/TestSecureProcessing.java +++ b/resteasy-jaxrs-testsuite/src/test/java/org/jboss/resteasy/test/xxe/TestSecureProcessing.java @@ -150,7 +150,7 @@ public void testSecurityDefaultDTDsFalseExpansionDefault() throws Exception before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.FALSE, MapInclusion.DEFAULT)); doTestFailsFailsPassesFails(); } - + @Test public void testSecurityDefaultDTDsFalseExpansionFalse() throws Exception { @@ -171,7 +171,7 @@ public void testSecurityDefaultDTDsTrueExpansionDefault() throws Exception before(getParameterMap(MapInclusion.DEFAULT, MapInclusion.TRUE, MapInclusion.DEFAULT)); doTestSkipFailsFailsSkip(); } - + @Test public void testSecurityDefaultDTDsTrueExpansionFalse() throws Exception { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/StringParameterUnmarshallerBinder.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/StringParameterUnmarshallerBinder.java index 81539800f9c..2db9020c436 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/StringParameterUnmarshallerBinder.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/StringParameterUnmarshallerBinder.java @@ -20,4 +20,4 @@ public @interface StringParameterUnmarshallerBinder { Class value(); -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/DecoderPrecedence.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/DecoderPrecedence.java index a345b54640e..e928eee794e 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/DecoderPrecedence.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/DecoderPrecedence.java @@ -17,4 +17,4 @@ public @interface DecoderPrecedence { String PRECEDENCE_STRING = "DECODER"; -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/ServerInterceptor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/ServerInterceptor.java index 01d63a7590f..ec479a16714 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/ServerInterceptor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/annotations/interception/ServerInterceptor.java @@ -15,4 +15,4 @@ @Retention(RetentionPolicy.RUNTIME) public @interface ServerInterceptor { -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyConstraintViolation.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyConstraintViolation.java index e2f4c69d85d..be9c011bc75 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyConstraintViolation.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyConstraintViolation.java @@ -7,12 +7,12 @@ import javax.xml.bind.annotation.XmlRootElement; /** -* -* @author Ron Sigal -* @version $Revision: 1.1 $ -* -* Copyright Jun 4, 2013 -*/ + * + * @author Ron Sigal + * @version $Revision: 1.1 $ + * + * Copyright Jun 4, 2013 + */ @XmlRootElement(name="resteasyConstraintViolation") @XmlAccessorType(XmlAccessType.FIELD) public class ResteasyConstraintViolation implements Serializable @@ -37,50 +37,50 @@ public ResteasyConstraintViolation() } /** -* @return type of constraint -*/ + * @return type of constraint + */ public ConstraintType.Type getConstraintType() { return constraintType; } /** -* @return description of element violating constraint -*/ + * @return description of element violating constraint + */ public String getPath() { return path; } /** -* @return description of constraint violation -*/ + * @return description of constraint violation + */ public String getMessage() { return message; } /** -* @return object in violation of constraint -*/ + * @return object in violation of constraint + */ public String getValue() { return value; } /** -* @return String representation of violation -*/ + * @return String representation of violation + */ public String toString() { return "[" + type() + "]\r[" + path + "]\r[" + message + "]\r[" + value + "]\r"; } /** -* @return String form of violation type -*/ + * @return String form of violation type + */ public String type() { return constraintType.toString(); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationException.java index ba9de4d7fb2..d23785c24cb 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationException.java @@ -67,7 +67,7 @@ public ResteasyViolationException(Set> constrai /** * New constructor - * + * * @param constraintViolations set of constraint violations * @param accept list of accept media types */ @@ -80,7 +80,7 @@ public ResteasyViolationException(Set> constrai /** * New constructor - * + * * @param container violation container */ public ResteasyViolationException(SimpleViolationsContainer container) @@ -91,7 +91,7 @@ public ResteasyViolationException(SimpleViolationsContainer container) /** * New constructor - * + * * @param container violation container * @param accept list of accept media types */ diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationExceptionMapper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationExceptionMapper.java index 622c543150c..4e9329efb01 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationExceptionMapper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ResteasyViolationExceptionMapper.java @@ -127,4 +127,4 @@ private MediaType getAcceptMediaType (List accept) } return null; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ViolationReport.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ViolationReport.java index 463e890dcad..5c1391a3490 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ViolationReport.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/api/validation/ViolationReport.java @@ -7,12 +7,12 @@ import javax.xml.bind.annotation.XmlRootElement; /** -* -* @author Ron Sigal -* @version $Revision: 1.1 $ -* -* Copyright July 27, 2013 -*/ + * + * @author Ron Sigal + * @version $Revision: 1.1 $ + * + * Copyright July 27, 2013 + */ @XmlRootElement(name="violationReport") @XmlAccessorType(XmlAccessType.FIELD) public class ViolationReport @@ -107,4 +107,4 @@ public void setReturnValueViolations(ArrayList retu { this.returnValueViolations = returnValueViolations; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequest.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequest.java index 7395d4c23e1..b1f67cc4227 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequest.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequest.java @@ -193,7 +193,7 @@ protected String toString(Object object) if (object instanceof String) return (String) object; StringConverter converter = providerFactory.getStringConverter(object - .getClass()); + .getClass()); if (converter != null) return converter.toString(object); else @@ -275,7 +275,7 @@ public ClientRequest pathParameters(Object... values) public ClientRequest body(String contentType, Object data) { return body(MediaType.valueOf(contentType), data, data.getClass(), null, - null); + null); } public ClientRequest body(MediaType contentType, Object data) @@ -287,7 +287,7 @@ public ClientRequest body(MediaType contentType, Object data, GenericType genericType) { return body(contentType, data, genericType.getType(), genericType - .getGenericType(), null); + .getGenericType(), null); } public ClientRequest body(MediaType contentType, Object data, @@ -428,7 +428,7 @@ public ClientResponse execute() throws Exception if (getExecutionInterceptorList().isEmpty()) { setExecutionInterceptors(providerFactory - .getClientExecutionInterceptorRegistry().bindForList(null, null)); + .getClientExecutionInterceptorRegistry().bindForList(null, null)); } BaseClientResponse response = null; @@ -439,7 +439,7 @@ public ClientResponse execute() throws Exception else { ClientExecutionContextImpl ctx = new ClientExecutionContextImpl( - getExecutionInterceptorList(), executor, this); + getExecutionInterceptorList(), executor, this); response = (BaseClientResponse) ctx.proceed(); } response.setAttributes(attributes); @@ -455,7 +455,7 @@ public ClientResponse execute() throws Exception } public void writeRequestBody(MultivaluedMap headers, - OutputStream outputStream) throws IOException + OutputStream outputStream) throws IOException { if (body == null) { @@ -467,8 +467,8 @@ public void writeRequestBody(MultivaluedMap headers, setWriterInterceptors(providerFactory.getClientWriterInterceptorRegistry().postMatch(null, null)); } new ClientWriterInterceptorContext(getWriterInterceptors(), providerFactory, body, - bodyType, bodyGenericType, bodyAnnotations, bodyContentType, - headers, outputStream, attributes).proceed(); + bodyType, bodyGenericType, bodyAnnotations, bodyContentType, + headers, outputStream, attributes).proceed(); } public ClientResponse get() throws Exception @@ -513,7 +513,7 @@ public ClientResponse get(Class returnType) throws Exception } public ClientResponse get(Class returnType, Type genericType) - throws Exception + throws Exception { BaseClientResponse response = (BaseClientResponse) get(); response.setReturnType(returnType); @@ -547,7 +547,7 @@ public ClientResponse put(Class returnType) throws Exception } public ClientResponse put(Class returnType, Type genericType) - throws Exception + throws Exception { BaseClientResponse response = (BaseClientResponse) put(); response.setReturnType(returnType); @@ -589,7 +589,7 @@ public T postTarget(Class returnType) throws Exception } public ClientResponse post(Class returnType, Type genericType) - throws Exception + throws Exception { BaseClientResponse response = (BaseClientResponse) post(); response.setReturnType(returnType); @@ -634,7 +634,7 @@ public ClientResponse delete(Class returnType) throws Exception } public ClientResponse delete(Class returnType, Type genericType) - throws Exception + throws Exception { BaseClientResponse response = (BaseClientResponse) delete(); response.setReturnType(returnType); @@ -663,7 +663,7 @@ public ClientResponse options(Class returnType) throws Exception } public ClientResponse options(Class returnType, Type genericType) - throws Exception + throws Exception { BaseClientResponse response = (BaseClientResponse) options(); response.setReturnType(returnType); @@ -686,7 +686,7 @@ public ClientResponse httpMethod(String httpMethod) throws Exception } public ClientResponse httpMethod(String method, Class returnType) - throws Exception + throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(returnType); @@ -703,7 +703,7 @@ public ClientResponse httpMethod(String method, Class returnType, } public ClientResponse httpMethod(String method, GenericType type) - throws Exception + throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(type.getType()); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequestFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequestFactory.java index 9411481f2b9..25f62d8c88d 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequestFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ClientRequestFactory.java @@ -69,7 +69,7 @@ private void init(ClientExecutor executor, else this.providerFactory = providerFactory; if (executor == null) - this.executor = new ApacheHttpClient4Executor(); + this.executor = new ApacheHttpClient4Executor(); else this.executor = executor; this.base = base; @@ -83,9 +83,9 @@ public ClientRequestFactory(ClientRequestFactory other) this.applyDefaultInterceptors = other.applyDefaultInterceptors; this.followRedirects = other.followRedirects; other.prefixInterceptors - .copyClientInterceptorsTo(this.prefixInterceptors); + .copyClientInterceptorsTo(this.prefixInterceptors); other.suffixInterceptors - .copyClientInterceptorsTo(this.suffixInterceptors); + .copyClientInterceptorsTo(this.suffixInterceptors); } public URI getBase() @@ -142,7 +142,7 @@ public ClientRequest createRelativeRequest(String uriTemplate) public ClientRequest createRequest(String uriTemplate) { ClientRequest clientRequest = new ClientRequest(new ResteasyUriBuilder() - .uriTemplate(uriTemplate), executor, providerFactory); + .uriTemplate(uriTemplate), executor, providerFactory); if (applyDefaultInterceptors) { ClientInvokerInterceptorFactory.applyDefaultInterceptors( @@ -157,16 +157,16 @@ public ClientRequest createRequest(String uriTemplate) } public T getRelative(String uriTemplate, Class type, Object... params) - throws Exception + throws Exception { return get(base.toString() + uriTemplate, type, params); } public T get(String uriTemplate, Class type, Object... params) - throws Exception + throws Exception { return createRequest(uriTemplate).followRedirects(true).pathParameters( - params).get(type).getEntity(); + params).get(type).getEntity(); } public T createProxy(Class clazz) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyBuilder.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyBuilder.java index 8bfd9417216..09bd2d414a0 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyBuilder.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyBuilder.java @@ -34,140 +34,140 @@ @Deprecated public class ProxyBuilder { - public static ProxyBuilder build(Class iface, URI base) - { - return new ProxyBuilder(iface, base); - } - - public static ProxyBuilder build(Class iface, String base) - { - return new ProxyBuilder(iface, ProxyFactory.createUri(base)); - } - - private final Class iface; - private final URI baseUri; - private ClassLoader loader; - private ClientExecutor executor; - private ResteasyProviderFactory providerFactory; - private EntityExtractorFactory extractorFactory; - private Map requestAttributes; - private MediaType serverConsumes; - private MediaType serverProduces; - - private ProxyBuilder(Class iface, URI base) - { - this.iface = iface; - this.baseUri = base; - this.loader = iface.getClassLoader(); - } - - public ProxyBuilder classloader(ClassLoader cl) - { - this.loader = cl; - return this; - } - - public ProxyBuilder executor(ClientExecutor exec) - { - this.executor = exec; - return this; - } - - public ProxyBuilder providerFactory(ResteasyProviderFactory fact) - { - this.providerFactory = fact; - return this; - } - - public ProxyBuilder extractorFactory(EntityExtractorFactory fact) - { - this.extractorFactory = fact; - return this; - } - - /** shortcut for serverProduces(type).serverConsumes(type) */ - public ProxyBuilder serverMediaType(MediaType type) - { - this.serverProduces = type; - this.serverConsumes = type; - return this; - } - - public ProxyBuilder serverProduces(MediaType type) - { - this.serverProduces = type; - return this; - } - - public ProxyBuilder serverConsumes(MediaType type) - { - this.serverConsumes = type; - return this; - } - - public ProxyBuilder requestAttributes(Map attrs) - { - this.requestAttributes = attrs; - return this; - } - - private static final Class[] cClassArgArray = - { - Class.class - }; - - public T now() - { - if (providerFactory instanceof ProviderFactoryDelegate) - providerFactory = ((ProviderFactoryDelegate) providerFactory).getDelegate(); - - if (executor == null) - executor = ClientRequest.getDefaultExecutor(); - if (providerFactory == null) - providerFactory = ResteasyProviderFactory.getInstance(); - if (extractorFactory == null) - extractorFactory = new DefaultEntityExtractorFactory(); - if (requestAttributes == null) - requestAttributes = Collections.emptyMap(); - - final ProxyConfig config = new ProxyConfig(loader, executor, providerFactory, extractorFactory, requestAttributes, serverConsumes, serverProduces); - return createProxy(iface, baseUri, config); - } - - @SuppressWarnings("unchecked") - public static T createProxy(final Class iface, URI baseUri, final ProxyConfig config) - { - HashMap methodMap = new HashMap(); - for (Method method : iface.getMethods()) - { - // ignore the as method to allow declaration in client interfaces - if (!("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), cClassArgArray))) - { - MethodInvoker invoker; - Set httpMethods = IsHttpMethod.getHttpMethods(method); - if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) - { - invoker = new SubResourceInvoker(baseUri, method, config); - } - else - { - invoker = ProxyFactory.createClientInvoker(iface, method, baseUri, config); - } - methodMap.put(method, invoker); - } - } - - Class[] intfs = - { - iface, ResteasyClientProxy.class - }; - - ClientProxy clientProxy = new ClientProxy(methodMap, baseUri, config); - // this is done so that equals and hashCode work ok. Adding the proxy to a - // Collection will cause equals and hashCode to be invoked. The Spring - // infrastructure had some problems without this. - clientProxy.setClazz(iface); - - return (T) Proxy.newProxyInstance(config.getLoader(), intfs, clientProxy); - } + public static ProxyBuilder build(Class iface, URI base) + { + return new ProxyBuilder(iface, base); + } + + public static ProxyBuilder build(Class iface, String base) + { + return new ProxyBuilder(iface, ProxyFactory.createUri(base)); + } + + private final Class iface; + private final URI baseUri; + private ClassLoader loader; + private ClientExecutor executor; + private ResteasyProviderFactory providerFactory; + private EntityExtractorFactory extractorFactory; + private Map requestAttributes; + private MediaType serverConsumes; + private MediaType serverProduces; + + private ProxyBuilder(Class iface, URI base) + { + this.iface = iface; + this.baseUri = base; + this.loader = iface.getClassLoader(); + } + + public ProxyBuilder classloader(ClassLoader cl) + { + this.loader = cl; + return this; + } + + public ProxyBuilder executor(ClientExecutor exec) + { + this.executor = exec; + return this; + } + + public ProxyBuilder providerFactory(ResteasyProviderFactory fact) + { + this.providerFactory = fact; + return this; + } + + public ProxyBuilder extractorFactory(EntityExtractorFactory fact) + { + this.extractorFactory = fact; + return this; + } + + /** shortcut for serverProduces(type).serverConsumes(type) */ + public ProxyBuilder serverMediaType(MediaType type) + { + this.serverProduces = type; + this.serverConsumes = type; + return this; + } + + public ProxyBuilder serverProduces(MediaType type) + { + this.serverProduces = type; + return this; + } + + public ProxyBuilder serverConsumes(MediaType type) + { + this.serverConsumes = type; + return this; + } + + public ProxyBuilder requestAttributes(Map attrs) + { + this.requestAttributes = attrs; + return this; + } + + private static final Class[] cClassArgArray = + { + Class.class + }; + + public T now() + { + if (providerFactory instanceof ProviderFactoryDelegate) + providerFactory = ((ProviderFactoryDelegate) providerFactory).getDelegate(); + + if (executor == null) + executor = ClientRequest.getDefaultExecutor(); + if (providerFactory == null) + providerFactory = ResteasyProviderFactory.getInstance(); + if (extractorFactory == null) + extractorFactory = new DefaultEntityExtractorFactory(); + if (requestAttributes == null) + requestAttributes = Collections.emptyMap(); + + final ProxyConfig config = new ProxyConfig(loader, executor, providerFactory, extractorFactory, requestAttributes, serverConsumes, serverProduces); + return createProxy(iface, baseUri, config); + } + + @SuppressWarnings("unchecked") + public static T createProxy(final Class iface, URI baseUri, final ProxyConfig config) + { + HashMap methodMap = new HashMap(); + for (Method method : iface.getMethods()) + { + // ignore the as method to allow declaration in client interfaces + if (!("as".equals(method.getName()) && Arrays.equals(method.getParameterTypes(), cClassArgArray))) + { + MethodInvoker invoker; + Set httpMethods = IsHttpMethod.getHttpMethods(method); + if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) + { + invoker = new SubResourceInvoker(baseUri, method, config); + } + else + { + invoker = ProxyFactory.createClientInvoker(iface, method, baseUri, config); + } + methodMap.put(method, invoker); + } + } + + Class[] intfs = + { + iface, ResteasyClientProxy.class + }; + + ClientProxy clientProxy = new ClientProxy(methodMap, baseUri, config); + // this is done so that equals and hashCode work ok. Adding the proxy to a + // Collection will cause equals and hashCode to be invoked. The Spring + // infrastructure had some problems without this. + clientProxy.setClazz(iface); + + return (T) Proxy.newProxyInstance(config.getLoader(), intfs, clientProxy); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyConfig.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyConfig.java index 3c944233c8d..2da0280fbb0 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyConfig.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyConfig.java @@ -16,58 +16,58 @@ @Deprecated public class ProxyConfig { - private final ClassLoader loader; - private final ClientExecutor executor; - private final ResteasyProviderFactory providerFactory; - private final EntityExtractorFactory extractorFactory; - private final Map requestAttributes; - private final MediaType serverConsumes; - private final MediaType serverProduces; + private final ClassLoader loader; + private final ClientExecutor executor; + private final ResteasyProviderFactory providerFactory; + private final EntityExtractorFactory extractorFactory; + private final Map requestAttributes; + private final MediaType serverConsumes; + private final MediaType serverProduces; - public ProxyConfig(ClassLoader loader, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map requestAttributes, MediaType serverConsumes, MediaType serverProduces) - { - super(); - this.loader = loader; - this.executor = executor; - this.providerFactory = providerFactory; - this.extractorFactory = extractorFactory; - this.requestAttributes = requestAttributes; - this.serverConsumes = serverConsumes; - this.serverProduces = serverProduces; - } + public ProxyConfig(ClassLoader loader, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map requestAttributes, MediaType serverConsumes, MediaType serverProduces) + { + super(); + this.loader = loader; + this.executor = executor; + this.providerFactory = providerFactory; + this.extractorFactory = extractorFactory; + this.requestAttributes = requestAttributes; + this.serverConsumes = serverConsumes; + this.serverProduces = serverProduces; + } - public ClassLoader getLoader() - { - return loader; - } + public ClassLoader getLoader() + { + return loader; + } - public ClientExecutor getExecutor() - { - return executor; - } + public ClientExecutor getExecutor() + { + return executor; + } - public ResteasyProviderFactory getProviderFactory() - { - return providerFactory; - } + public ResteasyProviderFactory getProviderFactory() + { + return providerFactory; + } - public EntityExtractorFactory getExtractorFactory() - { - return extractorFactory; - } + public EntityExtractorFactory getExtractorFactory() + { + return extractorFactory; + } - public Map getRequestAttributes() - { - return requestAttributes; - } + public Map getRequestAttributes() + { + return requestAttributes; + } - public MediaType getServerConsumes() - { - return serverConsumes; - } + public MediaType getServerConsumes() + { + return serverConsumes; + } - public MediaType getServerProduces() - { - return serverProduces; - } + public MediaType getServerProduces() + { + return serverProduces; + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyFactory.java index 1e3b99e837e..f82c776d8b7 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/ProxyFactory.java @@ -30,74 +30,74 @@ public class ProxyFactory { - public static T create(Class clazz, String base) - { - return create(clazz, base, ClientRequest.getDefaultExecutor()); - } + public static T create(Class clazz, String base) + { + return create(clazz, base, ClientRequest.getDefaultExecutor()); + } - public static T create(Class clazz, String base, Map requestAttributes) - { - return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), ResteasyProviderFactory.getInstance(), new DefaultEntityExtractorFactory(), requestAttributes); - } + public static T create(Class clazz, String base, Map requestAttributes) + { + return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), ResteasyProviderFactory.getInstance(), new DefaultEntityExtractorFactory(), requestAttributes); + } - public static T create(Class clazz, String base, ResteasyProviderFactory providerFactory, Map requestAttributes) - { - return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), providerFactory, new DefaultEntityExtractorFactory(), requestAttributes); - } + public static T create(Class clazz, String base, ResteasyProviderFactory providerFactory, Map requestAttributes) + { + return create(clazz, createUri(base), ClientRequest.getDefaultExecutor(), providerFactory, new DefaultEntityExtractorFactory(), requestAttributes); + } - public static T create(Class clazz, String base, ClientExecutor client) - { - return create(clazz, createUri(base), client, ResteasyProviderFactory.getInstance()); - } + public static T create(Class clazz, String base, ClientExecutor client) + { + return create(clazz, createUri(base), client, ResteasyProviderFactory.getInstance()); + } - public static URI createUri(String base) - { - try - { - return new URI(base); - } - catch (URISyntaxException e) - { - throw new RuntimeException(e); - } - } + public static URI createUri(String base) + { + try + { + return new URI(base); + } + catch (URISyntaxException e) + { + throw new RuntimeException(e); + } + } - public static T create(Class clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory) - { - return create(clazz, baseUri, executor, providerFactory, new DefaultEntityExtractorFactory()); - } + public static T create(Class clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory) + { + return create(clazz, baseUri, executor, providerFactory, new DefaultEntityExtractorFactory()); + } - public static T create(Class clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory) - { - return create(clazz, baseUri, executor, providerFactory, extractorFactory, new HashMap()); - } + public static T create(Class clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory) + { + return create(clazz, baseUri, executor, providerFactory, extractorFactory, new HashMap()); + } - public static T create(Class clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map requestAttributes) - { - return ProxyBuilder.build(clazz, baseUri).executor(executor).providerFactory(providerFactory).extractorFactory(extractorFactory).requestAttributes(requestAttributes).now(); - } + public static T create(Class clazz, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map requestAttributes) + { + return ProxyBuilder.build(clazz, baseUri).executor(executor).providerFactory(providerFactory).extractorFactory(extractorFactory).requestAttributes(requestAttributes).now(); + } - public static ClientInvoker createClientInvoker(Class clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory) - { - return createClientInvoker(clazz, method, baseUri, executor, providerFactory, extractorFactory, new HashMap()); - } + public static ClientInvoker createClientInvoker(Class clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory) + { + return createClientInvoker(clazz, method, baseUri, executor, providerFactory, extractorFactory, new HashMap()); + } - public static ClientInvoker createClientInvoker(Class clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map requestAttributes) - { - return createClientInvoker(clazz, method, baseUri, new ProxyConfig(null, executor, providerFactory, extractorFactory, requestAttributes, null, null)); - } - - public static ClientInvoker createClientInvoker(Class clazz, Method method, URI baseUri, ProxyConfig config) - { - Set httpMethods = IsHttpMethod.getHttpMethods(method); - if (httpMethods == null || httpMethods.size() != 1) - { - throw new RuntimeException(Messages.MESSAGES.mustUseOneHttpMethod(method.toString())); - } - ClientInvoker invoker = new ClientInvoker(baseUri, clazz, method, config); - invoker.getAttributes().putAll(config.getRequestAttributes()); - ClientInvokerInterceptorFactory.applyDefaultInterceptors(invoker, config.getProviderFactory(), clazz, method); - invoker.setHttpMethod(httpMethods.iterator().next()); - return invoker; - } + public static ClientInvoker createClientInvoker(Class clazz, Method method, URI baseUri, ClientExecutor executor, ResteasyProviderFactory providerFactory, EntityExtractorFactory extractorFactory, Map requestAttributes) + { + return createClientInvoker(clazz, method, baseUri, new ProxyConfig(null, executor, providerFactory, extractorFactory, requestAttributes, null, null)); + } + + public static ClientInvoker createClientInvoker(Class clazz, Method method, URI baseUri, ProxyConfig config) + { + Set httpMethods = IsHttpMethod.getHttpMethods(method); + if (httpMethods == null || httpMethods.size() != 1) + { + throw new RuntimeException(Messages.MESSAGES.mustUseOneHttpMethod(method.toString())); + } + ClientInvoker invoker = new ClientInvoker(baseUri, clazz, method, config); + invoker.getAttributes().putAll(config.getRequestAttributes()); + ClientInvokerInterceptorFactory.applyDefaultInterceptors(invoker, config.getProviderFactory(), clazz, method); + invoker.setHttpMethod(httpMethods.iterator().next()); + return invoker; + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheFactory.java index 143ae9dfe4b..109e80525ae 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheFactory.java @@ -60,9 +60,9 @@ public void modify(ClientInvoker invoker) * @param cache */ public static void makeCacheable( - ClientInterceptorRepository interceptorRepository, BrowserCache cache) + ClientInterceptorRepository interceptorRepository, BrowserCache cache) { interceptorRepository.getExecutionInterceptorList().addFirst( - new CacheInterceptor(cache)); + new CacheInterceptor(cache)); } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheInterceptor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheInterceptor.java index bb9c8aa2d37..e17ac6cc205 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheInterceptor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/CacheInterceptor.java @@ -113,7 +113,7 @@ protected ClientResponse handleExpired(ClientExecutionContext ctx, } private ClientResponse cache(ClientRequest request, ClientResponse response) - throws Exception + throws Exception { if (response.getStatus() != 200) return response; return cacheIfPossible(request, (BaseClientResponse) response); @@ -212,7 +212,7 @@ else if (exp != null) MediaType mediaType = MediaType.valueOf(contentType); final BrowserCache.Entry entry = cache.put(request.getUri(), mediaType, - response.getResponseHeaders(), cached, expires, etag, lastModified); + response.getResponseHeaders(), cached, expires, etag, lastModified); response.setStreamFactory(new CachedStreamFactory(entry)); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/LightweightBrowserCache.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/LightweightBrowserCache.java index edda7c4cfc3..f1b46db88d8 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/LightweightBrowserCache.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/LightweightBrowserCache.java @@ -85,8 +85,8 @@ public Entry get(String key, MediaType accept) } public Entry put(String key, MediaType mediaType, - MultivaluedMap headers, byte[] cached, int expires, - String etag, String lastModified) + MultivaluedMap headers, byte[] cached, int expires, + String etag, String lastModified) { Entry previousValue = internalCache.get(key, mediaType); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/MapCache.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/MapCache.java index 8a49b97fcec..aab4df0bffa 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/MapCache.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/cache/MapCache.java @@ -90,8 +90,8 @@ public Entry put(CacheEntry cacheEntry) } public Entry put(String key, MediaType mediaType, - MultivaluedMap headers, byte[] cached, int expires, - String etag, String lastModified) + MultivaluedMap headers, byte[] cached, int expires, + String etag, String lastModified) { return put(new CacheEntry(key, headers, cached, expires, etag, lastModified, mediaType)); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/BaseClientResponse.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/BaseClientResponse.java index 03df2a3d46a..5157694d106 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/BaseClientResponse.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/BaseClientResponse.java @@ -332,10 +332,10 @@ public void resetStream() { try { - if (this.streamFactory.getInputStream().markSupported()) - { - this.streamFactory.getInputStream().reset(); - } + if (this.streamFactory.getInputStream().markSupported()) + { + this.streamFactory.getInputStream().reset(); + } } catch (IOException e) { @@ -372,7 +372,7 @@ private Annotation[] getAnnotations(Class type, Type genericType) return this.annotations; } return (this.returnType == type && this.genericReturnType == genericType) ? this.annotations - : null; + : null; } @Override diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInterceptorRepositoryImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInterceptorRepositoryImpl.java index dce68a37a48..46f7ec60bef 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInterceptorRepositoryImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInterceptorRepositoryImpl.java @@ -26,9 +26,9 @@ private enum InterceptorType { MessageBodyReader(ReaderInterceptor.class), MessageBodyWriter( - WriterInterceptor.class), + WriterInterceptor.class), ClientExecution( - ClientExecutionInterceptor.class); + ClientExecutionInterceptor.class); Class clazz; @@ -71,29 +71,29 @@ private T[] getArray(Class type) { LinkedList interceptors = getInterceptors(type); return (T[]) interceptors.toArray((T[]) Array.newInstance(type, - interceptors.size())); + interceptors.size())); } protected void setReaderInterceptors( - ReaderInterceptor[] readerInterceptors) + ReaderInterceptor[] readerInterceptors) { setData(InterceptorType.MessageBodyReader, readerInterceptors); } protected void setWriterInterceptors( - WriterInterceptor[] writerInterceptors) + WriterInterceptor[] writerInterceptors) { setData(InterceptorType.MessageBodyWriter, writerInterceptors); } protected void setExecutionInterceptors( - ClientExecutionInterceptor[] executionInterceptors) + ClientExecutionInterceptor[] executionInterceptors) { setData(InterceptorType.ClientExecution, executionInterceptors); } protected void setExecutionInterceptors( - Collection executionInterceptorList) + Collection executionInterceptorList) { setData(InterceptorType.ClientExecution, executionInterceptorList); } @@ -116,14 +116,14 @@ public LinkedList getExecutionInterceptorList() protected LinkedList getInterceptors(Class clazz) { InterceptorType interceptorType = InterceptorType - .getInterceptorTypeFor(clazz); + .getInterceptorTypeFor(clazz); if (interceptorType == null) return null; return getInterceptors(interceptorType); } protected synchronized LinkedList getInterceptors( - InterceptorType interceptorType) + InterceptorType interceptorType) { LinkedList interceptors = interceptorLists.get(interceptorType); if (interceptors == null) @@ -148,7 +148,7 @@ private void setData(InterceptorType type, Collection newList) public void copyClientInterceptorsTo(ClientInterceptorRepositoryImpl copyTo) { for (Entry> entry : interceptorLists - .entrySet()) + .entrySet()) { LinkedList copyToInterceptors = copyTo.getInterceptors(entry.getKey()); LinkedList copyFromInterceptors = this.getInterceptors(entry.getKey()); @@ -159,7 +159,7 @@ public void copyClientInterceptorsTo(ClientInterceptorRepositoryImpl copyTo) public void prefixClientInterceptorsTo(ClientInterceptorRepositoryImpl copyTo) { for (Entry> entry : interceptorLists - .entrySet()) + .entrySet()) { LinkedList copyToInterceptors = copyTo.getInterceptors(entry.getKey()); LinkedList copyFromInterceptors = this.getInterceptors(entry.getKey()); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvoker.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvoker.java index 01636c46435..324518789e4 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvoker.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvoker.java @@ -50,7 +50,7 @@ public class ClientInvoker extends ClientInterceptorRepositoryImpl implements Me public ClientInvoker(URI baseUri, Class declaring, Method method, ResteasyProviderFactory providerFactory, ClientExecutor executor, EntityExtractorFactory extractorFactory) { - this(baseUri, declaring, method, new ProxyConfig(null, executor, providerFactory, extractorFactory, null, null, null)); + this(baseUri, declaring, method, new ProxyConfig(null, executor, providerFactory, extractorFactory, null, null, null)); } public ClientInvoker(URI baseUri, Class declaring, Method method, ProxyConfig config) @@ -174,4 +174,4 @@ public void followRedirects() { setFollowRedirects(true); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvokerInterceptorFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvokerInterceptorFactory.java index 11fe19fd982..063c1a422f2 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvokerInterceptorFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientInvokerInterceptorFactory.java @@ -8,24 +8,24 @@ public class ClientInvokerInterceptorFactory { public static void applyDefaultInterceptors( - ClientInterceptorRepositoryImpl repository, - ResteasyProviderFactory providerFactory) + ClientInterceptorRepositoryImpl repository, + ResteasyProviderFactory providerFactory) { applyDefaultInterceptors(repository, providerFactory, null, null); } public static void applyDefaultInterceptors( - ClientInterceptorRepositoryImpl repository, - ResteasyProviderFactory providerFactory, Class declaring, Method method) + ClientInterceptorRepositoryImpl repository, + ResteasyProviderFactory providerFactory, Class declaring, Method method) { repository.setReaderInterceptors(providerFactory - .getClientReaderInterceptorRegistry().postMatch(declaring, + .getClientReaderInterceptorRegistry().postMatch(declaring, method)); repository.setWriterInterceptors(providerFactory - .getClientWriterInterceptorRegistry().postMatch(declaring, + .getClientWriterInterceptorRegistry().postMatch(declaring, method)); repository.setExecutionInterceptors(providerFactory - .getClientExecutionInterceptorRegistry().bind(declaring, method)); + .getClientExecutionInterceptorRegistry().bind(declaring, method)); } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientProxy.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientProxy.java index 96f1a6dea83..c88adc9af3d 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientProxy.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/ClientProxy.java @@ -15,31 +15,31 @@ */ public class ClientProxy implements InvocationHandler { - private Map methodMap; - private Class clazz; - private final URI base; - private final ProxyConfig config; + private Map methodMap; + private Class clazz; + private final URI base; + private final ProxyConfig config; - public ClientProxy(Map methodMap, URI base, ProxyConfig config) - { - super(); - this.methodMap = methodMap; - this.base = base; - this.config = config; - } + public ClientProxy(Map methodMap, URI base, ProxyConfig config) + { + super(); + this.methodMap = methodMap; + this.base = base; + this.config = config; + } - public Class getClazz() - { - return clazz; - } + public Class getClazz() + { + return clazz; + } - public void setClazz(Class clazz) - { - this.clazz = clazz; - } + public void setClazz(Class clazz) + { + this.clazz = clazz; + } - public Object invoke(Object o, Method method, Object[] args) - throws Throwable + public Object invoke(Object o, Method method, Object[] args) + throws Throwable { // equals and hashCode were added for cases where the proxy is added to // collections. The Spring transaction management, for example, adds @@ -70,15 +70,15 @@ else if (method.getName().equals("applyClientInvokerModifier")) ClientInvokerModifier modifier = (ClientInvokerModifier) args[0]; for (MethodInvoker invoker : methodMap.values()) { - if(invoker instanceof ClientInvoker) - modifier.modify((ClientInvoker)invoker); + if(invoker instanceof ClientInvoker) + modifier.modify((ClientInvoker)invoker); } return null; } else if(method.getName().equals("as") && args.length == 1 && args[0] instanceof Class) { - return ProxyBuilder.createProxy((Class)args[0], base, config); + return ProxyBuilder.createProxy((Class)args[0], base, config); } } @@ -89,27 +89,27 @@ else if(method.getName().equals("as") && args.length == 1 && args[0] instanceof return clientInvoker.invoke(args); } - @Override - public boolean equals(Object obj) - { - if (obj == null || !(obj instanceof ClientProxy)) - return false; - ClientProxy other = (ClientProxy) obj; - if (other == this) - return true; - if (other.clazz != this.clazz) - return false; - return super.equals(obj); - } + @Override + public boolean equals(Object obj) + { + if (obj == null || !(obj instanceof ClientProxy)) + return false; + ClientProxy other = (ClientProxy) obj; + if (other == this) + return true; + if (other.clazz != this.clazz) + return false; + return super.equals(obj); + } - @Override - public int hashCode() - { - return clazz.hashCode(); - } + @Override + public int hashCode() + { + return clazz.hashCode(); + } - public String toString() - { - return "Client Proxy for :" + clazz.getName(); - } + public String toString() + { + return "Client Proxy for :" + clazz.getName(); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/MethodInvoker.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/MethodInvoker.java index 0d91829c689..010e5b6864b 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/MethodInvoker.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/MethodInvoker.java @@ -2,5 +2,5 @@ public interface MethodInvoker { - Object invoke(Object[] args); + Object invoke(Object[] args); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SelfExpandingBufferredInputStream.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SelfExpandingBufferredInputStream.java index 800a1fd3d41..1e61884fb4a 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SelfExpandingBufferredInputStream.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SelfExpandingBufferredInputStream.java @@ -112,4 +112,4 @@ public int getMarkPos() { return markpos; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SubResourceInvoker.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SubResourceInvoker.java index e51a703b6f0..3a2e7b1f575 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SubResourceInvoker.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/SubResourceInvoker.java @@ -12,44 +12,44 @@ public class SubResourceInvoker implements MethodInvoker { - final ProxyConfig config; - final Class iface; - final String base; - final String format; - - public SubResourceInvoker(URI uri, Method method, ProxyConfig config) - { - String base = uri.toString(); - if (!base.endsWith("/")) - base = base + "/"; - this.base = base; - this.iface = method.getReturnType(); - this.config = config; - String path = method.getAnnotation(Path.class).value(); - if (path.startsWith("/")) - path = path.substring(1); - Annotation[][] params = method.getParameterAnnotations(); - int index = 1; - for (Annotation[] param : params) - { - for (Annotation a : param) - { - if (a instanceof PathParam) - { - String name = ((PathParam) a).value(); - path = path.replaceFirst("\\{" + name + "(\\s)*(:.*)?\\}", "%" + index + "\\$s"); - break; - } - } - index++; - } - this.format = path; - } + final ProxyConfig config; + final Class iface; + final String base; + final String format; - @Override - public Object invoke(Object[] args) - { - String path = String.format(format, args); - return ProxyBuilder.createProxy(iface, ProxyFactory.createUri(base + path), config); - } + public SubResourceInvoker(URI uri, Method method, ProxyConfig config) + { + String base = uri.toString(); + if (!base.endsWith("/")) + base = base + "/"; + this.base = base; + this.iface = method.getReturnType(); + this.config = config; + String path = method.getAnnotation(Path.class).value(); + if (path.startsWith("/")) + path = path.substring(1); + Annotation[][] params = method.getParameterAnnotations(); + int index = 1; + for (Annotation[] param : params) + { + for (Annotation a : param) + { + if (a instanceof PathParam) + { + String name = ((PathParam) a).value(); + path = path.replaceFirst("\\{" + name + "(\\s)*(:.*)?\\}", "%" + index + "\\$s"); + break; + } + } + index++; + } + this.format = path; + } + + @Override + public Object invoke(Object[] args) + { + String path = String.format(format, args); + return ProxyBuilder.createProxy(iface, ProxyFactory.createUri(base + path), config); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/ApacheHttpClient4Executor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/ApacheHttpClient4Executor.java index 31861ab39bd..34208feca23 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/ApacheHttpClient4Executor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/ApacheHttpClient4Executor.java @@ -135,7 +135,7 @@ public ApacheHttpClient4Executor(HttpClient httpClient, HttpContext httpContext) */ public int getResponseBufferSize() { - return responseBufferSize; + return responseBufferSize; } /** @@ -146,7 +146,7 @@ public int getResponseBufferSize() */ public void setResponseBufferSize(int responseBufferSize) { - this.responseBufferSize = responseBufferSize; + this.responseBufferSize = responseBufferSize; } public HttpClient getHttpClient() @@ -165,7 +165,7 @@ public void setHttpContext(HttpContext httpContext) } public static CaseInsensitiveMap extractHeaders( - HttpResponse response) + HttpResponse response) { final CaseInsensitiveMap headers = new CaseInsensitiveMap(); @@ -439,7 +439,7 @@ protected HttpEntity buildEntity(final ClientRequest request) throws IOException private DeferredFileOutputStream writeRequestBodyToOutputStream(final ClientRequest request) throws IOException { DeferredFileOutputStream memoryManagedOutStream = - new DeferredFileOutputStream(this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(), + new DeferredFileOutputStream(this.fileUploadInMemoryThresholdLimit * getMemoryUnitMultiplier(), getTempfilePrefix(), ".tmp", this.fileUploadTempFileDir); request.writeRequestBody(request.getHeadersAsObjects(), memoryManagedOutStream); memoryManagedOutStream.close(); @@ -628,4 +628,4 @@ private enum MemoryUnit */ GB } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/InMemoryClientExecutor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/InMemoryClientExecutor.java index 4328968d6ed..1764ce57dbc 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/InMemoryClientExecutor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/InMemoryClientExecutor.java @@ -74,7 +74,7 @@ public ClientRequest createRequest(UriBuilder uriBuilder) public ClientResponse execute(ClientRequest request) throws Exception { MockHttpRequest mockHttpRequest = MockHttpRequest.create(request.getHttpMethod(), new URI(request.getUri()), - baseUri); + baseUri); final MockHttpResponse mockResponse = new MockHttpResponse(); mockHttpRequest.setAsynchronousContext(new SynchronousExecutionContext((SynchronousDispatcher)dispatcher, mockHttpRequest, mockResponse)); loadHttpMethod(request, mockHttpRequest); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/URLConnectionClientExecutor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/URLConnectionClientExecutor.java index add86135080..fecb45c3293 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/URLConnectionClientExecutor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/executors/URLConnectionClientExecutor.java @@ -107,12 +107,12 @@ public void close() } private MultivaluedMap getHeaders( - final HttpURLConnection connection) + final HttpURLConnection connection) { MultivaluedMap headers = new CaseInsensitiveMap(); for (Entry> header : connection.getHeaderFields() - .entrySet()) + .entrySet()) { if (header.getKey() != null) for (String value : header.getValue()) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/extractors/BodyEntityExtractor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/extractors/BodyEntityExtractor.java index 755c559c224..cba34594986 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/extractors/BodyEntityExtractor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/extractors/BodyEntityExtractor.java @@ -81,4 +81,4 @@ public Object extractEntity(ClientRequestContext context, Object... args) } throw new RuntimeException(Messages.MESSAGES.shouldBeUnreachable()); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/ClientMarshallerFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/ClientMarshallerFactory.java index cee597df7cb..7b965a5fcab 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/ClientMarshallerFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/ClientMarshallerFactory.java @@ -27,13 +27,13 @@ public class ClientMarshallerFactory { - public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory) - { - return createMarshallers(declaringClass, method, providerFactory, null); - } - - public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory, MediaType defaultConsumes) - { + public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory) + { + return createMarshallers(declaringClass, method, providerFactory, null); + } + + public static Marshaller[] createMarshallers(Class declaringClass, Method method, ResteasyProviderFactory providerFactory, MediaType defaultConsumes) + { Marshaller[] params = new Marshaller[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { @@ -46,18 +46,18 @@ public static Marshaller[] createMarshallers(Class declaringClass, Method method return params; } - public static Marshaller createMarshaller(Class declaring, - ResteasyProviderFactory providerFactory, Class type, - Annotation[] annotations, Type genericType, AccessibleObject target, - boolean ignoreBody) - { - return createMarshaller(declaring, providerFactory, type, annotations, genericType, target, null, ignoreBody); - } - - public static Marshaller createMarshaller(Class declaring, - ResteasyProviderFactory providerFactory, Class type, - Annotation[] annotations, Type genericType, AccessibleObject target, MediaType defaultConsumes, - boolean ignoreBody) + public static Marshaller createMarshaller(Class declaring, + ResteasyProviderFactory providerFactory, Class type, + Annotation[] annotations, Type genericType, AccessibleObject target, + boolean ignoreBody) + { + return createMarshaller(declaring, providerFactory, type, annotations, genericType, target, null, ignoreBody); + } + + public static Marshaller createMarshaller(Class declaring, + ResteasyProviderFactory providerFactory, Class type, + Annotation[] annotations, Type genericType, AccessibleObject target, MediaType defaultConsumes, + boolean ignoreBody) { Marshaller marshaller = null; @@ -70,50 +70,50 @@ public static Marshaller createMarshaller(Class declaring, // Form form; boolean isEncoded = FindAnnotation.findAnnotation(annotations, - Encoded.class) != null; + Encoded.class) != null; if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) { marshaller = new QueryParamMarshaller(query.value()); } else if ((header = FindAnnotation.findAnnotation(annotations, - HeaderParam.class)) != null) + HeaderParam.class)) != null) { marshaller = new HeaderParamMarshaller(header.value()); } else if ((cookie = FindAnnotation.findAnnotation(annotations, - CookieParam.class)) != null) + CookieParam.class)) != null) { marshaller = new CookieParamMarshaller(cookie.value()); } else if ((uriParam = FindAnnotation.findAnnotation(annotations, - PathParam.class)) != null) + PathParam.class)) != null) { marshaller = new PathParamMarshaller(uriParam.value(), isEncoded, providerFactory); } else if ((matrix = FindAnnotation.findAnnotation(annotations, - MatrixParam.class)) != null) + MatrixParam.class)) != null) { marshaller = new MatrixParamMarshaller(matrix.value()); } else if ((formParam = FindAnnotation.findAnnotation(annotations, - FormParam.class)) != null) + FormParam.class)) != null) { marshaller = new FormParamMarshaller(formParam.value()); } else if ((/* form = */FindAnnotation.findAnnotation(annotations, - Form.class)) != null) + Form.class)) != null) { marshaller = new FormMarshaller(type, providerFactory); } else if ((/* form = */FindAnnotation.findAnnotation(annotations, - BeanParam.class)) != null) + BeanParam.class)) != null) { marshaller = new FormMarshaller(type, providerFactory); } else if ((FindAnnotation.findAnnotation(annotations, - Context.class)) != null) + Context.class)) != null) { marshaller = new NOOPMarshaller(); } @@ -129,8 +129,7 @@ else if (FindAnnotation.findAnnotation(annotations, ClientURI.class) != null) else if (!ignoreBody) { MediaType mediaType = MediaTypeHelper.getConsumes(declaring, target); - if(mediaType == null) - mediaType = defaultConsumes; + if(mediaType == null) mediaType = defaultConsumes; if (mediaType == null) { throw new RuntimeException(Messages.MESSAGES.mustDefineConsumes()); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormMarshaller.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormMarshaller.java index e0ea617167c..f4f20e66b33 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormMarshaller.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormMarshaller.java @@ -51,7 +51,7 @@ public FormMarshaller(Class clazz, ResteasyProviderFactory factory) } public static long methodHash(Method method) - throws Exception + throws Exception { Class[] parameterTypes = method.getParameterTypes(); StringBuilder methodDesc = new StringBuilder(method.getName()).append("("); @@ -64,7 +64,7 @@ public static long methodHash(Method method) } public static long createHash(String methodDesc) - throws Exception + throws Exception { long hash = 0; ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512); @@ -224,4 +224,4 @@ public void build(ClientRequest request, Object object) } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormParamMarshaller.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormParamMarshaller.java index dd4acd21608..c299d99ca55 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormParamMarshaller.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/FormParamMarshaller.java @@ -77,4 +77,4 @@ else if (componentType.equals(double.class)) request.formParameter(paramName, object); } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/HeaderParamMarshaller.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/HeaderParamMarshaller.java index 7d2a8d12aa2..442a345e8fa 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/HeaderParamMarshaller.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/HeaderParamMarshaller.java @@ -76,4 +76,4 @@ else if (componentType.equals(double.class)) request.header(paramName, object); } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/Marshaller.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/Marshaller.java index aa2f1813e9e..643ac6e9f22 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/Marshaller.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/Marshaller.java @@ -9,4 +9,4 @@ public interface Marshaller { void build(ClientRequest request, Object target); -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MatrixParamMarshaller.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MatrixParamMarshaller.java index 069d4b0e55d..08db35e2d51 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MatrixParamMarshaller.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MatrixParamMarshaller.java @@ -34,4 +34,4 @@ public void build(ClientRequest request, Object object) } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MessageBodyParameterMarshaller.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MessageBodyParameterMarshaller.java index 465702138ea..d4829b7d774 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MessageBodyParameterMarshaller.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/MessageBodyParameterMarshaller.java @@ -40,4 +40,4 @@ public MediaType getMediaType() return mediaType; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/QueryParamMarshaller.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/QueryParamMarshaller.java index bf8e9c26931..aaec2ea8a49 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/QueryParamMarshaller.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/core/marshallers/QueryParamMarshaller.java @@ -76,4 +76,4 @@ else if (componentType.equals(double.class)) request.queryParameter(paramName, object); } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthChallengeException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthChallengeException.java index 2b7bfb6848c..eb89964b576 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthChallengeException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthChallengeException.java @@ -8,24 +8,24 @@ */ public class ResteasyAuthChallengeException extends ResteasyAuthenticationException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyAuthChallengeException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyAuthChallengeException(String message) - { - super(message); - } - - public ResteasyAuthChallengeException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyAuthChallengeException() + { + } + + public ResteasyAuthChallengeException(String message) + { + super(message); + } + + public ResteasyAuthChallengeException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyAuthChallengeException(Throwable cause) - { - super(cause); - } + public ResteasyAuthChallengeException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthenticationException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthenticationException.java index 613434a8281..04fd7de5020 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthenticationException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyAuthenticationException.java @@ -8,24 +8,24 @@ */ public class ResteasyAuthenticationException extends ResteasyProtocolException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyAuthenticationException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyAuthenticationException(String message) - { - super(message); - } - - public ResteasyAuthenticationException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyAuthenticationException() + { + } + + public ResteasyAuthenticationException(String message) + { + super(message); + } + + public ResteasyAuthenticationException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyAuthenticationException(Throwable cause) - { - super(cause); - } + public ResteasyAuthenticationException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCircularRedirectException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCircularRedirectException.java index 927d53e065a..b3f457bcf21 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCircularRedirectException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCircularRedirectException.java @@ -8,24 +8,24 @@ */ public class ResteasyCircularRedirectException extends ResteasyRedirectException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyCircularRedirectException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyCircularRedirectException(String message) - { - super(message); - } - - public ResteasyCircularRedirectException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyCircularRedirectException() + { + } + + public ResteasyCircularRedirectException(String message) + { + super(message); + } + + public ResteasyCircularRedirectException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyCircularRedirectException(Throwable cause) - { - super(cause); - } + public ResteasyCircularRedirectException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientException.java index 1f879e7a934..ad195a21db9 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientException.java @@ -8,24 +8,24 @@ */ public class ResteasyClientException extends RuntimeException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyClientException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyClientException(String message) - { - super(message); - } - - public ResteasyClientException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyClientException() + { + } + + public ResteasyClientException(String message) + { + super(message); + } + + public ResteasyClientException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyClientException(Throwable cause) - { - super(cause); - } + public ResteasyClientException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientProtocolException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientProtocolException.java index 553b5bc32df..c8fb6f674d9 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientProtocolException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyClientProtocolException.java @@ -8,24 +8,24 @@ */ public class ResteasyClientProtocolException extends ResteasyIOException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyClientProtocolException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyClientProtocolException(String message) - { - super(message); - } - - public ResteasyClientProtocolException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyClientProtocolException() + { + } + + public ResteasyClientProtocolException(String message) + { + super(message); + } + + public ResteasyClientProtocolException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyClientProtocolException(Throwable cause) - { - super(cause); - } + public ResteasyClientProtocolException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectTimeoutException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectTimeoutException.java index d965292720a..d56c1ebcaca 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectTimeoutException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectTimeoutException.java @@ -8,24 +8,24 @@ */ public class ResteasyConnectTimeoutException extends ResteasyIOException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyConnectTimeoutException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyConnectTimeoutException(String message) - { - super(message); - } - - public ResteasyConnectTimeoutException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyConnectTimeoutException() + { + } + + public ResteasyConnectTimeoutException(String message) + { + super(message); + } + + public ResteasyConnectTimeoutException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyConnectTimeoutException(Throwable cause) - { - super(cause); - } + public ResteasyConnectTimeoutException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionClosedException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionClosedException.java index 322e07aa963..9d648806006 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionClosedException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionClosedException.java @@ -8,24 +8,24 @@ */ public class ResteasyConnectionClosedException extends ResteasyIOException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyConnectionClosedException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyConnectionClosedException(String message) - { - super(message); - } - - public ResteasyConnectionClosedException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyConnectionClosedException() + { + } + + public ResteasyConnectionClosedException(String message) + { + super(message); + } + + public ResteasyConnectionClosedException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyConnectionClosedException(Throwable cause) - { - super(cause); - } + public ResteasyConnectionClosedException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionPoolTimeoutException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionPoolTimeoutException.java index 2babdd73766..8728ea8719c 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionPoolTimeoutException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyConnectionPoolTimeoutException.java @@ -8,24 +8,24 @@ */ public class ResteasyConnectionPoolTimeoutException extends ResteasyConnectTimeoutException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyConnectionPoolTimeoutException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyConnectionPoolTimeoutException(String message) - { - super(message); - } - - public ResteasyConnectionPoolTimeoutException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyConnectionPoolTimeoutException() + { + } + + public ResteasyConnectionPoolTimeoutException(String message) + { + super(message); + } + + public ResteasyConnectionPoolTimeoutException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyConnectionPoolTimeoutException(Throwable cause) - { - super(cause); - } + public ResteasyConnectionPoolTimeoutException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCookieRestrictionViolationException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCookieRestrictionViolationException.java index 4d6637e24aa..eb82a5b2e0e 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCookieRestrictionViolationException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCookieRestrictionViolationException.java @@ -8,24 +8,24 @@ */ public class ResteasyCookieRestrictionViolationException extends ResteasyMalformedCookieException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyCookieRestrictionViolationException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyCookieRestrictionViolationException(String message) - { - super(message); - } - - public ResteasyCookieRestrictionViolationException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyCookieRestrictionViolationException() + { + } + + public ResteasyCookieRestrictionViolationException(String message) + { + super(message); + } + + public ResteasyCookieRestrictionViolationException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyCookieRestrictionViolationException(Throwable cause) - { - super(cause); - } + public ResteasyCookieRestrictionViolationException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCredentialsNotAvailableException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCredentialsNotAvailableException.java index edbac5102db..112c1ac7ef3 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCredentialsNotAvailableException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyCredentialsNotAvailableException.java @@ -8,24 +8,24 @@ */ public class ResteasyCredentialsNotAvailableException extends ResteasyAuthenticationException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyCredentialsNotAvailableException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyCredentialsNotAvailableException(String message) - { - super(message); - } - - public ResteasyCredentialsNotAvailableException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyCredentialsNotAvailableException() + { + } + + public ResteasyCredentialsNotAvailableException(String message) + { + super(message); + } + + public ResteasyCredentialsNotAvailableException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyCredentialsNotAvailableException(Throwable cause) - { - super(cause); - } + public ResteasyCredentialsNotAvailableException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpContentTooLargeException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpContentTooLargeException.java index f895313cb31..dead554b601 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpContentTooLargeException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpContentTooLargeException.java @@ -8,24 +8,24 @@ */ public class ResteasyHttpContentTooLargeException extends ResteasyHttpException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyHttpContentTooLargeException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyHttpContentTooLargeException(String message) - { - super(message); - } - - public ResteasyHttpContentTooLargeException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyHttpContentTooLargeException() + { + } + + public ResteasyHttpContentTooLargeException(String message) + { + super(message); + } + + public ResteasyHttpContentTooLargeException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyHttpContentTooLargeException(Throwable cause) - { - super(cause); - } + public ResteasyHttpContentTooLargeException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpException.java index 96de9fc3831..a45c9760c2a 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpException.java @@ -8,24 +8,24 @@ */ public class ResteasyHttpException extends ResteasyClientException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyHttpException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyHttpException(String message) - { - super(message); - } - - public ResteasyHttpException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyHttpException() + { + } + + public ResteasyHttpException(String message) + { + super(message); + } + + public ResteasyHttpException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyHttpException(Throwable cause) - { - super(cause); - } + public ResteasyHttpException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpHostConnectException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpHostConnectException.java index 58e9db8438d..1398be7f48f 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpHostConnectException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpHostConnectException.java @@ -8,24 +8,24 @@ */ public class ResteasyHttpHostConnectException extends ResteasyIOException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyHttpHostConnectException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyHttpHostConnectException(String message) - { - super(message); - } - - public ResteasyHttpHostConnectException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyHttpHostConnectException() + { + } + + public ResteasyHttpHostConnectException(String message) + { + super(message); + } + + public ResteasyHttpHostConnectException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyHttpHostConnectException(Throwable cause) - { - super(cause); - } + public ResteasyHttpHostConnectException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpRecoverableException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpRecoverableException.java index 57ddf8b3aae..7242af0a66c 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpRecoverableException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyHttpRecoverableException.java @@ -8,24 +8,24 @@ */ public class ResteasyHttpRecoverableException extends ResteasyHttpException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyHttpRecoverableException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyHttpRecoverableException(String message) - { - super(message); - } - - public ResteasyHttpRecoverableException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyHttpRecoverableException() + { + } + + public ResteasyHttpRecoverableException(String message) + { + super(message); + } + + public ResteasyHttpRecoverableException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyHttpRecoverableException(Throwable cause) - { - super(cause); - } + public ResteasyHttpRecoverableException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyIOException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyIOException.java index 27d64b418d7..3db563bf709 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyIOException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyIOException.java @@ -8,24 +8,24 @@ */ public class ResteasyIOException extends ResteasyClientException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyIOException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyIOException(String message) - { - super(message); - } - - public ResteasyIOException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyIOException() + { + } + + public ResteasyIOException(String message) + { + super(message); + } + + public ResteasyIOException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyIOException(Throwable cause) - { - super(cause); - } + public ResteasyIOException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidCredentialsException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidCredentialsException.java index e3c617c1942..1db36d880a0 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidCredentialsException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidCredentialsException.java @@ -8,24 +8,24 @@ */ public class ResteasyInvalidCredentialsException extends ResteasyAuthenticationException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyInvalidCredentialsException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyInvalidCredentialsException(String message) - { - super(message); - } - - public ResteasyInvalidCredentialsException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyInvalidCredentialsException() + { + } + + public ResteasyInvalidCredentialsException(String message) + { + super(message); + } + + public ResteasyInvalidCredentialsException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyInvalidCredentialsException(Throwable cause) - { - super(cause); - } + public ResteasyInvalidCredentialsException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidRedirectLocationException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidRedirectLocationException.java index 47ae1498074..6c8d8cfb26f 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidRedirectLocationException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyInvalidRedirectLocationException.java @@ -8,24 +8,24 @@ */ public class ResteasyInvalidRedirectLocationException extends ResteasyRedirectException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyInvalidRedirectLocationException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyInvalidRedirectLocationException(String message) - { - super(message); - } - - public ResteasyInvalidRedirectLocationException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyInvalidRedirectLocationException() + { + } + + public ResteasyInvalidRedirectLocationException(String message) + { + super(message); + } + + public ResteasyInvalidRedirectLocationException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyInvalidRedirectLocationException(Throwable cause) - { - super(cause); - } + public ResteasyInvalidRedirectLocationException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChallengeException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChallengeException.java index 558531284f9..94bfeb7e1e5 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChallengeException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChallengeException.java @@ -8,24 +8,24 @@ */ public class ResteasyMalformedChallengeException extends ResteasyProtocolException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyMalformedChallengeException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyMalformedChallengeException(String message) - { - super(message); - } - - public ResteasyMalformedChallengeException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyMalformedChallengeException() + { + } + + public ResteasyMalformedChallengeException(String message) + { + super(message); + } + + public ResteasyMalformedChallengeException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyMalformedChallengeException(Throwable cause) - { - super(cause); - } + public ResteasyMalformedChallengeException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChunkCodingException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChunkCodingException.java index 251a18ce814..bee2700cac2 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChunkCodingException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedChunkCodingException.java @@ -8,24 +8,24 @@ */ public class ResteasyMalformedChunkCodingException extends ResteasyIOException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyMalformedChunkCodingException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyMalformedChunkCodingException(String message) - { - super(message); - } - - public ResteasyMalformedChunkCodingException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyMalformedChunkCodingException() + { + } + + public ResteasyMalformedChunkCodingException(String message) + { + super(message); + } + + public ResteasyMalformedChunkCodingException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyMalformedChunkCodingException(Throwable cause) - { - super(cause); - } + public ResteasyMalformedChunkCodingException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedCookieException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedCookieException.java index d299d830cc1..2d786b697c0 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedCookieException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMalformedCookieException.java @@ -8,24 +8,24 @@ */ public class ResteasyMalformedCookieException extends ResteasyProtocolException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyMalformedCookieException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyMalformedCookieException(String message) - { - super(message); - } - - public ResteasyMalformedCookieException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyMalformedCookieException() + { + } + + public ResteasyMalformedCookieException(String message) + { + super(message); + } + + public ResteasyMalformedCookieException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyMalformedCookieException(Throwable cause) - { - super(cause); - } + public ResteasyMalformedCookieException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMethodNotSupportedException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMethodNotSupportedException.java index d716a06c196..ec64bf47cfe 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMethodNotSupportedException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyMethodNotSupportedException.java @@ -8,24 +8,24 @@ */ public class ResteasyMethodNotSupportedException extends ResteasyHttpException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyMethodNotSupportedException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyMethodNotSupportedException(String message) - { - super(message); - } - - public ResteasyMethodNotSupportedException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyMethodNotSupportedException() + { + } + + public ResteasyMethodNotSupportedException(String message) + { + super(message); + } + + public ResteasyMethodNotSupportedException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyMethodNotSupportedException(Throwable cause) - { - super(cause); - } + public ResteasyMethodNotSupportedException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNTLMEngineException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNTLMEngineException.java index ae460464b7e..6f3a835f0be 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNTLMEngineException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNTLMEngineException.java @@ -8,24 +8,24 @@ */ public class ResteasyNTLMEngineException extends ResteasyAuthenticationException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyNTLMEngineException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyNTLMEngineException(String message) - { - super(message); - } - - public ResteasyNTLMEngineException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyNTLMEngineException() + { + } + + public ResteasyNTLMEngineException(String message) + { + super(message); + } + + public ResteasyNTLMEngineException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyNTLMEngineException(Throwable cause) - { - super(cause); - } + public ResteasyNTLMEngineException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNoHttpResponseException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNoHttpResponseException.java index 1d95333ab51..dbff74fe4b5 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNoHttpResponseException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNoHttpResponseException.java @@ -8,24 +8,24 @@ */ public class ResteasyNoHttpResponseException extends ResteasyIOException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyNoHttpResponseException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyNoHttpResponseException(String message) - { - super(message); - } - - public ResteasyNoHttpResponseException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyNoHttpResponseException() + { + } + + public ResteasyNoHttpResponseException(String message) + { + super(message); + } + + public ResteasyNoHttpResponseException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyNoHttpResponseException(Throwable cause) - { - super(cause); - } + public ResteasyNoHttpResponseException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNonRepeatableRequestException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNonRepeatableRequestException.java index f92792d089f..a4aec9ebe8f 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNonRepeatableRequestException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyNonRepeatableRequestException.java @@ -8,24 +8,24 @@ */ public class ResteasyNonRepeatableRequestException extends ResteasyProtocolException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyNonRepeatableRequestException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyNonRepeatableRequestException(String message) - { - super(message); - } - - public ResteasyNonRepeatableRequestException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyNonRepeatableRequestException() + { + } + + public ResteasyNonRepeatableRequestException(String message) + { + super(message); + } + + public ResteasyNonRepeatableRequestException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyNonRepeatableRequestException(Throwable cause) - { - super(cause); - } + public ResteasyNonRepeatableRequestException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyProtocolException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyProtocolException.java index 77aeef7f089..265df3ac937 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyProtocolException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyProtocolException.java @@ -8,24 +8,24 @@ */ public class ResteasyProtocolException extends ResteasyHttpException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyProtocolException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyProtocolException(String message) - { - super(message); - } - - public ResteasyProtocolException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyProtocolException() + { + } + + public ResteasyProtocolException(String message) + { + super(message); + } + + public ResteasyProtocolException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyProtocolException(Throwable cause) - { - super(cause); - } + public ResteasyProtocolException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyRedirectException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyRedirectException.java index e57a29922f7..0e2c3c01920 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyRedirectException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyRedirectException.java @@ -8,24 +8,24 @@ */ public class ResteasyRedirectException extends ResteasyNonRepeatableRequestException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyRedirectException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyRedirectException(String message) - { - super(message); - } - - public ResteasyRedirectException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyRedirectException() + { + } + + public ResteasyRedirectException(String message) + { + super(message); + } + + public ResteasyRedirectException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyRedirectException(Throwable cause) - { - super(cause); - } + public ResteasyRedirectException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyTunnelRefusedException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyTunnelRefusedException.java index 8d3979e78e2..4318b123baa 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyTunnelRefusedException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyTunnelRefusedException.java @@ -8,24 +8,24 @@ */ public class ResteasyTunnelRefusedException extends ResteasyProtocolException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyTunnelRefusedException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyTunnelRefusedException(String message) - { - super(message); - } - - public ResteasyTunnelRefusedException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyTunnelRefusedException() + { + } + + public ResteasyTunnelRefusedException(String message) + { + super(message); + } + + public ResteasyTunnelRefusedException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyTunnelRefusedException(Throwable cause) - { - super(cause); - } + public ResteasyTunnelRefusedException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyURIException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyURIException.java index a152f31352a..38f59a6651d 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyURIException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyURIException.java @@ -8,24 +8,24 @@ */ public class ResteasyURIException extends ResteasyHttpException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyURIException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyURIException(String message) - { - super(message); - } - - public ResteasyURIException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyURIException() + { + } + + public ResteasyURIException(String message) + { + super(message); + } + + public ResteasyURIException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyURIException(Throwable cause) - { - super(cause); - } + public ResteasyURIException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyUnsupportedHttpVersionException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyUnsupportedHttpVersionException.java index d9d6817b769..ccc1dbd60cf 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyUnsupportedHttpVersionException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/ResteasyUnsupportedHttpVersionException.java @@ -8,24 +8,24 @@ */ public class ResteasyUnsupportedHttpVersionException extends ResteasyProtocolException { - private static final long serialVersionUID = -5711578608757689465L; - - public ResteasyUnsupportedHttpVersionException() - { - } + private static final long serialVersionUID = -5711578608757689465L; - public ResteasyUnsupportedHttpVersionException(String message) - { - super(message); - } - - public ResteasyUnsupportedHttpVersionException(String message, Throwable cause) - { - super(message, cause); - } + public ResteasyUnsupportedHttpVersionException() + { + } + + public ResteasyUnsupportedHttpVersionException(String message) + { + super(message); + } + + public ResteasyUnsupportedHttpVersionException(String message, Throwable cause) + { + super(message, cause); + } - public ResteasyUnsupportedHttpVersionException(Throwable cause) - { - super(cause); - } + public ResteasyUnsupportedHttpVersionException(Throwable cause) + { + super(cause); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/mapper/ClientExceptionMapper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/mapper/ClientExceptionMapper.java index 0d6ac6d3fa0..81171ad7953 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/mapper/ClientExceptionMapper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/client/exception/mapper/ClientExceptionMapper.java @@ -6,7 +6,4 @@ * * Copyright Jul 28, 2012 */ -public interface ClientExceptionMapper -{ - RuntimeException toException(E exception); -} +public interface ClientExceptionMapper { RuntimeException toException(E exception);} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/AbstractCollectionFormInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/AbstractCollectionFormInjector.java index ede582a9c31..2558457220a 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/AbstractCollectionFormInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/AbstractCollectionFormInjector.java @@ -77,7 +77,7 @@ private Set findMatchingPrefixesWithNoneEmptyValues(MultivaluedMap findMatchingPrefixesWithNoneEmptyValues(MultivaluedMap() { - @Override - public ClassLoader run() { - return type.getClassLoader(); - } - }); - } - return Proxy.newProxyInstance(clazzLoader, intfs, new GenericDelegatingProxy()); - } - } + clazzLoader = AccessController.doPrivileged(new PrivilegedAction() { + @Override + public ClassLoader run() { + return type.getClassLoader(); + } + }); + } + return Proxy.newProxyInstance(clazzLoader, intfs, new GenericDelegatingProxy()); + } + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/CookieParamInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/CookieParamInjector.java index b5f9a08747a..6443c21de16 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/CookieParamInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/CookieParamInjector.java @@ -52,4 +52,4 @@ public Object inject() { throw new RuntimeException(Messages.MESSAGES.illegalToInjectCookieParam()); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExceptionHandler.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExceptionHandler.java index 9022442ca57..874c48e10ea 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExceptionHandler.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExceptionHandler.java @@ -115,12 +115,12 @@ protected Response unwrapException(HttpRequest request, Throwable e) Throwable unwrappedException = e.getCause(); /* - * If the response property of the exception does not - * contain an entity and an exception mapping provider - * (see section 4.4) is available for - * WebApplicationException an implementation MUST use the - * provider to create a new Response instance, otherwise - * the response property is used directly. + * If the response property of the exception does not + * contain an entity and an exception mapping provider + * (see section 4.4) is available for + * WebApplicationException an implementation MUST use the + * provider to create a new Response instance, otherwise + * the response property is used directly. */ if (unwrappedException instanceof WebApplicationException) { @@ -229,12 +229,12 @@ else if (e instanceof ReaderException) { } /* - * If the response property of the exception does not - * contain an entity and an exception mapping provider - * (see section 4.4) is available for - * WebApplicationException an implementation MUST use the - * provider to create a new Response instance, otherwise - * the response property is used directly. + * If the response property of the exception does not + * contain an entity and an exception mapping provider + * (see section 4.4) is available for + * WebApplicationException an implementation MUST use the + * provider to create a new Response instance, otherwise + * the response property is used directly. */ if (e instanceof WebApplicationException) { WebApplicationException wae = (WebApplicationException) e; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExtendedCacheControl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExtendedCacheControl.java index d4f3cad4f95..64d22641e1e 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExtendedCacheControl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ExtendedCacheControl.java @@ -11,35 +11,35 @@ */ public class ExtendedCacheControl extends CacheControl { - private boolean _public = false; + private boolean _public = false; - public boolean isPublic() { - return _public; - } + public boolean isPublic() { + return _public; + } - public void setPublic(boolean _public) { - this._public = _public; - } + public void setPublic(boolean _public) { + this._public = _public; + } - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + (_public ? 1231 : 1237); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + (_public ? 1231 : 1237); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - ExtendedCacheControl other = (ExtendedCacheControl) obj; - if (_public != other._public) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + ExtendedCacheControl other = (ExtendedCacheControl) obj; + if (_public != other._public) + return false; + return true; + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/FormParamInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/FormParamInjector.java index 6df6772a2dc..5868031bdd6 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/FormParamInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/FormParamInjector.java @@ -51,4 +51,4 @@ public Object inject() { throw new RuntimeException(Messages.MESSAGES.illegalToInjectFormParam()); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ListFormInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ListFormInjector.java index 754a2ceb907..243184c5310 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ListFormInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ListFormInjector.java @@ -11,40 +11,40 @@ */ public class ListFormInjector extends AbstractCollectionFormInjector { - /** - * Constructor. - * @param collectionType collection type - * @param genericType generic type - * @param prefix prefix - * @param factory provider factory - */ - public ListFormInjector(Class collectionType, Class genericType, String prefix, ResteasyProviderFactory factory) { - super(collectionType, genericType, prefix, Pattern.compile("^" + prefix + "\\[(\\d+)\\]"), factory); - } + /** + * Constructor. + * @param collectionType collection type + * @param genericType generic type + * @param prefix prefix + * @param factory provider factory + */ + public ListFormInjector(Class collectionType, Class genericType, String prefix, ResteasyProviderFactory factory) { + super(collectionType, genericType, prefix, Pattern.compile("^" + prefix + "\\[(\\d+)\\]"), factory); + } - /** - * {@inheritDoc} - * - * @return ArrayList - */ - @Override - protected List createInstance(Class collectionType) { - return new ArrayList(); - } + /** + * {@inheritDoc} + * + * @return ArrayList + */ + @Override + protected List createInstance(Class collectionType) { + return new ArrayList(); + } - /** - * {@inheritDoc} - */ - @SuppressWarnings(value = "unchecked") - @Override - protected void addTo(List collection, String key, Object value) { - int index = Integer.parseInt(key); - int size = collection.size(); - // in case the key doesn't come in sorted order - if (collection.size() <= index) { - for (int i = 0; i < index - size + 1; i++) - collection.add(null); - } - collection.set(index, value); - } -} \ No newline at end of file + /** + * {@inheritDoc} + */ + @SuppressWarnings(value = "unchecked") + @Override + protected void addTo(List collection, String key, Object value) { + int index = Integer.parseInt(key); + int size = collection.size(); + // in case the key doesn't come in sorted order + if (collection.size() <= index) { + for (int i = 0; i < index - size + 1; i++) + collection.add(null); + } + collection.set(index, value); + } +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MapFormInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MapFormInjector.java index 33de3e13337..90463696de6 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MapFormInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MapFormInjector.java @@ -59,4 +59,4 @@ protected void addTo(Map collection, String key, Object value) { collection.put(keyInjector.extractValue(key), value); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MatrixParamInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MatrixParamInjector.java index 7495e470f7f..f83bb2eebdc 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MatrixParamInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MatrixParamInjector.java @@ -63,4 +63,4 @@ public Object inject() { throw new RuntimeException(Messages.MESSAGES.illegalToInjectMatrixParam()); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MessageBodyParameterInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MessageBodyParameterInjector.java index c7e42013a16..b7357605573 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MessageBodyParameterInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/MessageBodyParameterInjector.java @@ -95,7 +95,7 @@ public MessageBodyParameterInjector(Class declaringClass, AccessibleObject targe } this.annotations = annotations; this.interceptors = factory - .getServerReaderInterceptorRegistry().postMatch( + .getServerReaderInterceptorRegistry().postMatch( this.declaringClass, this.target); // this is for when an interceptor is added after the creation of the injector @@ -105,14 +105,14 @@ public MessageBodyParameterInjector(Class declaringClass, AccessibleObject targe public void registryUpdated(JaxrsInterceptorRegistry registry) { this.interceptors = factory - .getServerReaderInterceptorRegistry().postMatch( + .getServerReaderInterceptorRegistry().postMatch( declaringClass, target); } public boolean isFormData(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { if (mediaType.isWildcardType() || mediaType.isWildcardSubtype() || - !mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) return false; + !mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) return false; if (!MultivaluedMap.class.isAssignableFrom(type)) return false; if (genericType == null) return true; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/NoMessageBodyWriterFoundFailure.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/NoMessageBodyWriterFoundFailure.java index fa7baf927ba..d6712867130 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/NoMessageBodyWriterFoundFailure.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/NoMessageBodyWriterFoundFailure.java @@ -12,10 +12,10 @@ public class NoMessageBodyWriterFoundFailure extends LoggableFailure public NoMessageBodyWriterFoundFailure(Class type, MediaType contentType) { super( - String + String .format( "Could not find MessageBodyWriter for response object of type: %s of media type: %s", type.getName(), contentType.toString()), - HttpResponseCodes.SC_INTERNAL_SERVER_ERROR); + HttpResponseCodes.SC_INTERNAL_SERVER_ERROR); } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvoker.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvoker.java index a1b2fdfc8eb..1ad64e3a386 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvoker.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvoker.java @@ -7,6 +7,6 @@ */ public interface PostResourceMethodInvoker { - void invoke(); + void invoke(); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvokers.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvokers.java index a0a2d3d7a8b..695ade9dbc5 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvokers.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PostResourceMethodInvokers.java @@ -11,22 +11,22 @@ */ public class PostResourceMethodInvokers { - private final List invokers; + private final List invokers; - public PostResourceMethodInvokers() { - this.invokers = new ArrayList<>(); - } + public PostResourceMethodInvokers() { + this.invokers = new ArrayList<>(); + } - public List getInvokers() { - return this.invokers; - } + public List getInvokers() { + return this.invokers; + } - public void clear() { - this.invokers.clear(); - } + public void clear() { + this.invokers.clear(); + } - public void addInvokers(PostResourceMethodInvoker... invokers) { - Collections.addAll(this.invokers, invokers); - } + public void addInvokers(PostResourceMethodInvoker... invokers) { + Collections.addAll(this.invokers, invokers); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PrefixedFormInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PrefixedFormInjector.java index fd42638dc53..adaa947a72a 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PrefixedFormInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PrefixedFormInjector.java @@ -82,4 +82,4 @@ protected boolean hasValue(List list) { return !list.isEmpty() && list.get(0).length() > 0; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PropertyInjectorImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PropertyInjectorImpl.java index 75d97e593c7..4730e26c5d6 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PropertyInjectorImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/PropertyInjectorImpl.java @@ -128,7 +128,7 @@ private ValueInjector getParameterExtractor(Class clazz, ResteasyProviderFact { boolean extractBody = (FindAnnotation.findAnnotation(annotations, Body.class) != null); ValueInjector injector = factory.getInjectorFactory().createParameterExtractor(clazz, accessibleObject, defaultName, type, genericType, - annotations, extractBody, factory); + annotations, extractBody, factory); return injector; } @@ -194,19 +194,19 @@ public void inject(Object target) private Field[] getDeclaredFields(final Class clazz) { - final SecurityManager sm = System.getSecurityManager(); - if (sm != null) - { - return AccessController.doPrivileged(new PrivilegedAction() - { - @Override - public Field[] run() - { - return clazz.getDeclaredFields(); - } - }); - } - return clazz.getDeclaredFields(); + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) + { + return AccessController.doPrivileged(new PrivilegedAction() + { + @Override + public Field[] run() + { + return clazz.getDeclaredFields(); + } + }); + } + return clazz.getDeclaredFields(); } private Method[] getDeclaredMethods(final Class clazz) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResourceMethodInvoker.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResourceMethodInvoker.java index 43cadda4884..2d468879ee9 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResourceMethodInvoker.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResourceMethodInvoker.java @@ -85,7 +85,7 @@ public ResourceMethodInvoker(ResourceMethod method, InjectorFactory injector, Re this.method = method; this.methodAnnotations = this.method.getAnnotatedMethod().getAnnotations(); - resourceInfo = new ResourceInfo() + resourceInfo = new ResourceInfo() { @Override public Method getResourceMethod() @@ -140,65 +140,65 @@ public Class getResourceClass() asyncResponseProvider = resourceMethodProviderFactory.getAsyncResponseProvider(method.getReturnType()); if(asyncResponseProvider == null){ - asyncStreamProvider = resourceMethodProviderFactory.getAsyncStreamProvider(method.getReturnType()); + asyncStreamProvider = resourceMethodProviderFactory.getAsyncStreamProvider(method.getReturnType()); } if (isSseResourceMethod(method)) { - isSse = true; - method.markAsynchronous(); + isSse = true; + method.markAsynchronous(); } } - // spec section 9.3 Server API: - // A resource method that injects an SseEventSink and - // produces the media type text/event-stream is an SSE resource method. - private boolean isSseResourceMethod(ResourceMethod resourceMethod) { - - // First exclusive condition to be a SSE resource method is to only - // produce text/event-stream - MediaType[] producedMediaTypes = resourceMethod.getProduces(); + // spec section 9.3 Server API: + // A resource method that injects an SseEventSink and + // produces the media type text/event-stream is an SSE resource method. + private boolean isSseResourceMethod(ResourceMethod resourceMethod) { + + // First exclusive condition to be a SSE resource method is to only + // produce text/event-stream + MediaType[] producedMediaTypes = resourceMethod.getProduces(); boolean onlyProduceServerSentEventsMediaType = producedMediaTypes != null && producedMediaTypes.length == 1 && MediaType.SERVER_SENT_EVENTS_TYPE.isCompatible(producedMediaTypes[0]); - if (!onlyProduceServerSentEventsMediaType) - { - return false; - } - - // Second condition to be a SSE resource method is to be injected with a - // SseEventSink parameter - MethodParameter[] resourceMethodParameters = resourceMethod.getParams(); - if (resourceMethodParameters != null) - { - for (MethodParameter resourceMethodParameter : resourceMethodParameters) - { - if (Parameter.ParamType.CONTEXT.equals(resourceMethodParameter.getParamType()) - && SseEventSink.class.equals(resourceMethodParameter.getType())) - { - return true; - } - } - } - - // Resteasy specific: - // Or the given application should register a - // org.jboss.resteasy.spi.AsyncStreamProvider compatible with resource - // method return type and the resource method must not be annotated with - // any org.jboss.resteasy.annotations.Stream annotation - if (asyncStreamProvider != null) - { - for (Annotation annotation : resourceMethod.getAnnotatedMethod().getAnnotations()) - { - if (annotation.annotationType() == Stream.class) - { - return false; - } - } - return true; - } - - return false; - } + if (!onlyProduceServerSentEventsMediaType) + { + return false; + } + + // Second condition to be a SSE resource method is to be injected with a + // SseEventSink parameter + MethodParameter[] resourceMethodParameters = resourceMethod.getParams(); + if (resourceMethodParameters != null) + { + for (MethodParameter resourceMethodParameter : resourceMethodParameters) + { + if (Parameter.ParamType.CONTEXT.equals(resourceMethodParameter.getParamType()) + && SseEventSink.class.equals(resourceMethodParameter.getType())) + { + return true; + } + } + } + + // Resteasy specific: + // Or the given application should register a + // org.jboss.resteasy.spi.AsyncStreamProvider compatible with resource + // method return type and the resource method must not be annotated with + // any org.jboss.resteasy.annotations.Stream annotation + if (asyncStreamProvider != null) + { + for (Annotation annotation : resourceMethod.getAnnotatedMethod().getAnnotations()) + { + if (annotation.annotationType() == Stream.class) + { + return false; + } + } + return true; + } + + return false; + } public void cleanup() { @@ -349,7 +349,7 @@ protected Object invokeOnTargetDryRun(HttpRequest request, HttpResponse response } catch (RuntimeException ex) { - throw new ProcessingException(ex); + throw new ProcessingException(ex); } return rtn; @@ -360,7 +360,7 @@ protected BuiltResponse invokeOnTarget(HttpRequest request, HttpResponse respons ResteasyProviderFactory.pushContext(ResourceInfo.class, resourceInfo); // we don't pop so writer interceptors can get at this PostMatchContainerRequestContext requestContext = new PostMatchContainerRequestContext(request, this, requestFilters, - () -> invokeOnTargetAfterFilter(request, response, target)); + () -> invokeOnTargetAfterFilter(request, response, target)); // let it handle the continuation return requestContext.filter(); } @@ -390,7 +390,7 @@ else if (isValidatable) } else if (asyncStreamProvider != null) { - asyncResponseConsumer = AsyncResponseConsumer.makeAsyncResponseConsumer(this, asyncStreamProvider); + asyncResponseConsumer = AsyncResponseConsumer.makeAsyncResponseConsumer(this, asyncStreamProvider); } Object rtn = null; @@ -502,21 +502,21 @@ else if (request.getAsyncContext().isSuspended()) return jaxrsResponse; } - private Object internalInvokeOnTarget(HttpRequest request, HttpResponse response, Object target) { - PostResourceMethodInvokers postResourceMethodInvokers = ResteasyProviderFactory - .getContextData(PostResourceMethodInvokers.class); - try { - Object toReturn = this.methodInjector.invoke(request, response, target); - if (postResourceMethodInvokers != null) { - postResourceMethodInvokers.getInvokers().forEach(e -> e.invoke()); - } - return toReturn; - } finally { - if (postResourceMethodInvokers != null) { - postResourceMethodInvokers.clear(); - } - } - } + private Object internalInvokeOnTarget(HttpRequest request, HttpResponse response, Object target) { + PostResourceMethodInvokers postResourceMethodInvokers = ResteasyProviderFactory + .getContextData(PostResourceMethodInvokers.class); + try { + Object toReturn = this.methodInjector.invoke(request, response, target); + if (postResourceMethodInvokers != null) { + postResourceMethodInvokers.getInvokers().forEach(e -> e.invoke()); + } + return toReturn; + } finally { + if (postResourceMethodInvokers != null) { + postResourceMethodInvokers.clear(); + } + } + } public void initializeAsync(ResteasyAsynchronousResponse asyncResponse) { @@ -648,7 +648,7 @@ public MediaType[] getConsumes() public boolean isSse() { - return isSse; + return isSse; } public void markMethodAsAsync() diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletRequestWrapper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletRequestWrapper.java index 341df12b66a..763c69348a9 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletRequestWrapper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletRequestWrapper.java @@ -195,12 +195,12 @@ public boolean isRequestedSessionIdFromURL() } /** - * - * @deprecated As of Version 2.1 of the Java Servlet - * API, use {@link #isRequestedSessionIdFromURL} - * instead. - * - */ + * + * @deprecated As of Version 2.1 of the Java Servlet + * API, use {@link #isRequestedSessionIdFromURL} + * instead. + * + */ @Override public boolean isRequestedSessionIdFromUrl() { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletResponseWrapper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletResponseWrapper.java index e64fdaabddd..deff0d8be99 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletResponseWrapper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ResteasyHttpServletResponseWrapper.java @@ -162,7 +162,7 @@ public String encodeRedirectURL(String url) * @deprecated As of version 2.1, use encodeURL(String url) instead * * @param url the url to be encoded. - * @return the encoded URL if encoding is needed; + * @return the encoded URL if encoding is needed; * the unchanged URL otherwise. */ @Override @@ -172,11 +172,11 @@ public String encodeUrl(String url) } /** - * @deprecated As of version 2.1, use + * @deprecated As of version 2.1, use * encodeRedirectURL(String url) instead * * @param url the url to be encoded. - * @return the encoded URL if encoding is needed; + * @return the encoded URL if encoding is needed; * the unchanged URL otherwise. */ @Override @@ -246,13 +246,13 @@ public void setStatus(int sc) } /** - * @deprecated As of version 2.1, due to ambiguous meaning of the - * message parameter. To set a status code + * @deprecated As of version 2.1, due to ambiguous meaning of the + * message parameter. To set a status code * use setStatus(int), to send an error with a description * use sendError(int, String). * * Sets the status code and message for this response. - * + * * @param sc the status code * @param sm the status message */ diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ServerResponseWriter.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ServerResponseWriter.java index a5efb165904..b1de3ffc9c5 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ServerResponseWriter.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ServerResponseWriter.java @@ -47,9 +47,9 @@ public class ServerResponseWriter { @FunctionalInterface public interface RunnableWithIOException { - void run() throws IOException; + void run() throws IOException; } - + public static void writeNomapResponse(BuiltResponse jaxrsResponse, final HttpRequest request, final HttpResponse response, final ResteasyProviderFactory providerFactory, Consumer onComplete) throws IOException { @@ -150,7 +150,7 @@ public static void setResponseMediaType(BuiltResponse jaxrsResponse, HttpRequest jaxrsResponse.getHeaders().putSingle(HttpHeaders.CONTENT_TYPE, mt.toString()); } } - + public static MediaType getResponseMediaType(BuiltResponse jaxrsResponse, HttpRequest request, HttpResponse response, ResteasyProviderFactory providerFactory, ResourceMethodInvoker method) { MediaType mt = null; @@ -183,7 +183,7 @@ public static MediaType getResponseMediaType(BuiltResponse jaxrsResponse, HttpRe private static void executeFilters(BuiltResponse jaxrsResponse, HttpRequest request, HttpResponse response, ResteasyProviderFactory providerFactory, - ResourceMethodInvoker method, Consumer onComplete, RunnableWithIOException continuation) throws IOException + ResourceMethodInvoker method, Consumer onComplete, RunnableWithIOException continuation) throws IOException { ContainerResponseFilter[] responseFilters = null; @@ -200,7 +200,7 @@ private static void executeFilters(BuiltResponse jaxrsResponse, HttpRequest requ { ResponseContainerRequestContext requestContext = new ResponseContainerRequestContext(request); ContainerResponseContextImpl responseContext = new ContainerResponseContextImpl(request, response, jaxrsResponse, - requestContext, responseFilters, onComplete, continuation); + requestContext, responseFilters, onComplete, continuation); // filter calls the continuation responseContext.filter(); } @@ -470,7 +470,7 @@ public static void commitHeaders(BuiltResponse jaxrsResponse, HttpResponse respo } } if (jaxrsResponse.getMetadata() != null - && jaxrsResponse.getMetadata().size() > 0) + && jaxrsResponse.getMetadata().size() > 0) { response.getOutputHeaders().putAll(jaxrsResponse.getMetadata()); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/StringParameterInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/StringParameterInjector.java index cf6e9e3654d..10716e83861 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/StringParameterInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/StringParameterInjector.java @@ -47,330 +47,330 @@ @SuppressWarnings(value = { "unchecked", "deprecation" }) public class StringParameterInjector { - private static final ParamConverter characterParamConverter = new ParamConverter() { - - @Override - public Character fromString(String value) { - if(value != null && value.length() == 1) - { - return value.charAt(0); - } - return null; - } - - @Override - public String toString(Character value) { - return null; - } - - }; - - private static final class UnmodifiableArrayList extends ArrayList{ - + private static final ParamConverter characterParamConverter = new ParamConverter() { + + @Override + public Character fromString(String value) { + if(value != null && value.length() == 1) + { + return value.charAt(0); + } + return null; + } + + @Override + public String toString(Character value) { + return null; + } + + }; + + private static final class UnmodifiableArrayList extends ArrayList{ + private static final long serialVersionUID = -4912938596876802150L; private UnmodifiableArrayList(Collectioncollection) { - super(collection); - } - - @Override - public boolean add(E e) {throw new UnsupportedOperationException();} - @Override - public void add(int index, E element) {throw new UnsupportedOperationException();} - @Override - public boolean addAll(Collection c) {throw new UnsupportedOperationException();} - @Override - public void clear() {throw new UnsupportedOperationException();} - @Override - public boolean remove(Object o) {throw new UnsupportedOperationException();} - @Override - public boolean addAll(int index, Collection c) {throw new UnsupportedOperationException();} - @Override - public E remove(int index) {throw new UnsupportedOperationException();} - @Override - public boolean removeAll(Collection c) {throw new UnsupportedOperationException();} - @Override - public boolean removeIf(Predicate filter) {throw new UnsupportedOperationException();} - @Override - public void replaceAll(UnaryOperator operator) {throw new UnsupportedOperationException();} - @Override - public boolean retainAll(Collection c) {throw new UnsupportedOperationException();} - @Override - public E set(int index, E element) {throw new UnsupportedOperationException();} - @Override - public void sort(Comparator c) {throw new UnsupportedOperationException();} - - @Override - public List subList(int fromIndex, int toIndex) { - return new UnmodifiableArrayList<>(super.subList(fromIndex, toIndex)); - } - - @Override - public Iterator iterator() { - return new Iterator() { - private final Iterator iterator = UnmodifiableArrayList.super.iterator(); - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - @Override - public E next() { - return iterator.next(); - } - @Override - public void remove() {throw new UnsupportedOperationException();} - @Override - public void forEachRemaining(Consumer action) { - iterator.forEachRemaining(action); - } - }; - } - - @Override - public ListIterator listIterator() { - return listIterator(0); - } - - @Override - public ListIterator listIterator(int index) { - return new ListIterator() { - private final ListIterator iterator = UnmodifiableArrayList.super.listIterator(index); - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - @Override - public E next() { - return iterator.next(); - } - @Override - public boolean hasPrevious() { - return iterator.hasPrevious(); - } - @Override - public E previous() { - return iterator.previous(); - } - @Override - public int nextIndex() { - return iterator.nextIndex(); - } - @Override - public int previousIndex() { - return iterator.previousIndex(); - } - @Override - public void remove() {throw new UnsupportedOperationException();} - @Override - public void set(E e) {throw new UnsupportedOperationException();} - @Override - public void add(E e) {throw new UnsupportedOperationException();} - @Override - public void forEachRemaining(Consumer action) { - iterator.forEachRemaining(action); - } + super(collection); + } + + @Override + public boolean add(E e) {throw new UnsupportedOperationException();} + @Override + public void add(int index, E element) {throw new UnsupportedOperationException();} + @Override + public boolean addAll(Collection c) {throw new UnsupportedOperationException();} + @Override + public void clear() {throw new UnsupportedOperationException();} + @Override + public boolean remove(Object o) {throw new UnsupportedOperationException();} + @Override + public boolean addAll(int index, Collection c) {throw new UnsupportedOperationException();} + @Override + public E remove(int index) {throw new UnsupportedOperationException();} + @Override + public boolean removeAll(Collection c) {throw new UnsupportedOperationException();} + @Override + public boolean removeIf(Predicate filter) {throw new UnsupportedOperationException();} + @Override + public void replaceAll(UnaryOperator operator) {throw new UnsupportedOperationException();} + @Override + public boolean retainAll(Collection c) {throw new UnsupportedOperationException();} + @Override + public E set(int index, E element) {throw new UnsupportedOperationException();} + @Override + public void sort(Comparator c) {throw new UnsupportedOperationException();} + + @Override + public List subList(int fromIndex, int toIndex) { + return new UnmodifiableArrayList<>(super.subList(fromIndex, toIndex)); + } + + @Override + public Iterator iterator() { + return new Iterator() { + private final Iterator iterator = UnmodifiableArrayList.super.iterator(); + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + @Override + public E next() { + return iterator.next(); + } + @Override + public void remove() {throw new UnsupportedOperationException();} + @Override + public void forEachRemaining(Consumer action) { + iterator.forEachRemaining(action); + } }; - - } - - } - - private static final class UnmodifiableHashSet extends HashSet{ - + } + + @Override + public ListIterator listIterator() { + return listIterator(0); + } + + @Override + public ListIterator listIterator(int index) { + return new ListIterator() { + private final ListIterator iterator = UnmodifiableArrayList.super.listIterator(index); + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + @Override + public E next() { + return iterator.next(); + } + @Override + public boolean hasPrevious() { + return iterator.hasPrevious(); + } + @Override + public E previous() { + return iterator.previous(); + } + @Override + public int nextIndex() { + return iterator.nextIndex(); + } + @Override + public int previousIndex() { + return iterator.previousIndex(); + } + @Override + public void remove() {throw new UnsupportedOperationException();} + @Override + public void set(E e) {throw new UnsupportedOperationException();} + @Override + public void add(E e) {throw new UnsupportedOperationException();} + @Override + public void forEachRemaining(Consumer action) { + iterator.forEachRemaining(action); + } + }; + + } + + } + + private static final class UnmodifiableHashSet extends HashSet{ + private static final long serialVersionUID = 9175388977415467750L; private final boolean initialized; - - private UnmodifiableHashSet(Collectioncollection) { - super(collection); - this.initialized=true; - } - - @Override - public boolean remove(Object o) {throw new UnsupportedOperationException();} - @Override - public void clear() {throw new UnsupportedOperationException();} - @Override - public boolean removeAll(Collection c) {throw new UnsupportedOperationException();} - @Override - public boolean retainAll(Collection c) {throw new UnsupportedOperationException();} - @Override - public boolean removeIf(Predicate filter) {throw new UnsupportedOperationException();} - - @Override - public boolean add(E e) { - //Called by constructor - if(initialized){ - throw new UnsupportedOperationException(); - } - return super.add(e); - } - - @Override - public boolean addAll(Collection c) { - //Called by constructor - if(initialized){ - throw new UnsupportedOperationException(); - } - return super.addAll(c); - } - - @Override - public Iterator iterator() { - return new Iterator() { - private final Iterator iterator = UnmodifiableHashSet.super.iterator(); - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - @Override - public E next() { - return iterator.next(); - } - @Override - public void remove() {throw new UnsupportedOperationException();} - @Override - public void forEachRemaining(Consumer action) { - iterator.forEachRemaining(action); - } - }; - } - - } - - private static final class UnmodifiableTreeSet extends TreeSet{ + + private UnmodifiableHashSet(Collectioncollection) { + super(collection); + this.initialized=true; + } + + @Override + public boolean remove(Object o) {throw new UnsupportedOperationException();} + @Override + public void clear() {throw new UnsupportedOperationException();} + @Override + public boolean removeAll(Collection c) {throw new UnsupportedOperationException();} + @Override + public boolean retainAll(Collection c) {throw new UnsupportedOperationException();} + @Override + public boolean removeIf(Predicate filter) {throw new UnsupportedOperationException();} + + @Override + public boolean add(E e) { + //Called by constructor + if(initialized){ + throw new UnsupportedOperationException(); + } + return super.add(e); + } + + @Override + public boolean addAll(Collection c) { + //Called by constructor + if(initialized){ + throw new UnsupportedOperationException(); + } + return super.addAll(c); + } + + @Override + public Iterator iterator() { + return new Iterator() { + private final Iterator iterator = UnmodifiableHashSet.super.iterator(); + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + @Override + public E next() { + return iterator.next(); + } + @Override + public void remove() {throw new UnsupportedOperationException();} + @Override + public void forEachRemaining(Consumer action) { + iterator.forEachRemaining(action); + } + }; + } + + } + + private static final class UnmodifiableTreeSet extends TreeSet{ private static final long serialVersionUID = 6337958351217117300L; private final boolean initialized; - - private UnmodifiableTreeSet(Collectioncollection) { - super(collection); - this.initialized=true; - } - - private UnmodifiableTreeSet(Comparator comparator,Collectioncollection) { - super(comparator); - addAll(collection); - this.initialized=true; - } - - @Override - public boolean remove(Object o) {throw new UnsupportedOperationException();} - @Override - public void clear() {throw new UnsupportedOperationException();} - @Override - public boolean removeAll(Collection c) {throw new UnsupportedOperationException();} - @Override - public boolean retainAll(Collection c) {throw new UnsupportedOperationException();} - @Override - public boolean removeIf(Predicate filter) {throw new UnsupportedOperationException();} - @Override - public E pollFirst() {throw new UnsupportedOperationException();} - @Override - public E pollLast() {throw new UnsupportedOperationException();} - - @Override - public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return new UnmodifiableTreeSet<>(super.subSet(fromElement, fromInclusive, toElement, toInclusive)); - } - - @Override - public SortedSet subSet(E fromElement, E toElement) { - return new UnmodifiableTreeSet<>(super.subSet(fromElement, toElement)); - } - - @Override - public NavigableSet descendingSet() { - NavigableSet descendingSet = super.descendingSet(); - return new UnmodifiableTreeSet<>(descendingSet.comparator(), descendingSet); - } - - @Override - public SortedSet headSet(E toElement) { - return new UnmodifiableTreeSet<>(super.headSet(toElement)); - } - - @Override - public NavigableSet headSet(E toElement, boolean inclusive) { - return new UnmodifiableTreeSet<>(super.headSet(toElement, inclusive)); - } - - @Override - public SortedSet tailSet(E fromElement) { - return new UnmodifiableTreeSet<>(super.tailSet(fromElement)); - } - - @Override - public NavigableSet tailSet(E fromElement, boolean inclusive) { - return new UnmodifiableTreeSet<>(super.tailSet(fromElement, inclusive)); - } - - @Override - public boolean add(E e) { - //Called by constructor - if(initialized){ - throw new UnsupportedOperationException(); - } - return super.add(e); - } - - @Override - public boolean addAll(Collection c) { - //Called by constructor - if(initialized){ - throw new UnsupportedOperationException(); - } - return super.addAll(c); - } - - @Override - public Iterator iterator() { - return new Iterator() { - private final Iterator iterator = UnmodifiableTreeSet.super.iterator(); - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - @Override - public E next() { - return iterator.next(); - } - @Override - public void remove() {throw new UnsupportedOperationException();} - @Override - public void forEachRemaining(Consumer action) { - iterator.forEachRemaining(action); - } - }; - } - - @Override - public Iterator descendingIterator() { - return new Iterator() { - private final Iterator iterator = UnmodifiableTreeSet.super.descendingIterator(); - - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - @Override - public E next() { - return iterator.next(); - } - @Override - public void remove() {throw new UnsupportedOperationException();} - @Override - public void forEachRemaining(Consumer action) { - iterator.forEachRemaining(action); - } - }; - } - - - } - + + private UnmodifiableTreeSet(Collectioncollection) { + super(collection); + this.initialized=true; + } + + private UnmodifiableTreeSet(Comparator comparator,Collectioncollection) { + super(comparator); + addAll(collection); + this.initialized=true; + } + + @Override + public boolean remove(Object o) {throw new UnsupportedOperationException();} + @Override + public void clear() {throw new UnsupportedOperationException();} + @Override + public boolean removeAll(Collection c) {throw new UnsupportedOperationException();} + @Override + public boolean retainAll(Collection c) {throw new UnsupportedOperationException();} + @Override + public boolean removeIf(Predicate filter) {throw new UnsupportedOperationException();} + @Override + public E pollFirst() {throw new UnsupportedOperationException();} + @Override + public E pollLast() {throw new UnsupportedOperationException();} + + @Override + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return new UnmodifiableTreeSet<>(super.subSet(fromElement, fromInclusive, toElement, toInclusive)); + } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return new UnmodifiableTreeSet<>(super.subSet(fromElement, toElement)); + } + + @Override + public NavigableSet descendingSet() { + NavigableSet descendingSet = super.descendingSet(); + return new UnmodifiableTreeSet<>(descendingSet.comparator(), descendingSet); + } + + @Override + public SortedSet headSet(E toElement) { + return new UnmodifiableTreeSet<>(super.headSet(toElement)); + } + + @Override + public NavigableSet headSet(E toElement, boolean inclusive) { + return new UnmodifiableTreeSet<>(super.headSet(toElement, inclusive)); + } + + @Override + public SortedSet tailSet(E fromElement) { + return new UnmodifiableTreeSet<>(super.tailSet(fromElement)); + } + + @Override + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return new UnmodifiableTreeSet<>(super.tailSet(fromElement, inclusive)); + } + + @Override + public boolean add(E e) { + //Called by constructor + if(initialized){ + throw new UnsupportedOperationException(); + } + return super.add(e); + } + + @Override + public boolean addAll(Collection c) { + //Called by constructor + if(initialized){ + throw new UnsupportedOperationException(); + } + return super.addAll(c); + } + + @Override + public Iterator iterator() { + return new Iterator() { + private final Iterator iterator = UnmodifiableTreeSet.super.iterator(); + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + @Override + public E next() { + return iterator.next(); + } + @Override + public void remove() {throw new UnsupportedOperationException();} + @Override + public void forEachRemaining(Consumer action) { + iterator.forEachRemaining(action); + } + }; + } + + @Override + public Iterator descendingIterator() { + return new Iterator() { + private final Iterator iterator = UnmodifiableTreeSet.super.descendingIterator(); + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + @Override + public E next() { + return iterator.next(); + } + @Override + public void remove() {throw new UnsupportedOperationException();} + @Override + public void forEachRemaining(Consumer action) { + iterator.forEachRemaining(action); + } + }; + } + + + } + protected Class type; protected Class baseType; protected Type baseGenericType; @@ -417,25 +417,25 @@ protected void initialize(Class type, Type genericType, String paramName, Cla //Step 1: try to find a conversion mechanism using the type as it is if(initialize(annotations, factory)) { - return; + return; } //Step2: try to find a conversion mechanism if the type is an array type - if (type.isArray()) + if (type.isArray()) + { + isArray = true; + baseType = type.getComponentType(); + if(initialize(annotations, factory)) + { + return; + } + } + + //Step 3: try to find a conversion mechanism if the type is a collection type + collectionType = convertParameterTypeToCollectionType(); + if (collectionType != null) { - isArray = true; - baseType = type.getComponentType(); - if(initialize(annotations, factory)) - { - return ; - } - } - - //Step 3: try to find a conversion mechanism if the type is a collection type - collectionType = convertParameterTypeToCollectionType(); - if (collectionType != null) - { - isCollection = true; + isCollection = true; if (genericType instanceof ParameterizedType) { ParameterizedType zType = (ParameterizedType) baseGenericType; @@ -449,96 +449,96 @@ protected void initialize(Class type, Type genericType, String paramName, Cla } if(initialize(annotations, factory)) { - return; + return; } - } + } - throw new RuntimeException(Messages.MESSAGES.unableToFindConstructor(getParamSignature(), target, baseType.getName())); + throw new RuntimeException(Messages.MESSAGES.unableToFindConstructor(getParamSignature(), target, baseType.getName())); - } + } private boolean initialize(Annotation[] annotations, ResteasyProviderFactory factory){ - - //No need to find any conversion mechanism if we are dealing with primitive type - if(baseType.isPrimitive()) - { - return true; - } - - // First try to find a ParamConverter if any - paramConverter = factory.getParamConverter(baseType, baseGenericType, annotations); - if (paramConverter != null) - { - return true; - } - - // Else try to find a StringParameterUnmarshaller if any - unmarshaller = factory.createStringParameterUnmarshaller(baseType); - if (unmarshaller != null) - { - unmarshaller.setAnnotations(annotations); - return true; - } - for (Annotation annotation : annotations) - { - StringParameterUnmarshallerBinder binder = annotation.annotationType().getAnnotation(StringParameterUnmarshallerBinder.class); - if (binder != null) - { - try - { - unmarshaller = binder.value().newInstance(); - } - catch (InstantiationException e) - { - throw new RuntimeException(e.getCause()); - } - catch (IllegalAccessException e) - { - throw new RuntimeException(e); - } - factory.injectProperties(unmarshaller); - unmarshaller.setAnnotations(annotations); - return true; - } - } - - // Else try to find a StringConverter if any - converter = factory.getStringConverter(baseType); - if (converter != null) - { - return true; - } - - // Else try to find a RuntimeDelegate.HeaderDelegate if any - if (paramType.equals(HeaderParam.class)) - { - delegate = factory.getHeaderDelegate(baseType); - if (delegate != null) - { - return true; - } - } - - // Else try to find a public Constructor that accepts a single String argument if any - try - { - constructor = baseType.getConstructor(String.class); - if (!Modifier.isPublic(constructor.getModifiers())) - { - constructor = null; - } - else - { - return true; - } - } - catch (NoSuchMethodException ignored) - { - - } - - // Else try to find a public fromValue (JAXB enum) or valueOf or fromString method that accepts a single String argument if any. + + //No need to find any conversion mechanism if we are dealing with primitive type + if(baseType.isPrimitive()) + { + return true; + } + + // First try to find a ParamConverter if any + paramConverter = factory.getParamConverter(baseType, baseGenericType, annotations); + if (paramConverter != null) + { + return true; + } + + // Else try to find a StringParameterUnmarshaller if any + unmarshaller = factory.createStringParameterUnmarshaller(baseType); + if (unmarshaller != null) + { + unmarshaller.setAnnotations(annotations); + return true; + } + for (Annotation annotation : annotations) + { + StringParameterUnmarshallerBinder binder = annotation.annotationType().getAnnotation(StringParameterUnmarshallerBinder.class); + if (binder != null) + { + try + { + unmarshaller = binder.value().newInstance(); + } + catch (InstantiationException e) + { + throw new RuntimeException(e.getCause()); + } + catch (IllegalAccessException e) + { + throw new RuntimeException(e); + } + factory.injectProperties(unmarshaller); + unmarshaller.setAnnotations(annotations); + return true; + } + } + + // Else try to find a StringConverter if any + converter = factory.getStringConverter(baseType); + if (converter != null) + { + return true; + } + + // Else try to find a RuntimeDelegate.HeaderDelegate if any + if (paramType.equals(HeaderParam.class)) + { + delegate = factory.getHeaderDelegate(baseType); + if (delegate != null) + { + return true; + } + } + + // Else try to find a public Constructor that accepts a single String argument if any + try + { + constructor = baseType.getConstructor(String.class); + if (!Modifier.isPublic(constructor.getModifiers())) + { + constructor = null; + } + else + { + return true; + } + } + catch (NoSuchMethodException ignored) + { + + } + + // Else try to find a public fromValue (JAXB enum) or valueOf or fromString method that accepts a single String argument if any. try { // this is for JAXB generated enums. @@ -591,28 +591,28 @@ else if (valueOf == null) } if (valueOf == null) { - if(Character.class.equals(baseType)) - { - paramConverter = characterParamConverter; - return true; - } + if(Character.class.equals(baseType)) + { + paramConverter = characterParamConverter; + return true; + } } } return valueOf != null; } - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes") private Class convertParameterTypeToCollectionType() { - if (List.class.equals(type) || ArrayList.class.equals(type)) { - return ArrayList.class; - } else if (SortedSet.class.equals(type) || TreeSet.class.equals(type)) { - return TreeSet.class; - } else if (Set.class.equals(type) || HashSet.class.equals(type)) { - return HashSet.class; - } - return null; - } + if (List.class.equals(type) || ArrayList.class.equals(type)) { + return ArrayList.class; + } else if (SortedSet.class.equals(type) || TreeSet.class.equals(type)) { + return TreeSet.class; + } else if (Set.class.equals(type) || HashSet.class.equals(type)) { + return HashSet.class; + } + return null; + } public String getParamSignature() { @@ -654,13 +654,13 @@ else if (isCollection) { collection.add(extractValue(str)); } - if (ArrayList.class.equals(collectionType)) { - return new UnmodifiableArrayList<>(collection); - } else if (TreeSet.class.equals(collectionType)) { - return new UnmodifiableTreeSet<>(collection); - } else if (HashSet.class.equals(collectionType)) { - return new UnmodifiableHashSet<>(collection); - } + if (ArrayList.class.equals(collectionType)) { + return new UnmodifiableArrayList<>(collection); + } else if (TreeSet.class.equals(collectionType)) { + return new UnmodifiableTreeSet<>(collection); + } else if (HashSet.class.equals(collectionType)) { + return new UnmodifiableHashSet<>(collection); + } throw new RuntimeException("Unable to handle "+collectionType); } else diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SuspendInjector.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SuspendInjector.java index db4085d1bb3..381be48a811 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SuspendInjector.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SuspendInjector.java @@ -49,4 +49,4 @@ public void setResponse(Response response) } }; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SynchronousDispatcher.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SynchronousDispatcher.java index b1689d78156..37dee58b438 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SynchronousDispatcher.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/SynchronousDispatcher.java @@ -108,7 +108,7 @@ public Response preprocess(HttpRequest request) { //logger.error("Failed in preprocess, mapping exception", e); aborted = new ExceptionHandler(providerFactory, unwrappedExceptions).handleException(request, e); - } + } return aborted; } @@ -131,10 +131,10 @@ protected void preprocess(HttpRequest request, HttpResponse response, Runnable c } ContainerRequestFilter[] requestFilters = providerFactory.getContainerRequestFilterRegistry().preMatch(); requestContext = new PreMatchContainerRequestContext(request, requestFilters, - () -> { - continuation.run(); - return null; - }); + () -> { + continuation.run(); + return null; + }); aborted = requestContext.filter(); } catch (Exception e) @@ -290,7 +290,7 @@ public void invokePropagateNotFound(HttpRequest request, HttpResponse response) } public ResourceInvoker getInvoker(HttpRequest request) - throws Failure + throws Failure { LogMessages.LOGGER.pathInfo(request.getUri().getPath()); if (!request.isInitial()) @@ -369,22 +369,22 @@ public Response internalInvocation(HttpRequest request, HttpResponse response, O public void clearContextData() { - Cleanables cleanables = ResteasyProviderFactory.getContextData(Cleanables.class); - if (cleanables != null) - { - for (Iterator it = cleanables.getCleanables().iterator(); it.hasNext(); ) - { - try - { - it.next().clean(); - } - catch(Exception e) - { - // Empty - } - } - } - ResteasyProviderFactory.clearContextData(); + Cleanables cleanables = ResteasyProviderFactory.getContextData(Cleanables.class); + if (cleanables != null) + { + for (Iterator it = cleanables.getCleanables().iterator(); it.hasNext(); ) + { + try + { + it.next().clean(); + } + catch(Exception e) + { + // Empty + } + } + } + ResteasyProviderFactory.clearContextData(); // just in case there were internalDispatches that need to be cleaned up MessageBodyParameterInjector.clearBodies(); } @@ -526,10 +526,10 @@ protected void writeResponse(HttpRequest request, HttpResponse response, Respons try { ServerResponseWriter.writeNomapResponse((BuiltResponse) jaxrsResponse, request, response, providerFactory, - t -> { - if(t != null) - writeException(request, response, t, t2 -> {}); - }); + t -> { + if(t != null) + writeException(request, response, t, t2 -> {}); + }); } catch (Exception e) { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ThreadLocalResteasyProviderFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ThreadLocalResteasyProviderFactory.java index c653fa8e373..4a4b5efcc1f 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ThreadLocalResteasyProviderFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/ThreadLocalResteasyProviderFactory.java @@ -273,7 +273,7 @@ public MessageBodyReader getMessageBodyReader(Class type, Type generic { MessageBodyReader reader = getDelegate().getMessageBodyReader(type, genericType, annotations, mediaType); if (reader!=null) - LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); return reader; } @@ -624,7 +624,7 @@ public MessageBodyWriter getMessageBodyWriter(Class type, Type generic { MessageBodyWriter writer = getDelegate().getMessageBodyWriter(type, genericType, annotations, mediaType); if (writer!=null) - LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); return writer; } @@ -675,7 +675,7 @@ public MessageBodyWriter getClientMessageBodyWriter(Class type, Type g { MessageBodyWriter writer = getDelegate().getClientMessageBodyWriter(type, genericType, annotations, mediaType); if (writer!=null) - LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); return writer; } @@ -684,7 +684,7 @@ public MessageBodyReader getClientMessageBodyReader(Class type, Type g { MessageBodyReader reader = getDelegate().getClientMessageBodyReader(type, genericType, annotations, mediaType); if (reader!=null) - LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); return reader; } @@ -693,7 +693,7 @@ public MessageBodyReader getServerMessageBodyReader(Class type, Type g { MessageBodyReader reader = getDelegate().getServerMessageBodyReader(type, genericType, annotations, mediaType); if (reader!=null) - LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); return reader; } @@ -702,7 +702,7 @@ public MessageBodyWriter getServerMessageBodyWriter(Class type, Type g { MessageBodyWriter writer = getDelegate().getServerMessageBodyWriter(type, genericType, annotations, mediaType); if (writer!=null) - LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); return writer; } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractReaderInterceptorContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractReaderInterceptorContext.java index a8027c56a08..60a74af2ef3 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractReaderInterceptorContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractReaderInterceptorContext.java @@ -52,7 +52,7 @@ public Object proceed() throws IOException { MessageBodyReader reader = getReader(); if (reader!=null) - LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); return readFrom(reader); } LogMessages.LOGGER.debugf("ReaderInterceptor: %s", interceptors[index].getClass().getName()); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractWriterInterceptorContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractWriterInterceptorContext.java index 853605d684a..6f4bc23a0f8 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractWriterInterceptorContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/AbstractWriterInterceptorContext.java @@ -120,7 +120,7 @@ public void proceed() throws IOException, WebApplicationException { MessageBodyWriter writer = getWriter(); if (writer!=null) - LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); writeTo(writer); } else diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientExecutionContextImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientExecutionContextImpl.java index 2bf78460c7d..8b2b68e5404 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientExecutionContextImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientExecutionContextImpl.java @@ -57,4 +57,4 @@ public ClientResponse proceed() throws Exception } } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientReaderInterceptorContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientReaderInterceptorContext.java index d307d3bf793..5b63bc3cce5 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientReaderInterceptorContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientReaderInterceptorContext.java @@ -42,7 +42,7 @@ protected void throwReaderNotFound() protected MessageBodyReader resolveReader(MediaType mediaType) { return providerFactory.getClientMessageBodyReader(type, - genericType, annotations, mediaType); + genericType, annotations, mediaType); } @Override diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientWriterInterceptorContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientWriterInterceptorContext.java index ba4c522d990..93a42119a66 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientWriterInterceptorContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ClientWriterInterceptorContext.java @@ -43,7 +43,7 @@ protected MessageBodyWriter resolveWriter() { @SuppressWarnings(value = "unchecked") MessageBodyWriter writer = providerFactory.getClientMessageBodyWriter( - type, genericType, annotations, mediaType); + type, genericType, annotations, mediaType); //logger.info("********* WRITER: " + writer.getClass().getName()); return writer; } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ContainerResponseContextImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ContainerResponseContextImpl.java index 40a813967ed..043d9a39ebb 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ContainerResponseContextImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ContainerResponseContextImpl.java @@ -157,7 +157,7 @@ public MultivaluedMap getHeaders() @Override public Set getAllowedMethods() { - return jaxrsResponse.getAllowedMethods(); + return jaxrsResponse.getAllowedMethods(); } @Override diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/DecoratorMatcher.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/DecoratorMatcher.java index dc42ad7cf69..b628ed7830c 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/DecoratorMatcher.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/DecoratorMatcher.java @@ -36,7 +36,7 @@ public T decorate(Class targetClass, T target, Class type, Annotation[] a HashMap, Annotation> meta = new HashMap, Annotation>(); if (type != null) { - registerDecorators(targetClass, meta, type.getAnnotations()); + registerDecorators(targetClass, meta, type.getAnnotations()); } // override any class level ones if (annotations != null) @@ -85,14 +85,14 @@ public T decorate(Class targetClass, T target, Class type, Annotation[] a return target; } - private void registerDecorators(Class targetClass, HashMap, Annotation> meta, Annotation[] annotations) { - for (Annotation annotation : annotations) - { - Decorator decorator = annotation.annotationType().getAnnotation(Decorator.class); - if (decorator != null && targetClass.isAssignableFrom(decorator.target())) - { - meta.put(annotation.annotationType(), annotation); - } - } - } + private void registerDecorators(Class targetClass, HashMap, Annotation> meta, Annotation[] annotations) { + for (Annotation annotation : annotations) + { + Decorator decorator = annotation.annotationType().getAnnotation(Decorator.class); + if (decorator != null && targetClass.isAssignableFrom(decorator.target())) + { + meta.put(annotation.annotationType(), annotation); + } + } + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/InterceptorRegistry.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/InterceptorRegistry.java index c4f998117ad..371c4c60459 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/InterceptorRegistry.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/InterceptorRegistry.java @@ -275,4 +275,4 @@ public void register(T interceptor) } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/JaxrsInterceptorRegistry.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/JaxrsInterceptorRegistry.java index 8753396f275..b0320608379 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/JaxrsInterceptorRegistry.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/JaxrsInterceptorRegistry.java @@ -53,7 +53,7 @@ protected static List> getNameBound(Class declari { if (annotation.annotationType().isAnnotationPresent(NameBinding.class)) { - nameBound.add(annotation.annotationType()); + nameBound.add(annotation.annotationType()); } } return nameBound; @@ -485,4 +485,4 @@ private Class getNonSyntheticClass(Class clazz) } return clazz; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerReaderInterceptorContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerReaderInterceptorContext.java index 1028022c3b8..2f35fd63b44 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerReaderInterceptorContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerReaderInterceptorContext.java @@ -42,7 +42,7 @@ protected MessageBodyReader resolveReader(MediaType mediaType) { @SuppressWarnings(value = "unchecked") MessageBodyReader reader = providerFactory.getServerMessageBodyReader(type, - genericType, annotations, mediaType); + genericType, annotations, mediaType); //logger.info("**** picked reader: " + reader.getClass().getName()); return reader; } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerWriterInterceptorContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerWriterInterceptorContext.java index 86676fbc334..c57f4611135 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerWriterInterceptorContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/ServerWriterInterceptorContext.java @@ -39,7 +39,7 @@ public ServerWriterInterceptorContext(WriterInterceptor[] interceptors, Resteasy protected MessageBodyWriter resolveWriter() { return providerFactory.getServerMessageBodyWriter( - type, genericType, annotations, mediaType); + type, genericType, annotations, mediaType); } @Override diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerRequestContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerRequestContext.java index b481ffe4581..e8abcb10a26 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerRequestContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerRequestContext.java @@ -13,9 +13,9 @@ public interface SuspendableContainerRequestContext extends ContainerRequestCont /** * Suspends the current request. This makes the current request asynchronous. No * further request filter is executed until this request is resumed. - * + * * No reply is going to be sent to the client until this request is resumed either - * with {@link #resume()} or aborted with {@link #resume(Throwable)} or + * with {@link #resume()} or aborted with {@link #resume(Throwable)} or * {@link #abortWith(javax.ws.rs.core.Response)}. */ void suspend(); @@ -31,7 +31,7 @@ public interface SuspendableContainerRequestContext extends ContainerRequestCont * filter threw this exception synchronously, which means exceptions may be mapped via * exception mappers, response filters will run and async response callbacks will be * called with this exception. - * + * * @param t the exception to send back to the client, as mapped by the application. */ void resume(Throwable t); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerResponseContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerResponseContext.java index e5ad9bfae56..7e4f6596f79 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerResponseContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/interception/jaxrs/SuspendableContainerResponseContext.java @@ -13,9 +13,9 @@ public interface SuspendableContainerResponseContext extends ContainerResponseCo /** * Suspends the current response. This makes the current request asynchronous. No * further response filter is executed until this response is resumed. - * + * * No reply is going to be sent to the client until this response is resumed either - * with {@link #resume()} or aborted with {@link #resume(Throwable)} or + * with {@link #resume()} or aborted with {@link #resume(Throwable)} or * {@link org.jboss.resteasy.core.interception.ResponseContainerRequestContext#abortWith(javax.ws.rs.core.Response)}. */ void suspend(); @@ -31,7 +31,7 @@ public interface SuspendableContainerResponseContext extends ContainerResponseCo * filter threw this exception synchronously, which means that the exception will not * be mapped by exception mappers, the response filters will stop running, and the * async response callbacks will be called with this exception. - * + * * @param t the exception to send back to the client, as an internal server error. */ void resume(Throwable t); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/ReaderUtility.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/ReaderUtility.java index 319a97b9098..087bd0e4425 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/ReaderUtility.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/ReaderUtility.java @@ -33,26 +33,26 @@ public abstract class ReaderUtility private ReaderInterceptor[] interceptors; public static T read(Class type, String contentType, String buffer) - throws IOException + throws IOException { return read(type, contentType, buffer.getBytes()); } public static T read(Class type, String contentType, byte[] buffer) - throws IOException + throws IOException { return read(type, MediaType.valueOf(contentType), - new ByteArrayInputStream(buffer)); + new ByteArrayInputStream(buffer)); } public static T read(Class type, MediaType mediaType, byte[] buffer) - throws IOException + throws IOException { return read(type, mediaType, new ByteArrayInputStream(buffer)); } public static T read(Class type, MediaType mt, InputStream is) - throws IOException + throws IOException { return new ReaderUtility() { @@ -78,14 +78,14 @@ public ReaderUtility(ResteasyProviderFactory factory, } public T doRead(Class type, MediaType mediaType, InputStream is) - throws IOException + throws IOException { return doRead(type, type, mediaType, null, null, is); } public T doRead(Class type, Type genericType, MediaType mediaType, MultivaluedMap requestHeaders, InputStream is) - throws IOException + throws IOException { return doRead(type, genericType, mediaType, null, requestHeaders, is); } @@ -94,13 +94,13 @@ public Object doRead(HttpRequest request, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) throws IOException { return doRead(type, genericType, mediaType, annotations, request - .getHttpHeaders().getRequestHeaders(), request.getInputStream()); + .getHttpHeaders().getRequestHeaders(), request.getInputStream()); } public T doRead(Class type, Type genericType, MediaType mediaType, Annotation[] annotations, MultivaluedMap requestHeaders, InputStream inputStream) - throws IOException + throws IOException { try { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/WriterUtility.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/WriterUtility.java index 0ca8dd2bdc6..eade8074267 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/WriterUtility.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/messagebody/WriterUtility.java @@ -32,13 +32,13 @@ public abstract class WriterUtility private WriterInterceptor[] interceptors; public static String asString(Object toOutput, String contentType) - throws IOException + throws IOException { return new String(getBytes(toOutput, contentType)); } public static byte[] getBytes(Object toOutput, String contentType) - throws IOException + throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); write(toOutput, MediaType.valueOf(contentType), bos); @@ -46,7 +46,7 @@ public static byte[] getBytes(Object toOutput, String contentType) } public static void write(Object toOutput, MediaType mt, OutputStream os) - throws IOException + throws IOException { new WriterUtility() { @@ -72,21 +72,21 @@ public WriterUtility(ResteasyProviderFactory factory, } public void doWrite(Object toOutput, MediaType mediaType, OutputStream os) - throws IOException + throws IOException { doWrite(toOutput, toOutput.getClass(), mediaType, os); } public void doWrite(Object toOutput, Class type, MediaType mediaType, OutputStream os) - throws IOException + throws IOException { doWrite(toOutput, type, type, mediaType, null, null, os); } public void doWrite(Object toOutput, Class type, Type genericType, MediaType mediaType, MultivaluedMap requestHeaders, OutputStream os) - throws IOException + throws IOException { doWrite(toOutput, type, genericType, mediaType, null, requestHeaders, os); } @@ -95,7 +95,7 @@ public void doWrite(HttpResponse response, Object toOutput, Class type, Type gen Annotation[] annotations, MediaType mediaType) throws IOException { doWrite(toOutput, type, genericType, mediaType, annotations, response - .getOutputHeaders(), response.getOutputStream()); + .getOutputHeaders(), response.getOutputStream()); } public void doWrite(Object toOutput, Class type, Type genericType, @@ -105,9 +105,9 @@ public void doWrite(Object toOutput, Class type, Type genericType, { final Map attributes = new HashMap(); AbstractWriterInterceptorContext messageBodyWriterContext = new ClientWriterInterceptorContext(interceptors, factory, toOutput, type, - genericType, annotations, mediaType, requestHeaders, outputStream, attributes); + genericType, annotations, mediaType, requestHeaders, outputStream, attributes); messageBodyWriterContext - .proceed(); + .proceed(); } public abstract RuntimeException createWriterNotFound(Type genericType, diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/MethodExpression.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/MethodExpression.java index 96b174bd56e..7fb1cfabd75 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/MethodExpression.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/MethodExpression.java @@ -29,11 +29,11 @@ public int compareTo(Expression expression) MethodExpression me = (MethodExpression)expression; if (this.invoker instanceof ResourceMethodInvoker && me.invoker instanceof ResourceLocatorInvoker) { - return -1; + return -1; } if (this.invoker instanceof ResourceLocatorInvoker && me.invoker instanceof ResourceMethodInvoker) { - return 1; + return 1; } return 0; } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/SegmentNode.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/SegmentNode.java index 964594a4737..82a1fc2c034 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/SegmentNode.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/registry/SegmentNode.java @@ -319,7 +319,7 @@ public MediaType getAcceptType() { String name = entry.getKey(); if ("q".equals(name) - || "qs".equals(name)) continue; + || "qs".equals(name)) continue; params.put(name, entry.getValue()); } Annotation[] annotations = match.expression.invoker.getMethod().getAnnotations(); @@ -454,7 +454,7 @@ public Match match(List matches, String httpMethod, HttpRequest request) if (httpMethod.equals("OPTIONS")) { - + ResponseBuilder resBuilder = Response.ok(allowHeaderValue.toString(), MediaType.TEXT_PLAIN_TYPE).header(HttpHeaderNames.ALLOW, allowHeaderValue.toString()); if (allowed.contains("PATCH")) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/request/ServerDrivenNegotiation.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/request/ServerDrivenNegotiation.java index 2a9b37a6521..3cf5ded5d29 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/request/ServerDrivenNegotiation.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/core/request/ServerDrivenNegotiation.java @@ -347,8 +347,8 @@ private boolean hasRequiredParameters(Map required, Map map = parser.parse(newCookie, ';'); - - for (Map.Entry entry : map.entrySet()) { - String name = entry.getKey(); - String value = entry.getValue(); - if (name.equalsIgnoreCase("Comment")) - comment = value; - else if (name.equalsIgnoreCase("Domain")) - domain = value; - else if (name.equalsIgnoreCase("Max-Age")) - maxAge = Integer.parseInt(value); - else if (name.equalsIgnoreCase("Path")) - path = value; - else if (name.equalsIgnoreCase("Secure")) - secure = true; - else if (name.equalsIgnoreCase("Version")) - version = Integer.parseInt(value); - else if (name.equalsIgnoreCase("HttpOnly")) - httpOnly = true; - else if (name.equalsIgnoreCase("Expires")) { - try - { - expiry = new SimpleDateFormat(OLD_COOKIE_PATTERN, Locale.US).parse(value); - } - catch (ParseException e) - { - } - } else { - cookieName = name; - cookieValue = value; + private final static String OLD_COOKIE_PATTERN = "EEE, dd-MMM-yyyy HH:mm:ss z"; + + public Object fromString(String newCookie) throws IllegalArgumentException { + if (newCookie == null) throw new IllegalArgumentException(Messages.MESSAGES.newCookieValueNull()); + String cookieName = null; + String cookieValue = null; + String comment = null; + String domain = null; + int maxAge = NewCookie.DEFAULT_MAX_AGE; + String path = null; + boolean secure = false; + int version = NewCookie.DEFAULT_VERSION; + boolean httpOnly = false; + Date expiry = null; + + ParameterParser parser = new ParameterParser(); + Map map = parser.parse(newCookie, ';'); + + for (Map.Entry entry : map.entrySet()) { + String name = entry.getKey(); + String value = entry.getValue(); + if (name.equalsIgnoreCase("Comment")) + comment = value; + else if (name.equalsIgnoreCase("Domain")) + domain = value; + else if (name.equalsIgnoreCase("Max-Age")) + maxAge = Integer.parseInt(value); + else if (name.equalsIgnoreCase("Path")) + path = value; + else if (name.equalsIgnoreCase("Secure")) + secure = true; + else if (name.equalsIgnoreCase("Version")) + version = Integer.parseInt(value); + else if (name.equalsIgnoreCase("HttpOnly")) + httpOnly = true; + else if (name.equalsIgnoreCase("Expires")) { + try + { + expiry = new SimpleDateFormat(OLD_COOKIE_PATTERN, Locale.US).parse(value); } - - } - - if (cookieValue == null) - { - cookieValue = ""; - } - - return new NewCookie(cookieName, cookieValue, path, domain, version, comment, maxAge, expiry, secure, httpOnly); - - } - - protected void quote(StringBuilder b, String value) { - - if (MediaTypeHeaderDelegate.quoted(value)) { - b.append('"'); - b.append(value); - b.append('"'); - } else { - b.append(value); - } - } - - public String toString(Object value) { - if (value == null) throw new IllegalArgumentException(Messages.MESSAGES.paramNull()); - NewCookie cookie = (NewCookie) value; - StringBuilder b = new StringBuilder(); - - b.append(cookie.getName()).append('='); - - if (cookie.getValue() != null) { - quote(b, cookie.getValue()); - } - - b.append(";").append("Version=").append(cookie.getVersion()); - - if (cookie.getComment() != null) { - b.append(";Comment="); - quote(b, cookie.getComment()); - } - if (cookie.getDomain() != null) { - b.append(";Domain="); - quote(b, cookie.getDomain()); - } - if (cookie.getPath() != null) { - b.append(";Path="); - b.append(cookie.getPath()); - } - if (cookie.getMaxAge() != -1) { - b.append(";Max-Age="); - b.append(cookie.getMaxAge()); - } - if (cookie.getExpiry() != null) { - b.append(";Expires="); - b.append(DateUtil.formatDate(cookie.getExpiry(), OLD_COOKIE_PATTERN)); - } - if (cookie.isSecure()) - b.append(";Secure"); - if (cookie.isHttpOnly()) - b.append(";HttpOnly"); - return b.toString(); - } + catch (ParseException e) + { + } + } else { + cookieName = name; + cookieValue = value; + } + + } + + if (cookieValue == null) + { + cookieValue = ""; + } + + return new NewCookie(cookieName, cookieValue, path, domain, version, comment, maxAge, expiry, secure, httpOnly); + + } + + protected void quote(StringBuilder b, String value) { + + if (MediaTypeHeaderDelegate.quoted(value)) { + b.append('"'); + b.append(value); + b.append('"'); + } else { + b.append(value); + } + } + + public String toString(Object value) { + if (value == null) throw new IllegalArgumentException(Messages.MESSAGES.paramNull()); + NewCookie cookie = (NewCookie) value; + StringBuilder b = new StringBuilder(); + + b.append(cookie.getName()).append('='); + + if (cookie.getValue() != null) { + quote(b, cookie.getValue()); + } + + b.append(";").append("Version=").append(cookie.getVersion()); + + if (cookie.getComment() != null) { + b.append(";Comment="); + quote(b, cookie.getComment()); + } + if (cookie.getDomain() != null) { + b.append(";Domain="); + quote(b, cookie.getDomain()); + } + if (cookie.getPath() != null) { + b.append(";Path="); + b.append(cookie.getPath()); + } + if (cookie.getMaxAge() != -1) { + b.append(";Max-Age="); + b.append(cookie.getMaxAge()); + } + if (cookie.getExpiry() != null) { + b.append(";Expires="); + b.append(DateUtil.formatDate(cookie.getExpiry(), OLD_COOKIE_PATTERN)); + } + if (cookie.isSecure()) + b.append(";Secure"); + if (cookie.isHttpOnly()) + b.append(";HttpOnly"); + return b.toString(); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/ServerCookie.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/ServerCookie.java index 33a3af8a8c7..821f740d0b2 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/ServerCookie.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/delegates/ServerCookie.java @@ -19,14 +19,14 @@ public class ServerCookie implements Serializable private static final String tspecials2 = "()<>@,;:\\\"/[]?={} \t"; /* - * Tests a string and returns true if the string counts as a - * reserved token in the Java language. - * - * @param value the String to be tested - * - * @return true if the String is a reserved - * token; false if it is not - */ + * Tests a string and returns true if the string counts as a + * reserved token in the Java language. + * + * @param value the String to be tested + * + * @return true if the String is a reserved + * token; false if it is not + */ public static boolean isToken(String value) { if (value == null) return true; @@ -82,16 +82,16 @@ public static boolean isToken2(String value) public static boolean checkName(String name) { if (!isToken(name) - || name.equalsIgnoreCase("Comment") // rfc2019 - || name.equalsIgnoreCase("Discard") // rfc2965 - || name.equalsIgnoreCase("Domain") // rfc2019 - || name.equalsIgnoreCase("Expires") // Netscape - || name.equalsIgnoreCase("Max-Age") // rfc2019 - || name.equalsIgnoreCase("Path") // rfc2019 - || name.equalsIgnoreCase("Secure") // rfc2019 - || name.equalsIgnoreCase("Version") // rfc2019 + || name.equalsIgnoreCase("Comment") // rfc2019 + || name.equalsIgnoreCase("Discard") // rfc2965 + || name.equalsIgnoreCase("Domain") // rfc2019 + || name.equalsIgnoreCase("Expires") // Netscape + || name.equalsIgnoreCase("Max-Age") // rfc2019 + || name.equalsIgnoreCase("Path") // rfc2019 + || name.equalsIgnoreCase("Secure") // rfc2019 + || name.equalsIgnoreCase("Version") // rfc2019 // TODO remaining RFC2965 attributes - ) + ) { return false; } @@ -169,14 +169,14 @@ public static void formatOldCookie(Date d, StringBuffer sb, // TODO RFC2965 fields also need to be passed public static void appendCookieValue(StringBuffer headerBuf, - int version, - String name, - String value, - String path, - String domain, - String comment, - int maxAge, - boolean isSecure) + int version, + String name, + String value, + String path, + String domain, + String comment, + int maxAge, + boolean isSecure) { StringBuffer buf = new StringBuffer(); // Servlet implementation checks name diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFeature.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFeature.java index c2e6d4461a4..1810535d5ee 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFeature.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFeature.java @@ -79,9 +79,9 @@ protected CacheControl initCacheControl(Cache methodCached) protected CacheControl initCacheControl(NoCache value) { CacheControl cacheControl = new CacheControl(); - cacheControl.setNoCache(true); - cacheControl.setNoTransform(false); - for (String field : value.fields()) cacheControl.getNoCacheFields().add(field); + cacheControl.setNoCache(true); + cacheControl.setNoTransform(false); + for (String field : value.fields()) cacheControl.getNoCacheFields().add(field); return cacheControl; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFilter.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFilter.java index 2d79b1a9cff..ece34f8381a 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFilter.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/CacheControlFilter.java @@ -31,4 +31,4 @@ public void filter(ContainerRequestContext requestContext, ContainerResponseCont responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cacheControl); } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/RoleBasedSecurityFeature.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/RoleBasedSecurityFeature.java index 41cd2ed4772..b7f925bb8df 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/RoleBasedSecurityFeature.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/RoleBasedSecurityFeature.java @@ -35,12 +35,12 @@ public void configure(ResourceInfo resourceInfo, FeatureContext configurable) } denyAll = (declaring.isAnnotationPresent(DenyAll.class) - && method.isAnnotationPresent(RolesAllowed.class) == false - && method.isAnnotationPresent(PermitAll.class) == false) || method.isAnnotationPresent(DenyAll.class); + && method.isAnnotationPresent(RolesAllowed.class) == false + && method.isAnnotationPresent(PermitAll.class) == false) || method.isAnnotationPresent(DenyAll.class); permitAll = (declaring.isAnnotationPresent(PermitAll.class) == true - && method.isAnnotationPresent(RolesAllowed.class) == false - && method.isAnnotationPresent(DenyAll.class) == false) || method.isAnnotationPresent(PermitAll.class); + && method.isAnnotationPresent(RolesAllowed.class) == false + && method.isAnnotationPresent(DenyAll.class) == false) || method.isAnnotationPresent(PermitAll.class); if (rolesAllowed != null || denyAll || permitAll) { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/GZIPDecodingInterceptor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/GZIPDecodingInterceptor.java index 8cdc6c50651..764adf57a73 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/GZIPDecodingInterceptor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/GZIPDecodingInterceptor.java @@ -30,21 +30,21 @@ @Priority(Priorities.ENTITY_CODER) public class GZIPDecodingInterceptor implements ReaderInterceptor { - private static final int DEFAULT_MAX_SIZE = 10000000; - private int maxSize; - - public GZIPDecodingInterceptor(int maxSize) - { - this.maxSize = maxSize; - } - - public GZIPDecodingInterceptor() - { - this.maxSize = -1; - } + private static final int DEFAULT_MAX_SIZE = 10000000; + private int maxSize; - public static class FinishableGZIPInputStream extends GZIPInputStream - { + public GZIPDecodingInterceptor(int maxSize) + { + this.maxSize = maxSize; + } + + public GZIPDecodingInterceptor() + { + this.maxSize = -1; + } + + public static class FinishableGZIPInputStream extends GZIPInputStream + { private int maxSize; private int count; private boolean server; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/MessageSanitizerContainerResponseFilter.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/MessageSanitizerContainerResponseFilter.java index 2ee5fb8bff7..ddda7c6dc1f 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/MessageSanitizerContainerResponseFilter.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/MessageSanitizerContainerResponseFilter.java @@ -27,85 +27,84 @@ @Provider @Priority(Priorities.ENTITY_CODER) public class MessageSanitizerContainerResponseFilter implements ContainerResponseFilter { - @Override - public void filter(ContainerRequestContext requestContext, - ContainerResponseContext responseContext) throws IOException { + @Override + public void filter(ContainerRequestContext requestContext, + ContainerResponseContext responseContext) throws IOException { - ResteasyDeployment deployment = ResteasyProviderFactory.getContextData(ResteasyDeployment.class); - if (deployment != null) - { - Boolean disable = (Boolean) deployment.getProperty(ResteasyContextParameters.RESTEASY_DISABLE_HTML_SANITIZER); - if (disable != null && disable) - { - return; + ResteasyDeployment deployment = ResteasyProviderFactory.getContextData(ResteasyDeployment.class); + if (deployment != null) + { + Boolean disable = (Boolean) deployment.getProperty(ResteasyContextParameters.RESTEASY_DISABLE_HTML_SANITIZER); + if (disable != null && disable) + { + return; + } + } + if (HttpResponseCodes.SC_BAD_REQUEST == responseContext.getStatus()) { + Object entity = responseContext.getEntity(); + if (entity != null && entity instanceof String) { + ArrayList contentTypes = (ArrayList)responseContext.getHeaders().get("Content-Type"); + if (contentTypes != null && containsHtmlText(contentTypes)) { + String escapedMsg = escapeXml((String) entity); + responseContext.setEntity(escapedMsg); } - } - if (HttpResponseCodes.SC_BAD_REQUEST == responseContext.getStatus()) { - Object entity = responseContext.getEntity(); - if (entity != null && entity instanceof String) { - ArrayList contentTypes = (ArrayList)responseContext.getHeaders().get("Content-Type"); - if (contentTypes != null && containsHtmlText(contentTypes)) { - String escapedMsg = escapeXml((String) entity); - responseContext.setEntity(escapedMsg); - } - } - } - } - + } + } + } - // set of replacement chars to hex encoding - private static final HashMap replacementMap; - static { - replacementMap = new HashMap(); - replacementMap.put("/", "/"); - replacementMap.put("<", "<"); - replacementMap.put(">", ">"); - replacementMap.put("&", "&"); - replacementMap.put("\"", """); - replacementMap.put("'", "'"); - } - /** - * Replace char with the hex encoding - * @param str - * @return - */ - private String escapeXml(String str) { - StringBuilder sb = new StringBuilder(); - if (!str.isEmpty()) { - // the vertical bar, |, is a special regular expression char that - // causes splitting on individual characters. - for (String key : str.split("|")) { - String value = replacementMap.get(key); - if (value == null) { - sb.append(key); - } else { - sb.append(value); - } + // set of replacement chars to hex encoding + private static final HashMap replacementMap; + static { + replacementMap = new HashMap(); + replacementMap.put("/", "/"); + replacementMap.put("<", "<"); + replacementMap.put(">", ">"); + replacementMap.put("&", "&"); + replacementMap.put("\"", """); + replacementMap.put("'", "'"); + } + /** + * Replace char with the hex encoding + * @param str + * @return + */ + private String escapeXml(String str) { + StringBuilder sb = new StringBuilder(); + if (!str.isEmpty()) { + // the vertical bar, |, is a special regular expression char that + // causes splitting on individual characters. + for (String key : str.split("|")) { + String value = replacementMap.get(key); + if (value == null) { + sb.append(key); + } else { + sb.append(value); } - } - return sb.toString(); - } - private boolean containsHtmlText(ArrayList list) { - for (Object o : list) { - if (o instanceof MediaType && MediaType.TEXT_HTML_TYPE.isCompatible((MediaType) o)) { - return true; - } - if (o instanceof String) { - String mediaType = (String) o; - String[] partsType = mediaType.split("/"); - if (partsType.length >= 2) { - String[] partsSubtype = partsType[1].split(";"); - if (partsType[0].trim().equalsIgnoreCase("text") && - partsSubtype[0].trim().toLowerCase().equals("html")) { - return true; - } - } - } - } - return false; - } -} + } + } + return sb.toString(); + } + private boolean containsHtmlText(ArrayList list) { + for (Object o : list) { + if (o instanceof MediaType && MediaType.TEXT_HTML_TYPE.isCompatible((MediaType) o)) { + return true; + } + if (o instanceof String) { + String mediaType = (String) o; + String[] partsType = mediaType.split("/"); + if (partsType.length >= 2) { + String[] partsSubtype = partsType[1].split(";"); + if (partsType[0].trim().equalsIgnoreCase("text") && + partsSubtype[0].trim().toLowerCase().equals("html")) { + return true; + } + } + } + } + return false; + } +} \ No newline at end of file diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFeature.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFeature.java index c47cad04cf5..d8c812b445e 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFeature.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFeature.java @@ -65,7 +65,7 @@ protected Set getEncodings(Annotation[] annotations) { if (annotation.annotationType().isAnnotationPresent(ContentEncoding.class)) { - encodings.add(annotation.annotationType().getAnnotation(ContentEncoding.class).value().toLowerCase()); + encodings.add(annotation.annotationType().getAnnotation(ContentEncoding.class).value().toLowerCase()); } } return encodings; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFilter.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFilter.java index fecf602324e..2ecda7dde60 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFilter.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/interceptors/encoding/ServerContentEncodingAnnotationFilter.java @@ -24,9 +24,7 @@ @Priority(Priorities.HEADER_DECORATOR) public class ServerContentEncodingAnnotationFilter implements WriterInterceptor { - protected - @Context - HttpRequest request; + protected @Context HttpRequest request; Set encodings; @@ -59,4 +57,4 @@ public void aroundWriteTo(WriterInterceptorContext context) throws IOException, } context.proceed(); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/AbstractEntityProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/AbstractEntityProvider.java index 0f61bf890c8..cd322b94cb3 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/AbstractEntityProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/AbstractEntityProvider.java @@ -17,7 +17,7 @@ * @version $Revision: $ */ public abstract class AbstractEntityProvider - implements MessageBodyReader, MessageBodyWriter + implements MessageBodyReader, MessageBodyWriter { public long getSize(T t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DataSourceProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DataSourceProvider.java index 86237456162..50c467348d9 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DataSourceProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DataSourceProvider.java @@ -105,22 +105,22 @@ public static DataSource readDataSource(final InputStream in, final MediaType me byte[] buffer = new byte[4096]; int count = in.read(buffer, 0, buffer.length); if (count > -1) { - tempFile = File.createTempFile("resteasy-provider-datasource", null); - Cleanables cleanables = ResteasyProviderFactory.getContextData(Cleanables.class); - if (cleanables != null) - { - cleanables.addCleanable(new TempFileCleanable(tempFile)); - } - FileOutputStream fos = new FileOutputStream(tempFile); - fos.write(buffer, 0, count); - try - { - ProviderHelper.writeTo(in, fos); - } - finally - { - fos.close(); - } + tempFile = File.createTempFile("resteasy-provider-datasource", null); + Cleanables cleanables = ResteasyProviderFactory.getContextData(Cleanables.class); + if (cleanables != null) + { + cleanables.addCleanable(new TempFileCleanable(tempFile)); + } + FileOutputStream fos = new FileOutputStream(tempFile); + fos.write(buffer, 0, count); + try + { + ProviderHelper.writeTo(in, fos); + } + finally + { + fos.close(); + } } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DocumentProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DocumentProvider.java index 4923c52b4d1..e7769280446 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DocumentProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/DocumentProvider.java @@ -85,9 +85,9 @@ public boolean isReadable(Class clazz, Type type, } public Document readFrom(Class clazz, Type type, - Annotation[] annotations, MediaType mediaType, - MultivaluedMap headers, InputStream input) - throws IOException, WebApplicationException + Annotation[] annotations, MediaType mediaType, + MultivaluedMap headers, InputStream input) + throws IOException, WebApplicationException { LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); try @@ -125,7 +125,7 @@ public boolean isWriteable(Class clazz, Type type, public void writeTo(Document document, Class clazz, Type type, Annotation[] annotation, MediaType mediaType, MultivaluedMap headers, OutputStream output) - throws IOException, WebApplicationException + throws IOException, WebApplicationException { LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); try diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FileProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FileProvider.java index 4c97f9216d6..f0f8a118c00 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FileProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FileProvider.java @@ -36,7 +36,7 @@ @Produces("*/*") @Consumes("*/*") public class FileProvider implements MessageBodyReader, - MessageBodyWriter + MessageBodyWriter { private static final Logger LOG = Logger.getLogger(FileProvider.class); @@ -57,7 +57,7 @@ public boolean isReadable(Class type, Type genericType, public File readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) - throws IOException + throws IOException { LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); File downloadedFile = null; @@ -67,7 +67,7 @@ public File readFrom(Class type, Type genericType, try { downloadedFile = File.createTempFile(PREFIX, SUFFIX, new File( - _downloadDirectory)); + _downloadDirectory)); } catch (final IOException ex) { @@ -92,7 +92,7 @@ public File readFrom(Class type, Type genericType, if (NoContent.isContentLengthZero(httpHeaders)) return downloadedFile; OutputStream output = new BufferedOutputStream(new FileOutputStream( - downloadedFile)); + downloadedFile)); try { @@ -139,9 +139,9 @@ public void writeTo(File uploadFile, Class type, Type genericType, int byteUnit = range.indexOf("bytes="); if ( byteUnit < 0) { - //must start with 'bytes' - writeIt(uploadFile, entityStream); - return; + //must start with 'bytes' + writeIt(uploadFile, entityStream); + return; } range = range.substring("bytes=".length()); if (range.indexOf(',') > -1) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FormUrlEncodedProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FormUrlEncodedProvider.java index 371cd12af19..6b7768cf889 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FormUrlEncodedProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/FormUrlEncodedProvider.java @@ -69,7 +69,7 @@ public MultivaluedMap readFrom(Class type, Type genericType, Ann } public static MultivaluedMap parseForm(InputStream entityStream, String charset) - throws IOException + throws IOException { char[] buffer = new char[100]; StringBuffer buf = new StringBuffer(); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProvider.java index f9b0bd253e3..3cfc526909c 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProvider.java @@ -107,11 +107,11 @@ public boolean isReadable(Class type, Type genericType, Annotation[] annotati * Only effective if thrown prior to the response being committed. */ public IIOImage readFrom(Class type, - Type genericType, - Annotation[] annotations, - MediaType mediaType, - MultivaluedMap httpHeaders, - InputStream entityStream) throws IOException + Type genericType, + Annotation[] annotations, + MediaType mediaType, + MultivaluedMap httpHeaders, + InputStream entityStream) throws IOException { LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); ImageReader reader = IIOImageProviderHelper.getImageReaderByMediaType(mediaType); @@ -188,7 +188,7 @@ public void writeTo(IIOImage t, * maximum */ ImageWriterParams writerParams = FindAnnotation.findAnnotation(annotations, - ImageWriterParams.class); + ImageWriterParams.class); if (writerParams != null) { if (param.canWriteCompressed()) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProviderHelper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProviderHelper.java index 42c0ca62a14..830849b7778 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProviderHelper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/IIOImageProviderHelper.java @@ -68,7 +68,7 @@ public static ImageWriter getImageWriterByMediaType(MediaType mediaType) * @throws IOException if I/O error occurred */ public static IIOImage readImage(InputStream in, ImageReader reader, int imageIndex) - throws IOException + throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(in); reader.setInput(iis, false); @@ -117,7 +117,7 @@ public static void writeImage(Annotation[] annotations, ImageWriter writer, OutputStream out, IIOImage image) - throws IOException + throws IOException { ImageWriteParam param; if (mediaType.equals(MediaType.valueOf("image/jpeg"))) @@ -134,7 +134,7 @@ public static void writeImage(Annotation[] annotations, * maximum */ ImageWriterParams writerParams = - FindAnnotation.findAnnotation(annotations, ImageWriterParams.class); + FindAnnotation.findAnnotation(annotations, ImageWriterParams.class); if (writerParams != null) { if (param.canWriteCompressed()) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/InputStreamProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/InputStreamProvider.java index f6b359dce5d..3fb1594e12a 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/InputStreamProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/InputStreamProvider.java @@ -49,23 +49,23 @@ public long getSize(InputStream inputStream, Class type, Type genericType, An public void writeTo(InputStream inputStream, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { - LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); - try - { - int c = inputStream.read(); - if (c == -1) - { - httpHeaders.putSingle(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(0)); - entityStream.write(new byte[0]); // fix RESTEASY-204 - return; - } - else - entityStream.write(c); + LogMessages.LOGGER.debugf("Provider : %s, Method : writeTo", getClass().getName()); + try + { + int c = inputStream.read(); + if (c == -1) + { + httpHeaders.putSingle(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(0)); + entityStream.write(new byte[0]); // fix RESTEASY-204 + return; + } + else + entityStream.write(c); ProviderHelper.writeTo(inputStream, entityStream); - } - finally - { + } + finally + { inputStream.close(); - } + } } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ProviderHelper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ProviderHelper.java index 06ed730cc33..7d00ff29e2f 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ProviderHelper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ProviderHelper.java @@ -128,4 +128,4 @@ public static void writeTo(final InputStream in, final OutputStream out) throws out.write(buf, 0, read); } } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ReaderProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ReaderProvider.java index 071ab3fa298..ae558f210c1 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ReaderProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/ReaderProvider.java @@ -53,33 +53,33 @@ public long getSize(Reader inputStream, Class type, Type genericType, Annotat public void writeTo(Reader inputStream, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException { - LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); - try - { - int c = inputStream.read(); - if (c == -1) - { - httpHeaders.putSingle(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(0)); - entityStream.write(new byte[0]); // fix RESTEASY-204 - return; - } - else - entityStream.write(c); - while ((c = inputStream.read()) != -1) - { - entityStream.write(c); - } - } - finally - { - try - { - inputStream.close(); - } - catch (IOException e) - { - // Drop the exception so we don't mask real IO errors - } - } + LogMessages.LOGGER.debugf("Provider : %s, Method : readFrom", getClass().getName()); + try + { + int c = inputStream.read(); + if (c == -1) + { + httpHeaders.putSingle(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(0)); + entityStream.write(new byte[0]); // fix RESTEASY-204 + return; + } + else + entityStream.write(c); + while ((c = inputStream.read()) != -1) + { + entityStream.write(c); + } + } + finally + { + try + { + inputStream.close(); + } + catch (IOException e) + { + // Drop the exception so we don't mask real IO errors + } + } } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/StringTextStar.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/StringTextStar.java index 7a831476b30..82411d3b530 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/StringTextStar.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/StringTextStar.java @@ -65,4 +65,4 @@ public void writeTo(String o, else entityStream.write(o.getBytes(charset)); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/OutboundSseEventImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/OutboundSseEventImpl.java index 60dda6fef77..03dbf02627c 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/OutboundSseEventImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/OutboundSseEventImpl.java @@ -131,10 +131,10 @@ public Builder data(Object data) if (data instanceof GenericEntity) { - GenericEntity genericEntity = (GenericEntity) data; - this.type = genericEntity.getRawType(); - this.genericType = genericEntity.getType(); - this.data = genericEntity.getEntity(); + GenericEntity genericEntity = (GenericEntity) data; + this.type = genericEntity.getRawType(); + this.genericType = genericEntity.getType(); + this.data = genericEntity.getEntity(); } else { @@ -146,10 +146,10 @@ public Builder data(Object data) public OutboundSseEvent build() { - if (this.comment == null && this.data == null) - { - throw new IllegalArgumentException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("comment or data")); - } + if (this.comment == null && this.data == null) + { + throw new IllegalArgumentException(Messages.MESSAGES.nullValueSetToCreateOutboundSseEvent("comment or data")); + } return new OutboundSseEventImpl(name, id, reconnectDelay, type, genericType, mediaType, data, comment); } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventInputImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventInputImpl.java index 82cb4f3fb01..cf17bb60780 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventInputImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventInputImpl.java @@ -186,21 +186,21 @@ private int readLine(final InputStream in, final int delimiter, final OutputStre { if (!textLike && escape && b == '\\') { - b = in.read(); - if (b != '\\' && b != '\n' && b != '\r') - { - throw new RuntimeException(Messages.MESSAGES.expectedExcapedCharacter(b)); - } - out.write(b); - continue; + b = in.read(); + if (b != '\\' && b != '\n' && b != '\r') + { + throw new RuntimeException(Messages.MESSAGES.expectedExcapedCharacter(b)); + } + out.write(b); + continue; } if (b == delimiter || b == '\n' || b == '\r') { - break; + break; } else if (out != null) { - out.write(b); + out.write(b); } } return b; @@ -269,22 +269,22 @@ public byte[] readEvent(final InputStream in) throws IOException { if (b == '\r' || b == '\n') { - eolBuffer[pos] = b; - //if it meets \r\r , \n\n , \r\n\r\n or \n\r\n\r\n - if ((pos > 0 && eolBuffer[pos] == eolBuffer[pos - 1]) - || (pos >= 3 && new String(eolBuffer, 0, pos, StandardCharsets.UTF_8).contains(DELIMITER))) - { - boundary = true; - } - //take it a boundary if there are 5 unexpected eols - if (pos++ > 4) - { - boundary = true; - } + eolBuffer[pos] = b; + //if it meets \r\r , \n\n , \r\n\r\n or \n\r\n\r\n + if ((pos > 0 && eolBuffer[pos] == eolBuffer[pos - 1]) + || (pos >= 3 && new String(eolBuffer, 0, pos, StandardCharsets.UTF_8).contains(DELIMITER))) + { + boundary = true; + } + //take it a boundary if there are 5 unexpected eols + if (pos++ > 4) + { + boundary = true; + } } else { - pos = 0; + pos = 0; } } buffer.write(b); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputImpl.java index 6b43ff01993..18ce8e0a603 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputImpl.java @@ -159,7 +159,7 @@ private void internalFlushResponseToClient(boolean throwIOException) throws IOEx { ServerResponseWriter.writeNomapResponse(jaxrsResponse, request, response, ResteasyProviderFactory.getInstance(), t -> { - }, true); + }, true); response.getOutputStream().write(SseConstants.EOL); response.getOutputStream().write(SseConstants.EOL); response.flushBuffer(); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputProvider.java index 568d4d76216..778f302af3f 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventOutputProvider.java @@ -36,4 +36,4 @@ public void writeTo(final SseEventSink output, final Class type, final Type g { //no operation } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventProvider.java index 5dea6708360..83d0699daa2 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventProvider.java @@ -26,10 +26,8 @@ import org.jboss.resteasy.util.MediaTypeHelper; @Provider -@Produces( -{"text/event-stream", "application/x-stream-general"}) -@Consumes( -{"text/event-stream", "application/x-stream-general"}) +@Produces({"text/event-stream", "application/x-stream-general"}) +@Consumes({"text/event-stream", "application/x-stream-general"}) public class SseEventProvider implements MessageBodyWriter, MessageBodyReader { public static final MediaType GENERAL_STREAM_TYPE = new MediaType("application", "x-stream-general"); @@ -50,10 +48,9 @@ public long getSize(OutboundSseEvent t, Class type, Type genericType, Annotat } @Override - @SuppressWarnings( - {"unchecked"}) + @SuppressWarnings({"unchecked"}) public void writeTo(OutboundSseEvent event, Class type, Type genericType, Annotation[] annotations, - MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) + MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { Charset charset = StandardCharsets.UTF_8; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventSinkInterceptor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventSinkInterceptor.java index 3cb5e64eb9d..45c9f0bbe1a 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventSinkInterceptor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseEventSinkInterceptor.java @@ -29,16 +29,16 @@ public void filter(ContainerRequestContext requestContext) throws IOException if ((mode == Stream.MODE.GENERAL && ResteasyProviderFactory.getInstance().getAsyncStreamProvider(clazz) != null) || requestContext instanceof PostMatchContainerRequestContext && ((PostMatchContainerRequestContext) requestContext).getResourceMethod().isSse()) { - SseEventOutputImpl sink = new SseEventOutputImpl(new SseEventProvider()); - ResteasyProviderFactory.getContextDataMap().put(SseEventSink.class, sink); - ResteasyProviderFactory.getContextData(PostResourceMethodInvokers.class).addInvokers(new PostResourceMethodInvoker() - { - @Override - public void invoke() - { - sink.flushResponseToClient(); - } - }); + SseEventOutputImpl sink = new SseEventOutputImpl(new SseEventProvider()); + ResteasyProviderFactory.getContextDataMap().put(SseEventSink.class, sink); + ResteasyProviderFactory.getContextData(PostResourceMethodInvokers.class).addInvokers(new PostResourceMethodInvoker() + { + @Override + public void invoke() + { + sink.flushResponseToClient(); + } + }); } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseImpl.java index 9f1b5103e59..fa45c9be9fc 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/sse/SseImpl.java @@ -7,7 +7,7 @@ public class SseImpl implements Sse { - @Override + @Override public OutboundSseEvent.Builder newEventBuilder() { return new OutboundSseEventImpl.BuilderImpl(); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ConstraintTypeUtil11.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ConstraintTypeUtil11.java index ceaff351a7b..99209f45b49 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ConstraintTypeUtil11.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ConstraintTypeUtil11.java @@ -36,7 +36,7 @@ public ConstraintType.Type getConstraintType(Object o) Node secondNode = nodes.next(); if (secondNode.getKind() == ElementKind.PARAMETER || - secondNode.getKind() == ElementKind.CROSS_PARAMETER) + secondNode.getKind() == ElementKind.CROSS_PARAMETER) { return ConstraintType.Type.PARAMETER; } @@ -71,9 +71,9 @@ else if (secondNode.getKind() == ElementKind.RETURN_VALUE) String getterName = "is" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method m = getMethod(v.getLeafBean().getClass(), getterName); if (m.getReturnType().equals(boolean.class)) - { + { return ConstraintType.Type.PROPERTY; - } + } else { return ConstraintType.Type.FIELD; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ViolationsContainer.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ViolationsContainer.java index b09190a220d..0ba3273ff07 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ViolationsContainer.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/providers/validation/ViolationsContainer.java @@ -58,33 +58,33 @@ public void setTarget(Object target) public void addViolations(Set set) { - Iterator it = set.iterator(); - while (it.hasNext()) - { - ResteasyConstraintViolation violation = it.next(); - switch (violation.getConstraintType()) - { - case FIELD: - fieldViolations.add(violation); - break; + Iterator it = set.iterator(); + while (it.hasNext()) + { + ResteasyConstraintViolation violation = it.next(); + switch (violation.getConstraintType()) + { + case FIELD: + fieldViolations.add(violation); + break; - case PROPERTY: - propertyViolations.add(violation); - break; + case PROPERTY: + propertyViolations.add(violation); + break; - case CLASS: - classViolations.add(violation); - break; + case CLASS: + classViolations.add(violation); + break; - case PARAMETER: - parameterViolations.add(violation); - break; + case PARAMETER: + parameterViolations.add(violation); + break; - case RETURN_VALUE: - returnValueViolations.add(violation); - break; - } - } + case RETURN_VALUE: + returnValueViolations.add(violation); + break; + } + } } public void addFieldViolation(ResteasyConstraintViolation v) @@ -140,10 +140,10 @@ public List getReturnValueViolations() public int size() { return fieldViolations.size() + - propertyViolations.size() + - classViolations.size() + - parameterViolations.size() + - returnValueViolations.size(); + propertyViolations.size() + + classViolations.size() + + parameterViolations.size() + + returnValueViolations.size(); } public String toString() diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/resourcefactory/JndiComponentResourceFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/resourcefactory/JndiComponentResourceFactory.java index df54a8c6f27..de8aeac0eec 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/resourcefactory/JndiComponentResourceFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/resourcefactory/JndiComponentResourceFactory.java @@ -79,4 +79,4 @@ public Class getScannableClass() public void requestFinished(HttpRequest request, HttpResponse response, Object resource) { } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanable.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanable.java index b9e6c926d35..988347e5f41 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanable.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanable.java @@ -2,5 +2,5 @@ public interface Cleanable { - void clean() throws Exception; + void clean() throws Exception; } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanables.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanables.java index 2d4629b5ff5..3f67a7880c3 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanables.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Cleanables.java @@ -2,23 +2,23 @@ import java.util.HashSet; /** -* -* @author Ron Sigal -* @version $Revision: 1.1 $ -* -* Copyright Jul 23, 2015 -*/ + * + * @author Ron Sigal + * @version $Revision: 1.1 $ + * + * Copyright Jul 23, 2015 + */ public class Cleanables { - private HashSet cleanables = new HashSet(); + private HashSet cleanables = new HashSet(); - public HashSet getCleanables() - { - return cleanables; - } + public HashSet getCleanables() + { + return cleanables; + } - public void addCleanable(Cleanable cleanable) - { - cleanables.add(cleanable); - } + public void addCleanable(Cleanable cleanable) + { + cleanables.add(cleanable); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ConfigurationBootstrap.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ConfigurationBootstrap.java index dd14ca99f87..9360ff33274 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ConfigurationBootstrap.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ConfigurationBootstrap.java @@ -86,14 +86,14 @@ public ResteasyDeployment createDeployment() String resteasySecurity = getParameter(ResteasyContextParameters.RESTEASY_ROLE_BASED_SECURITY); if (resteasySecurity != null) { - boolean useResteasySecurity = parseBooleanParam(ResteasyContextParameters.RESTEASY_ROLE_BASED_SECURITY, resteasySecurity); - deployment.setSecurityEnabled(Boolean.valueOf(useResteasySecurity)); + boolean useResteasySecurity = parseBooleanParam(ResteasyContextParameters.RESTEASY_ROLE_BASED_SECURITY, resteasySecurity); + deployment.setSecurityEnabled(Boolean.valueOf(useResteasySecurity)); } String builtin = getParameter(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS); if (builtin != null) { - boolean useBuiltin = parseBooleanParam(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS, builtin); - deployment.setRegisterBuiltin(useBuiltin); + boolean useBuiltin = parseBooleanParam(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS, builtin); + deployment.setRegisterBuiltin(useBuiltin); } @@ -271,19 +271,19 @@ public ResteasyDeployment createDeployment() return deployment; } - private boolean parseBooleanParam(String key, String value) { - value = value.trim().toLowerCase(); - if (value.equals("true") || value.equals("1")) { - return true; - } else if (value.equals("false") || value.equals("0")) { - return false; - } else { - throw new RuntimeException(Messages.MESSAGES.keyCouldNotBeParsed(key)); + private boolean parseBooleanParam(String key, String value) { + value = value.trim().toLowerCase(); + if (value.equals("true") || value.equals("1")) { + return true; + } else if (value.equals("false") || value.equals("0")) { + return false; + } else { + throw new RuntimeException(Messages.MESSAGES.keyCouldNotBeParsed(key)); - } - } + } + } - protected Map parseMap(String map) + protected Map parseMap(String map) { Map parsed = new HashMap(); String[] entries = map.trim().split(","); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/FilterBootstrap.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/FilterBootstrap.java index d53a027a6fb..1a3421927c6 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/FilterBootstrap.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/FilterBootstrap.java @@ -61,4 +61,4 @@ public Set getInitParameterNames() while (en.hasMoreElements()) set.add(en.nextElement()); return set; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrapClasses.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrapClasses.java index 0b1f1349368..acbc533e215 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrapClasses.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ResteasyBootstrapClasses.java @@ -9,14 +9,14 @@ public interface ResteasyBootstrapClasses { String[] BOOTSTRAP_CLASSES = { - HttpServletDispatcher.class.getName(), - ResteasyBootstrap.class.getName(), - "org.springframework.web.servlet.DispatcherServlet", - FilterDispatcher.class.getName(), - "org.jboss.resteasy.plugins.server.servlet.JBossWebDispatcherServlet", - "org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher", - "org.jboss.resteasy.plugins.server.servlet.Filter30Dispatcher", - "org.jboss.resteasy.plugins.server.servlet.Tomcat6CometDispatcherServlet" + HttpServletDispatcher.class.getName(), + ResteasyBootstrap.class.getName(), + "org.springframework.web.servlet.DispatcherServlet", + FilterDispatcher.class.getName(), + "org.jboss.resteasy.plugins.server.servlet.JBossWebDispatcherServlet", + "org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher", + "org.jboss.resteasy.plugins.server.servlet.Filter30Dispatcher", + "org.jboss.resteasy.plugins.server.servlet.Tomcat6CometDispatcherServlet" }; } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Servlet3AsyncHttpRequest.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Servlet3AsyncHttpRequest.java index c450581dc55..82e22503e0d 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Servlet3AsyncHttpRequest.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/Servlet3AsyncHttpRequest.java @@ -187,7 +187,7 @@ public boolean cancel(int retryAfter) cancelled = true; AsyncContext asyncContext = getAsyncContext(); return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(), - t -> asyncContext.complete()); + t -> asyncContext.complete()); } } @@ -202,7 +202,7 @@ public boolean cancel(Date retryAfter) cancelled = true; AsyncContext asyncContext = getAsyncContext(); return internalResume(Response.status(Response.Status.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, retryAfter).build(), - t -> asyncContext.complete()); + t -> asyncContext.complete()); } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletBootstrap.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletBootstrap.java index 262493c2a95..c02c8c2d53e 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletBootstrap.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletBootstrap.java @@ -63,4 +63,4 @@ public Set getInitParameterNames() return set; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletUtil.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletUtil.java index bb06b2cb277..b348e45c483 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletUtil.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/plugins/server/servlet/ServletUtil.java @@ -25,14 +25,14 @@ public class ServletUtil { public static ResteasyUriInfo extractUriInfo(HttpServletRequest request, String servletPrefix) { - String contextPath = request.getContextPath(); - if (servletPrefix != null && servletPrefix.length() > 0 && !servletPrefix.equals("/")) - { - if (!contextPath.endsWith("/") && !servletPrefix.startsWith("/")) + String contextPath = request.getContextPath(); + if (servletPrefix != null && servletPrefix.length() > 0 && !servletPrefix.equals("/")) + { + if (!contextPath.endsWith("/") && !servletPrefix.startsWith("/")) contextPath += "/"; - contextPath += servletPrefix; - } - return new ResteasyUriInfo(request.getRequestURL().toString(), request.getQueryString(), contextPath); + contextPath += servletPrefix; + } + return new ResteasyUriInfo(request.getRequestURL().toString(), request.getQueryString(), contextPath); } public static ResteasyHttpHeaders extractHttpHeaders(HttpServletRequest request) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkBuilderImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkBuilderImpl.java index 52b5dca53bf..aeb54919683 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkBuilderImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkBuilderImpl.java @@ -18,7 +18,7 @@ public class LinkBuilderImpl implements Link.Builder { /** - * A map for all the link parameters such as "rel", "type", etc. + * A map for all the link parameters such as "rel", "type", etc. */ protected final Map map = new HashMap(); protected UriBuilder uriBuilder; @@ -99,15 +99,15 @@ public Link build(Object... values) throws UriBuilderException URI built = null; if (uriBuilder == null) { - built = baseUri; + built = baseUri; } else { - built = this.uriBuilder.build(values); + built = this.uriBuilder.build(values); } if (!built.isAbsolute() && baseUri != null) { - built = baseUri.resolve(built); + built = baseUri.resolve(built); } return new LinkImpl(built, this.map); } @@ -136,4 +136,4 @@ public Link.Builder baseUri(String uri) this.baseUri = URI.create(uri); return this; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkImpl.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkImpl.java index a093834a2dc..0cf777a6d3b 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkImpl.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/LinkImpl.java @@ -24,7 +24,7 @@ public class LinkImpl extends Link protected final Map map; protected static final RuntimeDelegate.HeaderDelegate delegate = - RuntimeDelegate.getInstance().createHeaderDelegate(Link.class); + RuntimeDelegate.getInstance().createHeaderDelegate(Link.class); public static Link valueOf(String value) { @@ -35,8 +35,8 @@ public static Link valueOf(String value) { this.uri = uri; this.map = map.isEmpty() ? Collections. emptyMap() : Collections - .unmodifiableMap(new HashMap(map)); - } + .unmodifiableMap(new HashMap(map)); + } @Override public URI getUri() { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyHttpHeaders.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyHttpHeaders.java index aff6918d4f8..514b24a4d79 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyHttpHeaders.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyHttpHeaders.java @@ -147,15 +147,15 @@ public List getAcceptableMediaTypes() String accepts = getHeaderString(ACCEPT); List list = new ArrayList(); if (accepts == null){ - list.add(MediaType.WILDCARD_TYPE); + list.add(MediaType.WILDCARD_TYPE); }else{ - StringTokenizer tokenizer = new StringTokenizer(accepts, ","); - while (tokenizer.hasMoreElements()) - { + StringTokenizer tokenizer = new StringTokenizer(accepts, ","); + while (tokenizer.hasMoreElements()) + { String item = tokenizer.nextToken().trim(); list.add(MediaType.valueOf(item)); - } - MediaTypeHelper.sortByWeight(list); + } + MediaTypeHelper.sortByWeight(list); } return Collections.unmodifiableList(list); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyUriBuilder.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyUriBuilder.java index 861451f1968..b7421b21659 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyUriBuilder.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/ResteasyUriBuilder.java @@ -24,39 +24,39 @@ */ public class ResteasyUriBuilder extends UriBuilder { - - private static final class URITemplateParametersMap extends HashMap { - - private final Object[] parameterValues; - private int index; - - private URITemplateParametersMap(Object...parameterValues) { - this.parameterValues=parameterValues; - } - - @Override - public Object get(Object key) { - Object object = null; - if ( !super.containsKey(key) && this.index != this.parameterValues.length) { - object = this.parameterValues[this.index++]; - super.put((String) key, object); - }else{ - object = super.get(key); - } - return object; - } - - @Override - public boolean containsKey(Object key) { - boolean containsKey = super.containsKey(key); - if (!containsKey && this.index != this.parameterValues.length) { - super.put((String) key, this.parameterValues[this.index++]); - containsKey = true; - } - return containsKey; - } - - } + + private static final class URITemplateParametersMap extends HashMap { + + private final Object[] parameterValues; + private int index; + + private URITemplateParametersMap(Object...parameterValues) { + this.parameterValues=parameterValues; + } + + @Override + public Object get(Object key) { + Object object = null; + if ( !super.containsKey(key) && this.index != this.parameterValues.length) { + object = this.parameterValues[this.index++]; + super.put((String) key, object); + }else{ + object = super.get(key); + } + return object; + } + + @Override + public boolean containsKey(Object key) { + boolean containsKey = super.containsKey(key); + if (!containsKey && this.index != this.parameterValues.length) { + super.put((String) key, this.parameterValues[this.index++]); + containsKey = true; + } + return containsKey; + } + + } private String host; private String scheme; @@ -229,7 +229,7 @@ protected UriBuilder parseHierarchicalUri(String uriTemplate, Matcher match) { String group = match.group(5); if (!scheme && !"".equals(group) && !group.startsWith("/") && group.indexOf(':') > -1 && - group.indexOf('/') > -1 && group.indexOf(':') < group.indexOf('/')) + group.indexOf('/') > -1 && group.indexOf(':') < group.indexOf('/')) throw new IllegalArgumentException(Messages.MESSAGES.illegalUriTemplate(uriTemplate)); if (!"".equals(group)) replacePath(group); } @@ -596,7 +596,7 @@ else if (authority != null) } if (path != null) { - StringBuilder tmp = new StringBuilder(); + StringBuilder tmp = new StringBuilder(); replaceParameter(paramMap, fromEncodedMap, isTemplate, path, tmp, encodeSlash); String tmpPath = tmp.toString(); if (userInfo != null || host != null) @@ -620,10 +620,10 @@ else if (authority != null) protected StringBuilder replacePathParameter(String name, String value, boolean isEncoded, String string, StringBuilder builder, boolean encodeSlash) { - if (string.indexOf('{') == -1) - { - return builder.append(string); - } + if (string.indexOf('{') == -1) + { + return builder.append(string); + } Matcher matcher = createUriParamMatcher(string); int start = 0; while (matcher.find()) @@ -641,8 +641,8 @@ protected StringBuilder replacePathParameter(String name, String value, boolean { value = Encode.encodeNonCodes(value); } - builder.append(value); - start = matcher.end(); + builder.append(value); + start = matcher.end(); } builder.append(string, start, string.length()); return builder; @@ -656,29 +656,29 @@ public static Matcher createUriParamMatcher(String string) protected StringBuilder replaceParameter(Map paramMap, boolean fromEncodedMap, boolean isTemplate, String string, StringBuilder builder, boolean encodeSlash) { - if (string.indexOf('{') == -1) - { - return builder.append(string); - } + if (string.indexOf('{') == -1) + { + return builder.append(string); + } Matcher matcher = createUriParamMatcher(string); int start = 0; while (matcher.find()) { - builder.append(string, start, matcher.start()); + builder.append(string, start, matcher.start()); String param = matcher.group(1); - boolean containsValueForParam = paramMap.containsKey(param); - if (!containsValueForParam) - { - if (isTemplate) - { - builder.append(matcher.group()); - start = matcher.end(); - continue; - } + boolean containsValueForParam = paramMap.containsKey(param); + if (!containsValueForParam) + { + if (isTemplate) + { + builder.append(matcher.group()); + start = matcher.end(); + continue; + } throw new IllegalArgumentException(Messages.MESSAGES.pathParameterNotProvided(param)); - } - Object value = paramMap.get(param); - String stringValue = value != null ? value.toString() : null; + } + Object value = paramMap.get(param); + String stringValue = value != null ? value.toString() : null; if (stringValue != null) { if (!fromEncodedMap) @@ -691,8 +691,8 @@ protected StringBuilder replaceParameter(Map paramMap, if (encodeSlash) stringValue = Encode.encodePathSegmentSaveEncodings(stringValue); else stringValue = Encode.encodePathSaveEncodings(stringValue); } - builder.append(stringValue); - start = matcher.end(); + builder.append(stringValue); + start = matcher.end(); } else { @@ -705,41 +705,41 @@ protected StringBuilder replaceParameter(Map paramMap, protected StringBuilder replaceQueryStringParameter(Map paramMap, boolean fromEncodedMap, boolean isTemplate, String string, StringBuilder builder) { - if (string.indexOf('{') == -1) - { - return builder.append(string); - } + if (string.indexOf('{') == -1) + { + return builder.append(string); + } Matcher matcher = createUriParamMatcher(string); int start = 0; while (matcher.find()) { - builder.append(string, start, matcher.start()); + builder.append(string, start, matcher.start()); String param = matcher.group(1); - boolean containsValueForParam = paramMap.containsKey(param); - if (!containsValueForParam) - { - if (isTemplate) - { - builder.append(matcher.group()); - start = matcher.end(); - continue; - } - throw new IllegalArgumentException(Messages.MESSAGES.pathParameterNotProvided(param)); - } - Object value = paramMap.get(param); - String stringValue = value != null ? value.toString() : null; + boolean containsValueForParam = paramMap.containsKey(param); + if (!containsValueForParam) + { + if (isTemplate) + { + builder.append(matcher.group()); + start = matcher.end(); + continue; + } + throw new IllegalArgumentException(Messages.MESSAGES.pathParameterNotProvided(param)); + } + Object value = paramMap.get(param); + String stringValue = value != null ? value.toString() : null; if (stringValue != null) { if (!fromEncodedMap) { - stringValue = Encode.encodeQueryParamAsIs(stringValue); + stringValue = Encode.encodeQueryParamAsIs(stringValue); } else { - stringValue = Encode.encodeQueryParamSaveEncodings(stringValue); + stringValue = Encode.encodeQueryParamSaveEncodings(stringValue); } - builder.append(stringValue); - start = matcher.end(); + builder.append(stringValue); + start = matcher.end(); } else { @@ -846,12 +846,12 @@ public UriBuilder replaceMatrixParam(String name, Object... values) throws Illeg int from = 0; while (matcher.find()) { - newSegment.append(pathWithoutEnclosedCurlyBraces, from, matcher.start()); + newSegment.append(pathWithoutEnclosedCurlyBraces, from, matcher.start()); foundParam = true; String group = matcher.group(); pathParams.add(PathHelper.recoverEnclosedCurlyBraces(group)); - newSegment.append("_resteasy_uri_parameter"); - from = matcher.end(); + newSegment.append("_resteasy_uri_parameter"); + from = matcher.end(); } newSegment.append(pathWithoutEnclosedCurlyBraces, from, pathWithoutEnclosedCurlyBraces.length()); path = newSegment.toString(); @@ -906,9 +906,9 @@ public UriBuilder replaceMatrixParam(String name, Object... values) throws Illeg from = 0; while (matcher.find()) { - newSegment.append(this.path, from, matcher.start()); - newSegment.append(pathParams.get(i++)); - from = matcher.end(); + newSegment.append(this.path, from, matcher.start()); + newSegment.append(pathParams.get(i++)); + from = matcher.end(); } newSegment.append(this.path, from, this.path.length()); path = newSegment.toString(); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/UnmodifiableMultivaluedMap.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/UnmodifiableMultivaluedMap.java index 6383d2a440c..5912acb71d8 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/UnmodifiableMultivaluedMap.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/specimpl/UnmodifiableMultivaluedMap.java @@ -16,126 +16,126 @@ public class UnmodifiableMultivaluedMap implements MultivaluedMap { - private final MultivaluedMap delegate; - - public UnmodifiableMultivaluedMap(MultivaluedMap delegate) - { - this.delegate = delegate; - } - - @Override - public void putSingle(K k, V v) - { - throw new UnsupportedOperationException(); - } - - @Override - public void add(K k, V v) - { - throw new UnsupportedOperationException(); - } - - @Override - public V getFirst(K key) - { - return delegate.getFirst(key); - } - - @SuppressWarnings(value = "unchecked") - @Override - public void addAll(K k, V... vs) - { - throw new UnsupportedOperationException(); - } - - @Override - public void addAll(K k, List list) - { - throw new UnsupportedOperationException(); - } - - @Override - public void addFirst(K k, V v) - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean equalsIgnoreValueOrder(MultivaluedMap omap) - { - return delegate.equalsIgnoreValueOrder(omap); - } - - @Override - public void clear() - { - throw new UnsupportedOperationException(); - } - - @Override - public Set>> entrySet() - { - return Collections.unmodifiableSet(delegate.entrySet()); - } - - @Override - public List get(Object key) - { - return delegate.get(key); - } - - @Override - public Set keySet() - { - return Collections.unmodifiableSet(delegate.keySet()); - } - - @Override - public List put(K key, List value) - { - throw new UnsupportedOperationException(); - } - - @Override - public void putAll(Map> m) - { - throw new UnsupportedOperationException(); - } - - @Override - public List remove(Object key) - { - throw new UnsupportedOperationException(); - } - - @Override - public Collection> values() - { - return Collections.unmodifiableCollection(delegate.values()); - } - - @Override - public boolean containsKey(Object o) - { - return delegate.containsKey(o); - } - - @Override - public boolean containsValue(Object o) - { - return delegate.containsValue(o); - } - - @Override - public int size() - { - return delegate.size(); - } - - @Override - public boolean isEmpty() - { - return delegate.isEmpty(); - } + private final MultivaluedMap delegate; + + public UnmodifiableMultivaluedMap(MultivaluedMap delegate) + { + this.delegate = delegate; + } + + @Override + public void putSingle(K k, V v) + { + throw new UnsupportedOperationException(); + } + + @Override + public void add(K k, V v) + { + throw new UnsupportedOperationException(); + } + + @Override + public V getFirst(K key) + { + return delegate.getFirst(key); + } + + @SuppressWarnings(value = "unchecked") + @Override + public void addAll(K k, V... vs) + { + throw new UnsupportedOperationException(); + } + + @Override + public void addAll(K k, List list) + { + throw new UnsupportedOperationException(); + } + + @Override + public void addFirst(K k, V v) + { + throw new UnsupportedOperationException(); + } + + @Override + public boolean equalsIgnoreValueOrder(MultivaluedMap omap) + { + return delegate.equalsIgnoreValueOrder(omap); + } + + @Override + public void clear() + { + throw new UnsupportedOperationException(); + } + + @Override + public Set>> entrySet() + { + return Collections.unmodifiableSet(delegate.entrySet()); + } + + @Override + public List get(Object key) + { + return delegate.get(key); + } + + @Override + public Set keySet() + { + return Collections.unmodifiableSet(delegate.keySet()); + } + + @Override + public List put(K key, List value) + { + throw new UnsupportedOperationException(); + } + + @Override + public void putAll(Map> m) + { + throw new UnsupportedOperationException(); + } + + @Override + public List remove(Object key) + { + throw new UnsupportedOperationException(); + } + + @Override + public Collection> values() + { + return Collections.unmodifiableCollection(delegate.values()); + } + + @Override + public boolean containsKey(Object o) + { + return delegate.containsKey(o); + } + + @Override + public boolean containsValue(Object o) + { + return delegate.containsValue(o); + } + + @Override + public int size() + { + return delegate.size(); + } + + @Override + public boolean isEmpty() + { + return delegate.isEmpty(); + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/AsyncClientResponseProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/AsyncClientResponseProvider.java index 96d6a87613f..64113f58b50 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/AsyncClientResponseProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/AsyncClientResponseProvider.java @@ -10,4 +10,3 @@ public interface AsyncClientResponseProvider { T fromCompletionStage(CompletionStage completionStage); } - diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/BadRequestException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/BadRequestException.java index 910d7ca77d8..133edc57f22 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/BadRequestException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/BadRequestException.java @@ -39,4 +39,4 @@ public BadRequestException(Throwable throwable, Response response) } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/DefaultOptionsMethodException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/DefaultOptionsMethodException.java index a916e28b880..e9da341001e 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/DefaultOptionsMethodException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/DefaultOptionsMethodException.java @@ -13,4 +13,4 @@ public DefaultOptionsMethodException(String s, Response response) { super(s, response); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/HttpRequest.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/HttpRequest.java index 87ff3915ebd..0c270b6234d 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/HttpRequest.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/HttpRequest.java @@ -45,7 +45,7 @@ public interface HttpRequest /** * Updates the object returned by {@link #getUri()}. * @param baseUri base uri - * @param requestUri request uri + * @param requestUri request uri */ void setRequestUri(URI baseUri, URI requestUri) throws IllegalStateException; /** diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/InternalServerErrorException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/InternalServerErrorException.java index 1a649f9775c..a11a07a32de 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/InternalServerErrorException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/InternalServerErrorException.java @@ -39,4 +39,4 @@ public InternalServerErrorException(Throwable throwable, Response response) } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyAsynchronousResponse.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyAsynchronousResponse.java index 2d9b6cee939..cdce2f50680 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyAsynchronousResponse.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyAsynchronousResponse.java @@ -14,28 +14,28 @@ public interface ResteasyAsynchronousResponse extends AsyncResponse { /** - * Callback by the initial http request thread. It is used to help simulate suspend/resume asynchronous semantics - * in containers that do not support asychronous HTTP. This method is a no-op in environments that support async HTTP. - */ - void initialRequestThreadFinished(); + * Callback by the initial http request thread. It is used to help simulate suspend/resume asynchronous semantics + * in containers that do not support asychronous HTTP. This method is a no-op in environments that support async HTTP. + */ + void initialRequestThreadFinished(); - ContainerResponseFilter[] getResponseFilters(); + ContainerResponseFilter[] getResponseFilters(); - void setResponseFilters(ContainerResponseFilter[] responseFilters); + void setResponseFilters(ContainerResponseFilter[] responseFilters); - WriterInterceptor[] getWriterInterceptors(); + WriterInterceptor[] getWriterInterceptors(); - void setWriterInterceptors(WriterInterceptor[] writerInterceptors); + void setWriterInterceptors(WriterInterceptor[] writerInterceptors); - Annotation[] getAnnotations(); + Annotation[] getAnnotations(); - void setAnnotations(Annotation[] annotations); + void setAnnotations(Annotation[] annotations); - ResourceMethodInvoker getMethod(); + ResourceMethodInvoker getMethod(); - void setMethod(ResourceMethodInvoker method); + void setMethod(ResourceMethodInvoker method); - void complete(); - - void completionCallbacks(Throwable throwable); + void complete(); + + void completionCallbacks(Throwable throwable); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyDeployment.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyDeployment.java index 8d40a9d8611..86869bb0766 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyDeployment.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyDeployment.java @@ -600,19 +600,19 @@ protected boolean processApplication(Application config) final Map properties = config.getProperties(); if (properties != null && !properties.isEmpty()) { - Feature appliationPropertiesRegistrationfeature = new Feature() - { - @Override - public boolean configure(FeatureContext featureContext) - { - for (Map.Entry property : properties.entrySet()) - { - featureContext = featureContext.property(property.getKey(), property.getValue()); - } - return true; - } - }; - this.providers.add(0, appliationPropertiesRegistrationfeature); + Feature appliationPropertiesRegistrationfeature = new Feature() + { + @Override + public boolean configure(FeatureContext featureContext) + { + for (Map.Entry property : properties.entrySet()) + { + featureContext = featureContext.property(property.getKey(), property.getValue()); + } + return true; + } + }; + this.providers.add(0, appliationPropertiesRegistrationfeature); } return registered; } @@ -999,7 +999,7 @@ public void setWiderRequestMatching(boolean widerRequestMatching) public boolean isJaxrs_2_0_RequestMatching() { return jaxrs_2_0_RequestMatching; - } + } public void setJaxrs_2_0_RequestMatching(boolean jaxrs_2_0_RequestMatching) { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyProviderFactory.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyProviderFactory.java index 74cc332b4eb..b2ce57c0218 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyProviderFactory.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyProviderFactory.java @@ -187,9 +187,9 @@ public Class getType() return template; } - public T getObj() { - return obj; - } + public T getObj() { + return obj; + } } protected static class ExtSortedKey extends SortedKey @@ -494,13 +494,13 @@ public Map, AsyncStreamProvider> getAsyncStreamProviders() protected void addAsyncClientResponseProvider(Class providerClass) { - AsyncClientResponseProvider provider = createProviderInstance(providerClass); - addAsyncClientResponseProvider(provider, providerClass); + AsyncClientResponseProvider provider = createProviderInstance(providerClass); + addAsyncClientResponseProvider(provider, providerClass); } protected void addAsyncClientResponseProvider(AsyncClientResponseProvider provider) { - addAsyncClientResponseProvider(provider, provider.getClass()); + addAsyncClientResponseProvider(provider, provider.getClass()); } protected void addAsyncClientResponseProvider(AsyncClientResponseProvider provider, Class providerClass) @@ -515,8 +515,8 @@ protected void addAsyncClientResponseProvider(AsyncClientResponseProvider provid Class asyncClass = Types.getRawType(asyncType); if (asyncClientResponseProviders == null) { - asyncClientResponseProviders = new ConcurrentHashMap, AsyncClientResponseProvider>(); - asyncClientResponseProviders.putAll(parent.getAsyncClientResponseProviders()); + asyncClientResponseProviders = new ConcurrentHashMap, AsyncClientResponseProvider>(); + asyncClientResponseProviders.putAll(parent.getAsyncClientResponseProviders()); } asyncClientResponseProviders.put(asyncClass, provider); } @@ -1221,7 +1221,7 @@ public MessageBodyReader getMessageBodyReader(Class type, Type generic MediaTypeMap> availableReaders = getServerMessageBodyReaders(); MessageBodyReader reader = resolveMessageBodyReader(type, genericType, annotations, mediaType, availableReaders); if (reader!=null) - LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyReader: %s", reader.getClass().getName()); return reader; } @@ -1313,7 +1313,7 @@ protected void addExceptionMapper(ExceptionMapper provider, Type exceptionType, SortedKey candidateExceptionMapper = new SortedKey<>(null, provider, providerClass, priority, isBuiltin); SortedKey registeredExceptionMapper; if ((registeredExceptionMapper = sortedExceptionMappers.get(exceptionClass)) != null - && (candidateExceptionMapper.compareTo(registeredExceptionMapper) > 0)) { + && (candidateExceptionMapper.compareTo(registeredExceptionMapper) > 0)) { return; } sortedExceptionMappers.put(exceptionClass, candidateExceptionMapper); @@ -1382,13 +1382,13 @@ public List getClientErrorInterceptors() protected void addAsyncResponseProvider(Class providerClass) { - AsyncResponseProvider provider = createProviderInstance(providerClass); - addAsyncResponseProvider(provider, providerClass); + AsyncResponseProvider provider = createProviderInstance(providerClass); + addAsyncResponseProvider(provider, providerClass); } protected void addAsyncResponseProvider(AsyncResponseProvider provider) { - addAsyncResponseProvider(provider, provider.getClass()); + addAsyncResponseProvider(provider, provider.getClass()); } protected void addAsyncResponseProvider(AsyncResponseProvider provider, Class providerClass) @@ -1404,21 +1404,21 @@ protected void addAsyncResponseProvider(AsyncResponseProvider provider, Type asy Class asyncClass = Types.getRawType(asyncType); if (asyncResponseProviders == null) { - asyncResponseProviders = new ConcurrentHashMap, AsyncResponseProvider>(); - asyncResponseProviders.putAll(parent.getAsyncResponseProviders()); + asyncResponseProviders = new ConcurrentHashMap, AsyncResponseProvider>(); + asyncResponseProviders.putAll(parent.getAsyncResponseProviders()); } asyncResponseProviders.put(asyncClass, provider); } protected void addAsyncStreamProvider(Class providerClass) { - AsyncStreamProvider provider = createProviderInstance(providerClass); - addAsyncStreamProvider(provider, providerClass); + AsyncStreamProvider provider = createProviderInstance(providerClass); + addAsyncStreamProvider(provider, providerClass); } protected void addAsyncStreamProvider(AsyncStreamProvider provider) { - addAsyncStreamProvider(provider, provider.getClass()); + addAsyncStreamProvider(provider, provider.getClass()); } protected void addAsyncStreamProvider(AsyncStreamProvider provider, Class providerClass) @@ -1434,8 +1434,8 @@ protected void addAsyncStreamProvider(AsyncStreamProvider provider, Type asyncTy Class asyncClass = Types.getRawType(asyncType); if (asyncStreamProviders == null) { - asyncStreamProviders = new ConcurrentHashMap, AsyncStreamProvider>(); - asyncStreamProviders.putAll(parent.getAsyncStreamProviders()); + asyncStreamProviders = new ConcurrentHashMap, AsyncStreamProvider>(); + asyncStreamProviders.putAll(parent.getAsyncStreamProviders()); } asyncStreamProviders.put(asyncClass, provider); } @@ -1568,26 +1568,26 @@ public List getContextResolvers(final Class clazz, MediaType // { // rtn.add(list.get(i).obj); // } - - // Fix for RESTEASY-1609. - // This is related to the fix in RESTEASY-1471, prior to which user ContextResolvers appeared - // to be built-in. The original loop may have been in response to that bug, so the reversal - // may not be necessary. In any case, this code will do the reversal but put user ContextResolvers - // at the beginning of the list. - for (int i = list.size() - 1; i >= 0; i--) - { - if (!list.get(i).isBuiltin) - { - rtn.add(list.get(i).obj); - } - } - for (int i = list.size() - 1; i >= 0; i--) - { - if (list.get(i).isBuiltin) - { - rtn.add(list.get(i).obj); - } - } + + // Fix for RESTEASY-1609. + // This is related to the fix in RESTEASY-1471, prior to which user ContextResolvers appeared + // to be built-in. The original loop may have been in response to that bug, so the reversal + // may not be necessary. In any case, this code will do the reversal but put user ContextResolvers + // at the beginning of the list. + for (int i = list.size() - 1; i >= 0; i--) + { + if (!list.get(i).isBuiltin) + { + rtn.add(list.get(i).obj); + } + } + for (int i = list.size() - 1; i >= 0; i--) + { + if (list.get(i).isBuiltin) + { + rtn.add(list.get(i).obj); + } + } } else { @@ -1649,7 +1649,7 @@ public String toString(Object object, Class clazz, Type genericType, Annotation[ return paramConverter.toString(object); } StringConverter converter = getStringConverter(object - .getClass()); + .getClass()); if (converter != null) return converter.toString(object); else @@ -2686,7 +2686,7 @@ public MessageBodyWriter getMessageBodyWriter(Class type, Type generic MediaTypeMap> availableWriters = getServerMessageBodyWriters(); MessageBodyWriter writer = resolveMessageBodyWriter(type, genericType, annotations, mediaType, availableWriters); if (writer!=null) - LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); + LogMessages.LOGGER.debugf("MessageBodyWriter: %s", writer.getClass().getName()); return writer; } @@ -2758,7 +2758,7 @@ public T getContext(Class type) * Create an instance of a class using provider allocation rules of the specification as well as the InjectorFactory * only does constructor injection. * - * @param clazz class + * @param clazz class * @param type * @return provider instance of type T */ diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyUriInfo.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyUriInfo.java index e721397d4d4..fa04377d859 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyUriInfo.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/ResteasyUriInfo.java @@ -57,7 +57,8 @@ public ResteasyUriInfo(String absoluteUri, String queryString, String contextPat } protected void initialize(String absoluteUri, String queryString, String contextPath) - {ResteasyUriBuilder absoluteBuilder = (ResteasyUriBuilder) UriBuilder.fromUri(absoluteUri); + { + ResteasyUriBuilder absoluteBuilder = (ResteasyUriBuilder) UriBuilder.fromUri(absoluteUri); absolutePath = absoluteBuilder.build(); requestURI = absoluteBuilder.replaceQuery(queryString).build(); encodedPath = PathHelper.getEncodedPathInfo(absolutePath.getRawPath(), contextPath); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/WriterException.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/WriterException.java index cc767825e23..ff8800d4e91 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/WriterException.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/WriterException.java @@ -65,4 +65,4 @@ public WriterException(Throwable throwable, int errorCode) { super(throwable, errorCode); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderContext.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderContext.java index 51fd43effee..5652c1af2aa 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderContext.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderContext.java @@ -56,4 +56,4 @@ public interface MessageBodyReaderContext void removeAttribute(String name); Object proceed() throws IOException, WebApplicationException; -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderInterceptor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderInterceptor.java index 7fbf69996da..a88e12482d2 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderInterceptor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/interception/MessageBodyReaderInterceptor.java @@ -26,4 +26,4 @@ public interface MessageBodyReaderInterceptor */ Object read(MessageBodyReaderContext context) throws IOException, WebApplicationException; -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceBuilder.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceBuilder.java index 90d9b5024f7..0381385e57c 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceBuilder.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceBuilder.java @@ -642,7 +642,7 @@ public ResourceMethodBuilder produces(String... produces) LogMessages.LOGGER.mediaTypeLacksCharset(mt, method.getMethod().getName()); } } -} + } } return this; } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClass.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClass.java index 04537a54ad2..6921b2dc57c 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClass.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClass.java @@ -5,17 +5,17 @@ */ public interface ResourceClass { - String getPath(); + String getPath(); - Class getClazz(); + Class getClazz(); - ResourceConstructor getConstructor(); + ResourceConstructor getConstructor(); - FieldParameter[] getFields(); + FieldParameter[] getFields(); - SetterParameter[] getSetters(); + SetterParameter[] getSetters(); - ResourceMethod[] getResourceMethods(); + ResourceMethod[] getResourceMethods(); - ResourceLocator[] getResourceLocators(); + ResourceLocator[] getResourceLocators(); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClassProcessor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClassProcessor.java index 64817d2f560..65c20faf525 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClassProcessor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceClassProcessor.java @@ -8,14 +8,14 @@ public interface ResourceClassProcessor { - /** - * Allows the implementation of this method to modify the resource metadata represented by - * the supplied {@link ResourceClass} instance. Implementation will typically create - * wrappers which modify only certain aspects of the metadata. - * - * @param clazz The original metadata - * @return the (potentially modified) metadata (never null) - */ - ResourceClass process(ResourceClass clazz); + /** + * Allows the implementation of this method to modify the resource metadata represented by + * the supplied {@link ResourceClass} instance. Implementation will typically create + * wrappers which modify only certain aspects of the metadata. + * + * @param clazz The original metadata + * @return the (potentially modified) metadata (never null) + */ + ResourceClass process(ResourceClass clazz); -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceConstructor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceConstructor.java index 1d6d84f5ea9..dc07d1049ac 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceConstructor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceConstructor.java @@ -7,9 +7,9 @@ */ public interface ResourceConstructor { - ResourceClass getResourceClass(); + ResourceClass getResourceClass(); - Constructor getConstructor(); + Constructor getConstructor(); - ConstructorParameter[] getParams(); + ConstructorParameter[] getParams(); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceLocator.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceLocator.java index 59ec3b365c2..3dcccee34cd 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceLocator.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceLocator.java @@ -8,20 +8,20 @@ */ public interface ResourceLocator { - ResourceClass getResourceClass(); + ResourceClass getResourceClass(); - Class getReturnType(); + Class getReturnType(); - Type getGenericReturnType(); + Type getGenericReturnType(); - Method getMethod(); + Method getMethod(); - Method getAnnotatedMethod(); + Method getAnnotatedMethod(); - MethodParameter[] getParams(); + MethodParameter[] getParams(); - String getFullpath(); + String getFullpath(); - String getPath(); + String getPath(); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceMethod.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceMethod.java index 2f31482e135..a67a23f80ed 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceMethod.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/metadata/ResourceMethod.java @@ -9,13 +9,13 @@ */ public interface ResourceMethod extends ResourceLocator { - Set getHttpMethods(); + Set getHttpMethods(); - MediaType[] getProduces(); + MediaType[] getProduces(); - MediaType[] getConsumes(); + MediaType[] getConsumes(); - boolean isAsynchronous(); + boolean isAsynchronous(); - void markAsynchronous(); + void markAsynchronous(); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/AbstractURITemplateAnnotationResolver.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/AbstractURITemplateAnnotationResolver.java index 2bab42ffb7a..ca0d3bc61f7 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/AbstractURITemplateAnnotationResolver.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/AbstractURITemplateAnnotationResolver.java @@ -17,7 +17,7 @@ import java.util.Map; public abstract class AbstractURITemplateAnnotationResolver implements - URIResolver + URIResolver { @SuppressWarnings("unchecked") @@ -30,11 +30,11 @@ public boolean handles(Class type) public String resolveURI(Object object) { Class clazz = AnnotationResolver - .getClassWithAnnotation(object.getClass(), getAnnotationType()); + .getClassWithAnnotation(object.getClass(), getAnnotationType()); ResteasyUriBuilder uriBuilderImpl = getUriBuilder(clazz); Map descriptors = getPropertyDescriptors(clazz); List values = getValues(object, descriptors, uriBuilderImpl - .getPathParamNamesInDeclarationOrder()); + .getPathParamNamesInDeclarationOrder()); return uriBuilderImpl.build(values.toArray()).toString(); } @@ -73,7 +73,7 @@ private List getValues(Object object, } private Map getPropertyDescriptors( - Class clazz) + Class clazz) { try { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedBy.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedBy.java index 9adad8eb3d2..4de519be469 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedBy.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedBy.java @@ -16,8 +16,8 @@ * MappedBy(Resource=FooResource.class, method="getFoo") * public class Foo * { - * private int id; - * // getters and setters + * private int id; + * // getters and setters * } * * {@literal @}Path("/foo")public class FooResource { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedByAnnotationResolver.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedByAnnotationResolver.java index 68b18973176..29132314b3d 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedByAnnotationResolver.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/MappedByAnnotationResolver.java @@ -5,7 +5,7 @@ import java.lang.annotation.Annotation; public class MappedByAnnotationResolver extends - AbstractURITemplateAnnotationResolver + AbstractURITemplateAnnotationResolver { protected Class getAnnotationType() { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplate.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplate.java index 79a66c5c61c..02cc07c8266 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplate.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplate.java @@ -28,7 +28,7 @@ */ @Target( - {ElementType.TYPE}) + {ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface URITemplate { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplateAnnotationResolver.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplateAnnotationResolver.java index ca5d755ceac..7a1fd475899 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplateAnnotationResolver.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/touri/URITemplateAnnotationResolver.java @@ -5,7 +5,7 @@ import java.lang.annotation.Annotation; public class URITemplateAnnotationResolver extends - AbstractURITemplateAnnotationResolver + AbstractURITemplateAnnotationResolver { protected Class getAnnotationType() diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidator.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidator.java index c232de24e0d..36a87076b13 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidator.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidator.java @@ -66,7 +66,7 @@ void validateReturnValue( /** * Indicates if validation is turned on for a class. - * + * * @param clazz Class to be examined * @return true if and only if validation is turned on for clazz */ @@ -74,16 +74,16 @@ void validateReturnValue( /** * Indicates if validation is turned on for a method. - * + * * @param method method to be examined * @return true if and only if validation is turned on for method - */ + */ boolean isMethodValidatable(Method method); /** * Throws a ResteasyViolationException if any validation violations have been detected. - * + * * @param request http request */ void checkViolations(HttpRequest request); -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidatorCDI.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidatorCDI.java index 186bfd88146..3e773d3a276 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidatorCDI.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/spi/validation/GeneralValidatorCDI.java @@ -17,22 +17,22 @@ public interface GeneralValidatorCDI extends GeneralValidator { /** * Indicates if validation is turned on for a class. - * + * * This method should be called from the resteasy-jaxrs module. It should * test if injectorFactor is an instance of CdiInjectorFactory, which indicates * that CDI is active. If so, it should return false. Otherwise, it should * return the same value returned by GeneralValidator.isValidatable(). - * + * * @param clazz Class to be examined * @param injectorFactory the InjectorFactory used for clazz * @return true if and only if validation is turned on for clazz */ - boolean isValidatable(Class clazz, InjectorFactory injectorFactory); + boolean isValidatable(Class clazz, InjectorFactory injectorFactory); /** * Indicates if validation is turned on for a class. * This method should be called only from the resteasy-cdi module. - * + * * @param clazz Class to be examined * @return true if and only if validation is turned on for clazz */ @@ -48,9 +48,9 @@ public interface GeneralValidatorCDI extends GeneralValidator /** * Throws a ResteasyViolationException if either a ConstraintViolationException or a * ResteasyConstraintViolationException is embedded in the cause hierarchy of e. - * + * * @param request http request * @param e exception */ void checkForConstraintViolations(HttpRequest request, Exception e); -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/test/TestPortProvider.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/test/TestPortProvider.java index 05e929f758e..3c5c580795e 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/test/TestPortProvider.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/test/TestPortProvider.java @@ -74,7 +74,7 @@ public static URI createURI(String path) * * @param path the request path * @return a full URL - * @throws MalformedURLException if no protocol is specified or an unknown protocol is found + * @throws MalformedURLException if no protocol is specified or an unknown protocol is found */ public static URL createURL(String path) throws MalformedURLException { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ArrayCharSequence.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ArrayCharSequence.java index a485f117933..e9ef57ac901 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ArrayCharSequence.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ArrayCharSequence.java @@ -64,4 +64,4 @@ public String toString() { return new String(this.buf, this.offset, this.count); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Base64.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Base64.java index 8414b881f61..0328d284cde 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Base64.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Base64.java @@ -238,16 +238,16 @@ public class Base64 */ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ private final static byte[] _STANDARD_ALPHABET = { - (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', - (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', - (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', - (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', - (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', - (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', - (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', - (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', - (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', - (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', + (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; @@ -256,37 +256,37 @@ public class Base64 * or a negative number indicating some other meaning. */ private final static byte[] _STANDARD_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - 62, // Plus sign at decimal 43 - -9, -9, -9, // Decimal 44 - 46 - 63, // Slash at decimal 47 - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' - -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + 62, // Plus sign at decimal 43 + -9, -9, -9, // Decimal 44 - 46 + 63, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 }; @@ -298,57 +298,57 @@ public class Base64 * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." */ private final static byte[] _URL_SAFE_ALPHABET = { - (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', - (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', - (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', - (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', - (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', - (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', - (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', - (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', - (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', - (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', + (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' }; /** * Used in decoding URL- and Filename-safe dialects of Base64. */ private final static byte[] _URL_SAFE_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 62, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' - 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' - -9, -9, -9, -9, // Decimal 91 - 94 - 63, // Underscore at decimal 95 - -9, // Decimal 96 - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 62, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 + 63, // Underscore at decimal 95 + -9, // Decimal 96 + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 }; @@ -360,59 +360,59 @@ public class Base64 * http://www.faqs.org/qa/rfcc-1940.html. */ private final static byte[] _ORDERED_ALPHABET = { - (byte) '-', - (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', - (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', - (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', - (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', - (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', - (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', - (byte) '_', - (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', - (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', - (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', - (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' + (byte) '-', + (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', + (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', + (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', + (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', + (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', + (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', + (byte) '_', + (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', + (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', + (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', + (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' }; /** * Used in decoding the "ordered" dialect of Base64. */ private final static byte[] _ORDERED_DECODABET = { - -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 - -5, -5, // Whitespace: Tab and Linefeed - -9, -9, // Decimal 11 - 12 - -5, // Whitespace: Carriage Return - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 - -9, -9, -9, -9, -9, // Decimal 27 - 31 - -5, // Whitespace: Space - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 - -9, // Plus sign at decimal 43 - -9, // Decimal 44 - 0, // Minus sign at decimal 45 - -9, // Decimal 46 - -9, // Slash at decimal 47 - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine - -9, -9, -9, // Decimal 58 - 60 - -1, // Equals sign at decimal 61 - -9, -9, -9, // Decimal 62 - 64 - 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' - 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' - -9, -9, -9, -9, // Decimal 91 - 94 - 37, // Underscore at decimal 95 - -9, // Decimal 96 - 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' - 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' - -9, -9, -9, -9, -9 // Decimal 123 - 127 - , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 - -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 + -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 + -5, -5, // Whitespace: Tab and Linefeed + -9, -9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 + -9, -9, -9, -9, -9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 0, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine + -9, -9, -9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9, -9, -9, // Decimal 62 - 64 + 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' + 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' + -9, -9, -9, -9, // Decimal 91 - 94 + 37, // Underscore at decimal 95 + -9, // Decimal 96 + 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' + -9, -9, -9, -9, -9 // Decimal 123 - 127 + , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243 + -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255 }; @@ -524,8 +524,8 @@ private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, * @since 1.3 */ private static byte[] encode3to4( - byte[] source, int srcOffset, int numSigBytes, - byte[] destination, int destOffset, int options) + byte[] source, int srcOffset, int numSigBytes, + byte[] destination, int destOffset, int options) { byte[] ALPHABET = getAlphabet(options); @@ -542,8 +542,8 @@ private static byte[] encode3to4( // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) - | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) - | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); + | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) + | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { @@ -647,7 +647,7 @@ public static void encode(java.nio.ByteBuffer raw, java.nio.CharBuffer encoded) * @since 1.4 */ public static String encodeObject(java.io.Serializable serializableObject) - throws java.io.IOException + throws java.io.IOException { return encodeObject(serializableObject, NO_OPTIONS); } // end encodeObject @@ -682,7 +682,7 @@ public static String encodeObject(java.io.Serializable serializableObject) * @since 2.0 */ public static String encodeObject(java.io.Serializable serializableObject, int options) - throws java.io.IOException + throws java.io.IOException { if (serializableObject == null) @@ -958,7 +958,7 @@ public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int opt if (off + len > source.length) { - throw new IllegalArgumentException(Messages.MESSAGES.cannotHaveOffset(off, len, source.length)); + throw new IllegalArgumentException(Messages.MESSAGES.cannotHaveOffset(off, len, source.length)); } // end if: off < 0 @@ -1102,8 +1102,8 @@ public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int opt * @since 1.3 */ private static int decode4to3( - byte[] source, int srcOffset, - byte[] destination, int destOffset, int options) + byte[] source, int srcOffset, + byte[] destination, int destOffset, int options) { // Lots of error checking and exception throwing @@ -1194,7 +1194,7 @@ else if (source[srcOffset + 3] == EQUALS_SIGN) * @since 2.3.1 */ public static byte[] decode(byte[] source) - throws java.io.IOException + throws java.io.IOException { byte[] decoded = null; // try { @@ -1224,7 +1224,7 @@ public static byte[] decode(byte[] source) * @since 1.3 */ public static byte[] decode(byte[] source, int off, int len, int options) - throws java.io.IOException + throws java.io.IOException { // Lots of error checking and exception throwing @@ -1415,7 +1415,7 @@ public static byte[] decode(String s, int options) throws java.io.IOException * @since 1.5 */ public static Object decodeToObject(String encodedObject) - throws java.io.IOException, java.lang.ClassNotFoundException + throws java.io.IOException, java.lang.ClassNotFoundException { return decodeToObject(encodedObject, NO_OPTIONS, null); } @@ -1438,8 +1438,8 @@ public static Object decodeToObject(String encodedObject) * @since 2.3.4 */ public static Object decodeToObject( - String encodedObject, int options, final ClassLoader loader) - throws java.io.IOException, java.lang.ClassNotFoundException + String encodedObject, int options, final ClassLoader loader) + throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary @@ -1522,7 +1522,7 @@ public Class resolveClass(java.io.ObjectStreamClass streamClass) * @since 2.1 */ public static void encodeToFile(byte[] dataToEncode, String filename) - throws java.io.IOException + throws java.io.IOException { if (dataToEncode == null) @@ -1565,7 +1565,7 @@ public static void encodeToFile(byte[] dataToEncode, String filename) * @since 2.1 */ public static void decodeToFile(String dataToDecode, String filename) - throws java.io.IOException + throws java.io.IOException { Base64.OutputStream bos = null; @@ -1604,7 +1604,7 @@ public static void decodeToFile(String dataToDecode, String filename) * @since 2.1 */ public static byte[] decodeFromFile(String filename) - throws java.io.IOException + throws java.io.IOException { byte[] decodedData = null; @@ -1670,7 +1670,7 @@ public static byte[] decodeFromFile(String filename) * @since 2.1 */ public static String encodeFromFile(String filename) - throws java.io.IOException + throws java.io.IOException { String encodedData = null; @@ -1722,7 +1722,7 @@ public static String encodeFromFile(String filename) * @since 2.2 */ public static void encodeFileToFile(String infile, String outfile) - throws java.io.IOException + throws java.io.IOException { String encoded = Base64.encodeFromFile(infile); @@ -1756,7 +1756,7 @@ public static void encodeFileToFile(String infile, String outfile) * @since 2.2 */ public static void decodeFileToFile(String infile, String outfile) - throws java.io.IOException + throws java.io.IOException { byte[] decoded = Base64.decodeFromFile(infile); @@ -1991,7 +1991,7 @@ else if (i == 0) */ @Override public int read(byte[] dest, int off, int len) - throws java.io.IOException + throws java.io.IOException { int i; int b; @@ -2104,7 +2104,7 @@ public OutputStream(java.io.OutputStream out, int options) */ @Override public void write(int theByte) - throws java.io.IOException + throws java.io.IOException { // Encoding suspended? if (suspendEncoding) @@ -2167,7 +2167,7 @@ else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) */ @Override public void write(byte[] theBytes, int off, int len) - throws java.io.IOException + throws java.io.IOException { // Encoding suspended? if (suspendEncoding) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CaseInsensitiveMap.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CaseInsensitiveMap.java index 52c31142568..63dbf015e74 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CaseInsensitiveMap.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CaseInsensitiveMap.java @@ -13,9 +13,9 @@ public class CaseInsensitiveMap extends MultivaluedTreeMap { public static final Comparator CASE_INSENSITIVE_ORDER - = new CaseInsensitiveComparator(); + = new CaseInsensitiveComparator(); private static class CaseInsensitiveComparator - implements Comparator, java.io.Serializable { + implements Comparator, java.io.Serializable { public int compare(String s1, String s2) { if (s1 == s2) return 0; @@ -186,7 +186,7 @@ public int hashCode() return keys.hashCode(); } - } + } private static class EntrySetWrapper implements Set> { @@ -567,6 +567,6 @@ public boolean equalsIgnoreValueOrder(MultivaluedMap omap) { } return true; } - */ + */ } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CookieParser.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CookieParser.java index 733c5f3d514..a18369044f0 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CookieParser.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/CookieParser.java @@ -61,5 +61,5 @@ else if (name.equalsIgnoreCase("$Domain")) { throw new IllegalArgumentException(Messages.MESSAGES.failedToParseCookie(cookieHeader), ex); } - } + } } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/DateUtil.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/DateUtil.java index 5c19802ebae..ac044c00238 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/DateUtil.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/DateUtil.java @@ -62,7 +62,7 @@ public DateParseException(Throwable throwable) public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy"; private static final Collection DEFAULT_PATTERNS = Arrays.asList( - new String[]{PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123}); + new String[]{PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123}); private static final Date DEFAULT_TWO_DIGIT_YEAR_START; @@ -98,7 +98,7 @@ public static Date parseDate(String dateValue) throws DateParseException * @throws DateParseException if none of the dataFormats could parse the dateValue */ public static Date parseDate(String dateValue, Collection dateFormats) - throws DateParseException + throws DateParseException { return parseDate(dateValue, dateFormats, null); } @@ -116,9 +116,9 @@ public static Date parseDate(String dateValue, Collection dateFormats) * @throws DateParseException if none of the dataFormats could parse the dateValue */ public static Date parseDate( - String dateValue, - Collection dateFormats, - Date startDate + String dateValue, + Collection dateFormats, + Date startDate ) throws DateParseException { @@ -137,9 +137,9 @@ public static Date parseDate( // trim single quotes around date if present // see issue #5279 if (dateValue.length() > 1 - && dateValue.startsWith("'") - && dateValue.endsWith("'") - ) + && dateValue.startsWith("'") + && dateValue.endsWith("'") + ) { dateValue = dateValue.substring(1, dateValue.length() - 1); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Encode.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Encode.java index 6e25ae47ca8..a56168883ce 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Encode.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Encode.java @@ -220,7 +220,7 @@ public static String decodePath(String path) CharsetDecoder decoder = Charset.forName(UTF_8).newDecoder(); while (matcher.find()) { - builder.append(path, start, matcher.start()); + builder.append(path, start, matcher.start()); decoder.reset(); String decoded = decodeBytes(matcher.group(1), decoder); builder.append(decoded); @@ -288,7 +288,7 @@ public static boolean savePathParams(String segmentString, StringBuilder newSegm int start = 0; while (matcher.find()) { - newSegment.append(segment, start, matcher.start()); + newSegment.append(segment, start, matcher.start()); foundParam = true; String group = matcher.group(); // Regular expressions can have '{' and '}' characters. Recover earlier replacement @@ -418,7 +418,7 @@ protected static String encodeFromArray(String segment, String[] encodingMap, bo StringBuilder result = new StringBuilder(); for (int i = 0; i < segment.length(); i++) { - char currentChar = segment.charAt(i); + char currentChar = segment.charAt(i); if (!encodePercent && currentChar == '%') { result.append(currentChar); @@ -471,12 +471,12 @@ public static String pathParamReplacement(String segment, List params) int start = 0; while (matcher.find()) { - newSegment.append(segment, start, matcher.start()); + newSegment.append(segment, start, matcher.start()); String replacement = params.get(i++); - newSegment.append(replacement); - start = matcher.end(); + newSegment.append(replacement); + start = matcher.end(); } - newSegment.append(segment, start, segment.length()); + newSegment.append(segment, start, segment.length()); segment = newSegment.toString(); return segment; } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/FindAnnotation.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/FindAnnotation.java index 1ab94ca79e9..34c6b7c7e95 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/FindAnnotation.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/FindAnnotation.java @@ -26,21 +26,21 @@ public final class FindAnnotation * */ private static final Class[] JAXRS_ANNOTATIONS = - (Class[]) new Class[]{ - QueryParam.class, - HeaderParam.class, - CookieParam.class, - PathParam.class, - MatrixParam.class, - FormParam.class, - Context.class, - org.jboss.resteasy.annotations.jaxrs.QueryParam.class, - org.jboss.resteasy.annotations.jaxrs.HeaderParam.class, - org.jboss.resteasy.annotations.jaxrs.CookieParam.class, - org.jboss.resteasy.annotations.jaxrs.PathParam.class, - org.jboss.resteasy.annotations.jaxrs.MatrixParam.class, - org.jboss.resteasy.annotations.jaxrs.FormParam.class, - }; + (Class[]) new Class[] { + QueryParam.class, + HeaderParam.class, + CookieParam.class, + PathParam.class, + MatrixParam.class, + FormParam.class, + Context.class, + org.jboss.resteasy.annotations.jaxrs.QueryParam.class, + org.jboss.resteasy.annotations.jaxrs.HeaderParam.class, + org.jboss.resteasy.annotations.jaxrs.CookieParam.class, + org.jboss.resteasy.annotations.jaxrs.PathParam.class, + org.jboss.resteasy.annotations.jaxrs.MatrixParam.class, + org.jboss.resteasy.annotations.jaxrs.FormParam.class, + }; @SuppressWarnings("rawtypes") private static final Class[] findJaxRSAnnotations_TYPE = new Class[]{}; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GenericType.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GenericType.java index e205cb8fab6..84285a79da0 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GenericType.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GenericType.java @@ -71,4 +71,4 @@ public final Type getGenericType() return genericType; } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java index fa8c01c139f..76ea9d6239b 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GetRestful.java @@ -80,19 +80,19 @@ public static Class getSubResourceClass(Class clazz) */ public static Class[] getSubResourceClasses(Class clazz) { - List> classes = new ArrayList>(); - // check class & superclasses for JAX-RS annotations - for (Class actualClass = clazz; isTopObject(actualClass); actualClass = actualClass.getSuperclass()) { - if (hasJAXRSAnnotations(actualClass)) - return new Class[]{actualClass}; - } + List> classes = new ArrayList>(); + // check class & superclasses for JAX-RS annotations + for (Class actualClass = clazz; isTopObject(actualClass); actualClass = actualClass.getSuperclass()) { + if (hasJAXRSAnnotations(actualClass)) + return new Class[]{actualClass}; + } - // ok, no @Path or @HttpMethods so look in interfaces. - for (Class intf : clazz.getInterfaces()) { - if (hasJAXRSAnnotations(intf)) + // ok, no @Path or @HttpMethods so look in interfaces. + for (Class intf : clazz.getInterfaces()) { + if (hasJAXRSAnnotations(intf)) classes.add(intf); - } - return classes.toArray(new Class[classes.size()]); + } + return classes.toArray(new Class[classes.size()]); } private static boolean isTopObject(Class actualClass) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GroupParameterParser.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GroupParameterParser.java index 0e3b784d842..71c4cc8856f 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GroupParameterParser.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/GroupParameterParser.java @@ -267,11 +267,11 @@ public List> parse(final char[] chars, char separator, char * @return a map of name/value pairs */ public List> parse( - final char[] chars, - int offset, - int length, - char separator, - char groupSeparator) + final char[] chars, + int offset, + int length, + char separator, + char groupSeparator) { if (chars == null) @@ -289,14 +289,13 @@ public List> parse( String paramValue = null; while (hasChar()) { - paramName = parseToken(new char[]{ - '=', separator, groupSeparator}); + paramName = parseToken(new char[]{'=', separator, groupSeparator}); paramValue = null; if (hasChar() && (chars[pos] == '=')) { pos++; // skip '=' paramValue = parseQuotedToken(new char[]{ - separator, groupSeparator}); + separator, groupSeparator}); } if ((paramName != null) && (paramName.length() > 0)) { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Hex.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Hex.java index c1b72f63714..4c9e9c2b18b 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Hex.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Hex.java @@ -9,8 +9,8 @@ public class Hex * Used building output as Hex */ private static final char[] DIGITS = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** @@ -92,4 +92,4 @@ public static String encodeHex(byte[] data) return new String(out); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpHeaderNames.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpHeaderNames.java index 59eacfee5bd..80766a96d1a 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpHeaderNames.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpHeaderNames.java @@ -56,4 +56,4 @@ public interface HttpHeaderNames String WARNING = "Warning"; String WWW_AUTHENTICATE = "WWW-Authenticate"; -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpServletRequestDelegate.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpServletRequestDelegate.java index eb08572a4a8..7269ec8755b 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpServletRequestDelegate.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/HttpServletRequestDelegate.java @@ -184,7 +184,7 @@ public String getCharacterEncoding() } public void setCharacterEncoding(String s) - throws UnsupportedEncodingException + throws UnsupportedEncodingException { delegate.setCharacterEncoding(s); } @@ -200,7 +200,7 @@ public String getContentType() } public ServletInputStream getInputStream() - throws IOException + throws IOException { return delegate.getInputStream(); } @@ -246,7 +246,7 @@ public int getServerPort() } public BufferedReader getReader() - throws IOException + throws IOException { return delegate.getReader(); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/InputStreamToByteArray.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/InputStreamToByteArray.java index 1de4c0ab791..7a7fb6b1725 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/InputStreamToByteArray.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/InputStreamToByteArray.java @@ -27,7 +27,7 @@ public byte[] toByteArray() @Override public int read() - throws IOException + throws IOException { int b = delegate.read(); if (b > -1) @@ -37,7 +37,7 @@ public int read() @Override public int read(byte[] bytes) - throws IOException + throws IOException { int num = delegate.read(bytes); if (num > 0) @@ -49,7 +49,7 @@ public int read(byte[] bytes) @Override public int read(byte[] bytes, int off, int len) - throws IOException + throws IOException { int num = delegate.read(bytes, off, len); if (num > 0) @@ -61,21 +61,21 @@ public int read(byte[] bytes, int off, int len) @Override public long skip(long l) - throws IOException + throws IOException { return delegate.skip(l); } @Override public int available() - throws IOException + throws IOException { return delegate.available(); } @Override public void close() - throws IOException + throws IOException { delegate.close(); } @@ -88,7 +88,7 @@ public void mark(int i) @Override public void reset() - throws IOException + throws IOException { throw new RuntimeException(Messages.MESSAGES.streamWrappedBySignature()); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MediaTypeHelper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MediaTypeHelper.java index db6791a9e91..74ed7254359 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MediaTypeHelper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MediaTypeHelper.java @@ -38,7 +38,7 @@ public static MediaType getConsumes(Class declaring, AccessibleObject method) public static MediaType getProduces(Class declaring, Method method) { - return getProduces(declaring, method, null); + return getProduces(declaring, method, null); } @SuppressWarnings(value = "unchecked") diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MethodHashing.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MethodHashing.java index 9aa0f7f308d..1f0b27ed8c9 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MethodHashing.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/MethodHashing.java @@ -13,7 +13,7 @@ public class MethodHashing { public static long methodHash(Method method) - throws Exception + throws Exception { Class[] parameterTypes = method.getParameterTypes(); StringBuilder methodDesc = new StringBuilder(method.getName()).append("("); @@ -26,7 +26,7 @@ public static long methodHash(Method method) } public static long createHash(String methodDesc) - throws Exception + throws Exception { long hash = 0; ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(512); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ParameterParser.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ParameterParser.java index 82d940ec1dd..e6ea3efb6bd 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ParameterParser.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ParameterParser.java @@ -262,10 +262,10 @@ public Map parse(final char[] chars, char separator) * @return a map of name/value pairs */ public Map parse( - final char[] chars, - int offset, - int length, - char separator) + final char[] chars, + int offset, + int length, + char separator) { if (chars == null) @@ -281,14 +281,13 @@ public Map parse( String paramValue = null; while (hasChar()) { - paramName = parseToken(new char[]{ - '=', separator}); + paramName = parseToken(new char[]{'=', separator}); paramValue = null; if (hasChar() && (chars[pos] == '=')) { pos++; // skip '=' paramValue = parseQuotedToken(new char[]{ - separator}); + separator}); } if (hasChar() && (chars[pos] == separator)) { @@ -319,12 +318,12 @@ public Map parse( * @return updated parameters string */ public String setAttribute( - final char[] chars, - int offset, - int length, - char separator, - String name, - String value) + final char[] chars, + int offset, + int length, + char separator, + String name, + String value) { this.chars = chars; @@ -340,8 +339,7 @@ public String setAttribute( while (hasChar()) { - paramName = parseToken(new char[]{ - '=', separator}); + paramName = parseToken(new char[]{'=', separator}); paramValue = null; int index = -1; if (paramName.equals(name)) @@ -352,7 +350,7 @@ public String setAttribute( { pos++; // skip '=' paramValue = parseQuotedToken(new char[]{ - separator}); + separator}); } if (paramName.equals(name)) { diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PathHelper.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PathHelper.java index 1ecda72ec5c..0fc2a7db0f8 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PathHelper.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PathHelper.java @@ -116,4 +116,4 @@ public static String recoverEnclosedCurlyBraces(String str) return str.replace(openCurlyReplacement, '{').replace(closeCurlyReplacement, '}'); } -} \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PickConstructor.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PickConstructor.java index b9914116877..2e234240c25 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PickConstructor.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PickConstructor.java @@ -43,7 +43,7 @@ public static Constructor pickSingletonConstructor(Class clazz) if (con.getParameterTypes().length >= numParameters) { if (con.getParameterTypes().length > numParameters) { - potentialConflict = false; + potentialConflict = false; } boolean noContextAnnotation = false; if (con.getParameterAnnotations() != null) @@ -58,7 +58,7 @@ public static Constructor pickSingletonConstructor(Class clazz) } if (noContextAnnotation) continue; if (con.getParameterTypes().length == numParameters && numParameters != 0) { - potentialConflict = true; + potentialConflict = true; } numParameters = con.getParameterTypes().length; pick = con; @@ -97,7 +97,7 @@ public static Constructor pickPerRequestConstructor(Class clazz) if (con.getParameterTypes().length >= numParameters) { if (con.getParameterTypes().length > numParameters) { - potentialConflict = false; + potentialConflict = false; } boolean noContextAnnotation = false; @@ -113,7 +113,7 @@ public static Constructor pickPerRequestConstructor(Class clazz) } if (noContextAnnotation) continue; if (con.getParameterTypes().length == numParameters && numParameters != 0) { - potentialConflict = true; + potentialConflict = true; } numParameters = con.getParameterTypes().length; pick = con; diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PrefixedFormFieldsHttpRequest.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PrefixedFormFieldsHttpRequest.java index cfe9857db5f..73216fb2dff 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PrefixedFormFieldsHttpRequest.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/PrefixedFormFieldsHttpRequest.java @@ -6,16 +6,16 @@ public class PrefixedFormFieldsHttpRequest extends DelegatingHttpRequest { - private final String prefix; + private final String prefix; - public PrefixedFormFieldsHttpRequest(String prefix, HttpRequest request) { - super(request); - this.prefix = prefix; - } + public PrefixedFormFieldsHttpRequest(String prefix, HttpRequest request) { + super(request); + this.prefix = prefix; + } - @Override - public MultivaluedMap getDecodedFormParameters() { - return new PrefixedMultivaluedMap(prefix, super.getDecodedFormParameters()); - } + @Override + public MultivaluedMap getDecodedFormParameters() { + return new PrefixedMultivaluedMap(prefix, super.getDecodedFormParameters()); + } - } \ No newline at end of file +} diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ReadFromStream.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ReadFromStream.java index 634cda3a6bd..60fa2e8564c 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ReadFromStream.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/ReadFromStream.java @@ -19,7 +19,7 @@ public class ReadFromStream * @throws IOException if I/O error occurred */ public static byte[] readFromStream(int bufferSize, InputStream entityStream) - throws IOException + throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/StringToPrimitive.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/StringToPrimitive.java index bffd5f3ed2d..a82075ba045 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/StringToPrimitive.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/StringToPrimitive.java @@ -16,15 +16,15 @@ public static Object stringToPrimitiveBoxType(Class primitiveType, String value) } else if (primitiveType.equals(char.class)) { - if(value==null) - { - return Character.valueOf(Character.MIN_VALUE); - } - else if (value.length() != 1) { - throw new IllegalArgumentException(); - } - return Character.valueOf(value.charAt(0)); - } + if(value==null) + { + return Character.valueOf(Character.MIN_VALUE); + } + else if (value.length() != 1) { + throw new IllegalArgumentException(); + } + return Character.valueOf(value.charAt(0)); + } if (value == null) value = "0"; if (primitiveType.equals(int.class)) return Integer.valueOf(value); if (primitiveType.equals(long.class)) return Long.valueOf(value); diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/TypeConverter.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/TypeConverter.java index 73056257366..24522dcb966 100755 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/TypeConverter.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/TypeConverter.java @@ -207,12 +207,12 @@ public static boolean isConvertable(final Class targetType) public static Boolean getBooleanValue(final String source) { if ("Y".equalsIgnoreCase(source) || "T".equalsIgnoreCase(source) - || "Yes".equalsIgnoreCase(source) || "1".equalsIgnoreCase(source)) + || "Yes".equalsIgnoreCase(source) || "1".equalsIgnoreCase(source)) { return Boolean.TRUE; } else if ("N".equals(source) || "F".equals(source) || "No".equals(source) - || "0".equalsIgnoreCase(source)) + || "0".equalsIgnoreCase(source)) { return Boolean.FALSE; } @@ -228,7 +228,7 @@ else if ("N".equals(source) || "F".equals(source) || "No".equals(source) */ @SuppressWarnings("unchecked") public static T getTypeViaValueOfMethod(final String source, final Class targetType) - throws NoSuchMethodException + throws NoSuchMethodException { Class actualTarget = targetType; /* @@ -276,7 +276,7 @@ else if (!actualTarget.equals(targetType) && actualTarget.isInstance(value)) * @return object instance of type T * @throws IllegalArgumentException if not suitable constructor was found * @throws InstantiationException if the underlying constructor represents an abstract class - * @throws IllegalAccessException if the underlying constructor is not accessible + * @throws IllegalAccessException if the underlying constructor is not accessible * @throws InvocationTargetException if the underlying constructor throws exception */ private static T getTypeViaStringConstructor(String source, Class targetType) diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Types.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Types.java index 0c9bcb6ff98..37756b21e04 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Types.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/Types.java @@ -303,12 +303,12 @@ else if (type instanceof TypeVariable) } else if (type instanceof WildcardType) { - WildcardType wildcardType = (WildcardType) type; - Type[] upperBounds = wildcardType.getUpperBounds(); - if (upperBounds != null && upperBounds.length > 0) - { - return getRawType(upperBounds[0]); - } + WildcardType wildcardType = (WildcardType) type; + Type[] upperBounds = wildcardType.getUpperBounds(); + if (upperBounds != null && upperBounds.length > 0) + { + return getRawType(upperBounds[0]); + } } throw new RuntimeException(Messages.MESSAGES.unableToDetermineBaseClass()); } diff --git a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/URLUtils.java b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/URLUtils.java index ea4e1ed7c9d..b70ad664b04 100644 --- a/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/URLUtils.java +++ b/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/URLUtils.java @@ -404,4 +404,4 @@ public static String encodePart(final String part, final String charset, final B } return encoded.toString(); } -} \ No newline at end of file +} diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/AddImpl.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/AddImpl.java index 7d04f905a77..f9880605e52 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/AddImpl.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/AddImpl.java @@ -6,8 +6,8 @@ */ public class AddImpl implements Add { - @Override - public Integer operate(Integer operand1, Integer operand2) { - return operand1 + operand2; - } + @Override + public Integer operate(Integer operand1, Integer operand2) { + return operand1 + operand2; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/CachedResource.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/CachedResource.java index 5ea7873c429..1a8c73f174e 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/CachedResource.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/CachedResource.java @@ -16,19 +16,19 @@ @Path("cached") public class CachedResource { - @GET - @GZIP - @Path("{uuid}") - public Response get(@Context HttpServletRequest servletRequest, @Context Request request, @PathParam("uuid") String uuid) throws Exception { - EntityTag tag = new EntityTag(Integer.toString(Math.abs(uuid.hashCode()))); - Response.ResponseBuilder builder = request.evaluatePreconditions(tag); + @GET + @GZIP + @Path("{uuid}") + public Response get(@Context HttpServletRequest servletRequest, @Context Request request, @PathParam("uuid") String uuid) throws Exception { + EntityTag tag = new EntityTag(Integer.toString(Math.abs(uuid.hashCode()))); + Response.ResponseBuilder builder = request.evaluatePreconditions(tag); - if (builder != null) { - return builder.build(); - } else { - builder = Response.ok(uuid, MediaType.TEXT_PLAIN); - builder.tag(tag); - return builder.build(); - } - } + if (builder != null) { + return builder.build(); + } else { + builder = Response.ok(uuid, MediaType.TEXT_PLAIN); + builder.tag(tag); + return builder.build(); + } + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/MinusImpl.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/MinusImpl.java index 2554258caaf..44f9fcdc4ac 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/MinusImpl.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/MinusImpl.java @@ -6,8 +6,8 @@ */ public class MinusImpl implements Minus { - @Override - public Integer operate(Integer operand1, Integer operand2) { - return operand1 - operand2; - } + @Override + public Integer operate(Integer operand1, Integer operand2) { + return operand1 - operand2; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/Operation.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/Operation.java index 758e4b7bbae..1c0e479b43e 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/Operation.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/Operation.java @@ -11,8 +11,8 @@ * @author Weinan Li */ public interface Operation { - @GET - @Path("/{operand1}/{operand2}") - @Produces(MediaType.TEXT_PLAIN) - public Integer operate(@PathParam("operand1") Integer operand1, @PathParam("operand2") Integer operand2); + @GET + @Path("/{operand1}/{operand2}") + @Produces(MediaType.TEXT_PLAIN) + public Integer operate(@PathParam("operand1") Integer operand1, @PathParam("operand2") Integer operand2); } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/SmokeTestResource.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/SmokeTestResource.java index d2444aeb274..6b322e99266 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/SmokeTestResource.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/SmokeTestResource.java @@ -11,121 +11,121 @@ */ @Path("/smoke") public class SmokeTestResource { - @Path("{id}") - @GET - @Produces("text/plain") - public String testPathParam(@PathParam("id") String id) { - return id; - } - - @POST - @Produces("text/plain") - public String testFormParam(@FormParam("key") String[] values) { - String val = ""; - for (String _val : values) { - val += _val + "::"; - } - return val; - } - - @Path("/post2") - @POST - @Produces("text/plain") - public String testFormParam2(@FormParam("key") String val) { - return val; - } - - @GET - @Produces("text/plain") - public String testQueryParam(@QueryParam("key") String[] values) { - String val = ""; - for (String _val : values) { - val += _val + "::"; - } - return val; - } - - @Path("/cookie") - @GET - @Produces("text/plain") - public String testCookieParam(@CookieParam("username") String key) { - return key; - } - - @GET - @Path("/matrix") - @Produces("text/plain") - public String testMatrixParam(@MatrixParam("key") String[] key) { - String val = ""; - for (String _val : key) { - val += _val + "::"; - } - return val; - } - - @GET - @Path("/header") - @Produces("text/plain") - public String testHeaderParam(@HeaderParam("Referer") String referer) { - return referer; - } - - @POST - @Path("/RESTEASY-731/false") - @Produces("text/plain") - public String testRESTEasy731False(@FormParam("false") boolean bool) { - return ("RESTEASY-731-" + String.valueOf(bool)); - } - - @POST - @Path("/RESTEASY-731/zero") - @Produces("text/plain") - public String testRESTEasy731Zero(@FormParam("zero") int zero) { - return ("RESTEASY-731-" + String.valueOf(zero)); - } - - @POST - @Path("/RESTEASY-805/form1") - @Produces("text/plain") - public String testRESTEasy805(@Form MyForm myForm) { - StringBuilder ret = new StringBuilder(); - for (String key : myForm.getMyMap().keySet()) { - ret.append(myForm.getMyMap().get(key).getBar()); - } - return ret.toString(); - } - - @POST - @Path("/RESTEASY-805/form2") - @Produces("text/plain") - public String testRESTEasy805Case2(@Form MyForm2 myForm2) { - return myForm2.getHeader() + myForm2.getStuff() + myForm2.getNumber(); - } - - @POST - @Path("/RESTEASY-805/form3") - @Produces("text/plain") - public String testRESTEasy805Case3(@Form MyForm3 myForm3) { - StringBuilder ret = new StringBuilder(); - for (Foo foo : myForm3.getFoos()) { - ret.append(foo.getBar()); - } - return ret.toString(); - } - - @POST - @Path("/postPrefixForm") - @Produces("text/plain") - public String postPrefixForm(@Form Person person) { - StringBuilder ret = new StringBuilder(); - for (TelephoneNumber number : person.getTelephoneNumbers()) { - ret.append(number.getNumber()).append(number.getCountryCode()); - } - - for (String key : person.getAddresses().keySet()) { - Address address = person.getAddresses().get(key); - ret.append(address.getHouseNumber()).append(address.getStreet()); - } - return ret.toString(); - } + @Path("{id}") + @GET + @Produces("text/plain") + public String testPathParam(@PathParam("id") String id) { + return id; + } + + @POST + @Produces("text/plain") + public String testFormParam(@FormParam("key") String[] values) { + String val = ""; + for (String _val : values) { + val += _val + "::"; + } + return val; + } + + @Path("/post2") + @POST + @Produces("text/plain") + public String testFormParam2(@FormParam("key") String val) { + return val; + } + + @GET + @Produces("text/plain") + public String testQueryParam(@QueryParam("key") String[] values) { + String val = ""; + for (String _val : values) { + val += _val + "::"; + } + return val; + } + + @Path("/cookie") + @GET + @Produces("text/plain") + public String testCookieParam(@CookieParam("username") String key) { + return key; + } + + @GET + @Path("/matrix") + @Produces("text/plain") + public String testMatrixParam(@MatrixParam("key") String[] key) { + String val = ""; + for (String _val : key) { + val += _val + "::"; + } + return val; + } + + @GET + @Path("/header") + @Produces("text/plain") + public String testHeaderParam(@HeaderParam("Referer") String referer) { + return referer; + } + + @POST + @Path("/RESTEASY-731/false") + @Produces("text/plain") + public String testRESTEasy731False(@FormParam("false") boolean bool) { + return ("RESTEASY-731-" + String.valueOf(bool)); + } + + @POST + @Path("/RESTEASY-731/zero") + @Produces("text/plain") + public String testRESTEasy731Zero(@FormParam("zero") int zero) { + return ("RESTEASY-731-" + String.valueOf(zero)); + } + + @POST + @Path("/RESTEASY-805/form1") + @Produces("text/plain") + public String testRESTEasy805(@Form MyForm myForm) { + StringBuilder ret = new StringBuilder(); + for (String key : myForm.getMyMap().keySet()) { + ret.append(myForm.getMyMap().get(key).getBar()); + } + return ret.toString(); + } + + @POST + @Path("/RESTEASY-805/form2") + @Produces("text/plain") + public String testRESTEasy805Case2(@Form MyForm2 myForm2) { + return myForm2.getHeader() + myForm2.getStuff() + myForm2.getNumber(); + } + + @POST + @Path("/RESTEASY-805/form3") + @Produces("text/plain") + public String testRESTEasy805Case3(@Form MyForm3 myForm3) { + StringBuilder ret = new StringBuilder(); + for (Foo foo : myForm3.getFoos()) { + ret.append(foo.getBar()); + } + return ret.toString(); + } + + @POST + @Path("/postPrefixForm") + @Produces("text/plain") + public String postPrefixForm(@Form Person person) { + StringBuilder ret = new StringBuilder(); + for (TelephoneNumber number : person.getTelephoneNumbers()) { + ret.append(number.getNumber()).append(number.getCountryCode()); + } + + for (String key : person.getAddresses().keySet()) { + Address address = person.getAddresses().get(key); + ret.append(address.getHouseNumber()).append(address.getStreet()); + } + return ret.toString(); + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/TestApplication.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/TestApplication.java index e2d27a8d831..36f4bf5810a 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/TestApplication.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/TestApplication.java @@ -9,24 +9,24 @@ * @author Weinan Li */ public class TestApplication extends javax.ws.rs.core.Application { - HashSet singletons = new HashSet(); + HashSet singletons = new HashSet(); - public TestApplication() { - singletons.add(new SmokeTestResource()); - singletons.add(new CachedResource()); - singletons.add(new AddImpl()); - singletons.add(new MinusImpl()); - singletons.add(new BookImpl()); - } + public TestApplication() { + singletons.add(new SmokeTestResource()); + singletons.add(new CachedResource()); + singletons.add(new AddImpl()); + singletons.add(new MinusImpl()); + singletons.add(new BookImpl()); + } - @Override - public Set> getClasses() { - HashSet> set = new HashSet>(); - return set; - } + @Override + public Set> getClasses() { + HashSet> set = new HashSet>(); + return set; + } - @Override - public Set getSingletons() { - return singletons; - } + @Override + public Set getSingletons() { + return singletons; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Address.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Address.java index 848c443ae29..0c8a58d6fe8 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Address.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Address.java @@ -8,22 +8,22 @@ * @author Weinan Li */ public class Address { - @FormParam("street") private String street; - @FormParam("houseNumber") private String houseNumber; + @FormParam("street") private String street; + @FormParam("houseNumber") private String houseNumber; - public String getStreet() { - return street; - } + public String getStreet() { + return street; + } - public void setStreet(String street) { - this.street = street; - } + public void setStreet(String street) { + this.street = street; + } - public String getHouseNumber() { - return houseNumber; - } + public String getHouseNumber() { + return houseNumber; + } - public void setHouseNumber(String houseNumber) { - this.houseNumber = houseNumber; - } + public void setHouseNumber(String houseNumber) { + this.houseNumber = houseNumber; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Foo.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Foo.java index 790c725250f..f3380379189 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Foo.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Foo.java @@ -8,14 +8,14 @@ * @author Weinan Li */ public class Foo { - @FormParam("bar") - private String bar; + @FormParam("bar") + private String bar; - public String getBar() { - return bar; - } + public String getBar() { + return bar; + } - public void setBar(String bar) { - this.bar = bar; - } + public void setBar(String bar) { + this.bar = bar; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm.java index 198fb09ff0f..cbfa89c2808 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm.java @@ -11,14 +11,14 @@ * @author Weinan Li */ public class MyForm { - @Form(prefix = "myMap") - private Map myMap = new HashMap(); + @Form(prefix = "myMap") + private Map myMap = new HashMap(); - public Map getMyMap() { - return myMap; - } + public Map getMyMap() { + return myMap; + } - public void setMyMap(Map myMap) { - this.myMap = myMap; - } + public void setMyMap(Map myMap) { + this.myMap = myMap; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm2.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm2.java index d655d203325..1d9884b30dd 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm2.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm2.java @@ -9,36 +9,36 @@ * @author Weinan Li */ public class MyForm2 { - @FormParam("stuff") - private String stuff; + @FormParam("stuff") + private String stuff; - @FormParam("number") - private int number; + @FormParam("number") + private int number; - @HeaderParam("myHeader") - private String header; + @HeaderParam("myHeader") + private String header; - public String getStuff() { - return stuff; - } + public String getStuff() { + return stuff; + } - public void setStuff(String stuff) { - this.stuff = stuff; - } + public void setStuff(String stuff) { + this.stuff = stuff; + } - public String getHeader() { - return header; - } + public String getHeader() { + return header; + } - public void setHeader(String header) { - this.header = header; - } + public void setHeader(String header) { + this.header = header; + } - public int getNumber() { - return number; - } + public int getNumber() { + return number; + } - public void setNumber(int number) { - this.number = number; - } + public void setNumber(int number) { + this.number = number; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm3.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm3.java index f33b15fcc05..db3fb992961 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm3.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/MyForm3.java @@ -10,14 +10,14 @@ * @author Weinan Li */ public class MyForm3 { - @Form(prefix="foos") - List foos; + @Form(prefix="foos") + List foos; - public List getFoos() { - return foos; - } + public List getFoos() { + return foos; + } - public void setFoos(List foos) { - this.foos = foos; - } + public void setFoos(List foos) { + this.foos = foos; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Person.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Person.java index 2750b3b7106..ccba0853672 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Person.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/Person.java @@ -11,23 +11,23 @@ * @author Weinan Li */ public class Person { - @Form(prefix="telephoneNumbers") List telephoneNumbers; - @Form(prefix="address") - Map addresses; + @Form(prefix="telephoneNumbers") List telephoneNumbers; + @Form(prefix="address") + Map addresses; - public List getTelephoneNumbers() { - return telephoneNumbers; - } + public List getTelephoneNumbers() { + return telephoneNumbers; + } - public void setTelephoneNumbers(List telephoneNumbers) { - this.telephoneNumbers = telephoneNumbers; - } + public void setTelephoneNumbers(List telephoneNumbers) { + this.telephoneNumbers = telephoneNumbers; + } - public Map getAddresses() { - return addresses; - } + public Map getAddresses() { + return addresses; + } - public void setAddresses(Map addresses) { - this.addresses = addresses; - } + public void setAddresses(Map addresses) { + this.addresses = addresses; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/TelephoneNumber.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/TelephoneNumber.java index a836e8acc39..481ac10119d 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/TelephoneNumber.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/form/TelephoneNumber.java @@ -8,22 +8,22 @@ * @author Weinan Li */ public class TelephoneNumber { - @FormParam("countryCode") private String countryCode; - @FormParam("number") private String number; + @FormParam("countryCode") private String countryCode; + @FormParam("number") private String number; - public String getCountryCode() { - return countryCode; - } + public String getCountryCode() { + return countryCode; + } - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; - } + public void setCountryCode(String countryCode) { + this.countryCode = countryCode; + } - public String getNumber() { - return number; - } + public String getNumber() { + return number; + } - public void setNumber(String number) { - this.number = number; - } + public void setNumber(String number) { + this.number = number; + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Book.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Book.java index 39668092f58..e0205406630 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Book.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Book.java @@ -9,11 +9,11 @@ * @author Weinan Li */ public interface Book { - @GET - @Path("/title") - @Produces("text/plain") - String getTitle(); + @GET + @Path("/title") + @Produces("text/plain") + String getTitle(); - @Path("/ch/{number}") - Chapter getChapter(@PathParam("number") int number); + @Path("/ch/{number}") + Chapter getChapter(@PathParam("number") int number); } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/BookImpl.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/BookImpl.java index 3b59a2bb8b2..0deb4addc51 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/BookImpl.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/BookImpl.java @@ -7,12 +7,12 @@ */ @Path("/gulliverstravels") public class BookImpl implements Book { - public String getTitle() { - return "Gulliver's Travels"; - } + public String getTitle() { + return "Gulliver's Travels"; + } - @Override - public Chapter getChapter(int number) { - return new ChapterImpl(number); - } + @Override + public Chapter getChapter(int number) { + return new ChapterImpl(number); + } } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Chapter.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Chapter.java index 7c798e43261..1e847cc50c7 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Chapter.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/Chapter.java @@ -9,13 +9,13 @@ */ @Path("") public interface Chapter { - @GET - @Path("title") - @Produces("text/plain") - String getTitle(); + @GET + @Path("title") + @Produces("text/plain") + String getTitle(); - @GET - @Path("body") - @Produces("text/plain") - String getBody(); + @GET + @Path("body") + @Produces("text/plain") + String getBody(); } diff --git a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/ChapterImpl.java b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/ChapterImpl.java index ad8bb71253f..fc1451e9d92 100644 --- a/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/ChapterImpl.java +++ b/resteasy-jsapi-testing/src/main/java/org/jboss/resteasy/jsapi/testing/sub/ChapterImpl.java @@ -6,17 +6,17 @@ * @author Weinan Li */ public class ChapterImpl implements Chapter { - private final int number; + private final int number; - public ChapterImpl(int number) { - this.number = number; - } + public ChapterImpl(int number) { + this.number = number; + } - public String getTitle() { - return "Chapter " + number; - } + public String getTitle() { + return "Chapter " + number; + } - public String getBody() { - return "This is the content of chapter " + number + "."; - } + public String getBody() { + return "This is the content of chapter " + number + "."; + } } diff --git a/resteasy-jsapi-testing/src/test/java/SmokingTest.java b/resteasy-jsapi-testing/src/test/java/SmokingTest.java index b848add56f3..7cd20f0b80e 100644 --- a/resteasy-jsapi-testing/src/test/java/SmokingTest.java +++ b/resteasy-jsapi-testing/src/test/java/SmokingTest.java @@ -18,108 +18,108 @@ * @created_at 08 24 2012 */ public class SmokingTest { - Selenium selenium; - - @Before - public void setUp() throws Exception { - selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://127.0.0.1:8080/resteasy-jsapi-testing/"); - selenium.start(); - } - - @Test - public void smokeTest() throws Exception { - selenium.open("/resteasy-jsapi-testing/"); - selenium.click("css=input[type=\"button\"]"); - selenium.click("//input[@value='Test Form Param']"); - selenium.click("//input[@value='Test Form Param2']"); - selenium.click("//input[@value='Test Form']"); - selenium.click("//input[@value='Test Form2']"); - selenium.click("//input[@value='Test Form3']"); - selenium.click("//input[@value='Test Prefix Form']"); - - selenium.click("//input[@value='Test Cookie Param']"); - selenium.click("//input[@value='Test Matrix Param']"); - selenium.click("//input[@value='Test Header Param']"); - selenium.click("//input[@value='RESTEASY-731-false']"); - selenium.click("//input[@value='RESTEASY-731-zero']"); - selenium.click("//input[@value='Test Subresource Locator']"); - - assertTrue(selenium.isTextPresent("Chapter 2This is the content of chapter 2.")); - assertTrue(selenium.isTextPresent("0")); - assertTrue(selenium.isTextPresent("exact:a::b::c::")); - assertTrue(selenium.isTextPresent("exact:xyz")); - assertTrue(selenium.isTextPresent(".-_~=&.-_~=&.-_~=&")); - assertTrue(selenium.isTextPresent("2B=_2A-&114")); - assertTrue(selenium.isTextPresent("CBA")); - assertTrue(selenium.isTextPresent("11111111")); - - - assertTrue(selenium.isTextPresent("Weinan")); - assertTrue(selenium.isTextPresent("exact:g::h::i::")); - assertTrue(selenium.isTextPresent("/resteasy-jsapi-testing/")); - assertTrue(selenium.isTextPresent("RESTEASY-731-false")); - assertTrue(selenium.isTextPresent("RESTEASY-731-0")); - - - // Put this at bottom because it will cause weird problem in Selenium. - selenium.click("//input[@value='Test Query Param']"); - assertTrue(selenium.isTextPresent("exact:d::e::f::")); - - - // Cache test - selenium.open("/resteasy-jsapi-testing/cacheTest.jsp"); - selenium.type("id=uuid", "1"); - selenium.click("css=input[type=\"button\"]"); - assertTrue(selenium.isTextPresent("200")); - selenium.click("css=input[type=\"button\"]"); - assertTrue(selenium.isTextPresent("304")); - selenium.type("id=uuid", "2"); - selenium.click("css=input[type=\"button\"]"); - assertTrue(selenium.isTextPresent("200")); - selenium.click("css=input[type=\"button\"]"); - assertTrue(selenium.isTextPresent("304")); - - // RESTEASY-789 - selenium.open("/resteasy-jsapi-testing/resteasy789.jsp"); - selenium.click("//input[@value='Test Add']"); - selenium.click("//input[@value='Test Minus']"); - assertTrue(selenium.isTextPresent("2")); - assertTrue(selenium.isTextPresent("0")); - - } - - @Test - public void testJSAPICache() throws Exception { - { - Client client = ClientBuilder.newBuilder().build(); - WebTarget target = client.target("http://127.0.0.1:8080/resteasy-jsapi-testing/rest-js"); - Response response = target.request().get(); - assertEquals(HttpStatus.SC_OK, response.getStatus()); - response.close(); - } - - String etag; - { - Client client = ClientBuilder.newBuilder().build(); - WebTarget target = client.target("http://127.0.0.1:8080/resteasy-jsapi-testing/rest-js"); - Response response = target.request().get(); - etag = response.getHeaderString("Etag"); - response.close(); - - } - - { - Client client = ClientBuilder.newBuilder().build(); - WebTarget target = client.target("http://127.0.0.1:8080/resteasy-jsapi-testing/rest-js"); - Response response = target.request().header("If-None-Match", etag).get(); - assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatus()); - response.close(); - } - } - - @After - public void tearDown() throws Exception { - selenium.stop(); - } + Selenium selenium; + + @Before + public void setUp() throws Exception { + selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://127.0.0.1:8080/resteasy-jsapi-testing/"); + selenium.start(); + } + + @Test + public void smokeTest() throws Exception { + selenium.open("/resteasy-jsapi-testing/"); + selenium.click("css=input[type=\"button\"]"); + selenium.click("//input[@value='Test Form Param']"); + selenium.click("//input[@value='Test Form Param2']"); + selenium.click("//input[@value='Test Form']"); + selenium.click("//input[@value='Test Form2']"); + selenium.click("//input[@value='Test Form3']"); + selenium.click("//input[@value='Test Prefix Form']"); + + selenium.click("//input[@value='Test Cookie Param']"); + selenium.click("//input[@value='Test Matrix Param']"); + selenium.click("//input[@value='Test Header Param']"); + selenium.click("//input[@value='RESTEASY-731-false']"); + selenium.click("//input[@value='RESTEASY-731-zero']"); + selenium.click("//input[@value='Test Subresource Locator']"); + + assertTrue(selenium.isTextPresent("Chapter 2This is the content of chapter 2.")); + assertTrue(selenium.isTextPresent("0")); + assertTrue(selenium.isTextPresent("exact:a::b::c::")); + assertTrue(selenium.isTextPresent("exact:xyz")); + assertTrue(selenium.isTextPresent(".-_~=&.-_~=&.-_~=&")); + assertTrue(selenium.isTextPresent("2B=_2A-&114")); + assertTrue(selenium.isTextPresent("CBA")); + assertTrue(selenium.isTextPresent("11111111")); + + + assertTrue(selenium.isTextPresent("Weinan")); + assertTrue(selenium.isTextPresent("exact:g::h::i::")); + assertTrue(selenium.isTextPresent("/resteasy-jsapi-testing/")); + assertTrue(selenium.isTextPresent("RESTEASY-731-false")); + assertTrue(selenium.isTextPresent("RESTEASY-731-0")); + + + // Put this at bottom because it will cause weird problem in Selenium. + selenium.click("//input[@value='Test Query Param']"); + assertTrue(selenium.isTextPresent("exact:d::e::f::")); + + + // Cache test + selenium.open("/resteasy-jsapi-testing/cacheTest.jsp"); + selenium.type("id=uuid", "1"); + selenium.click("css=input[type=\"button\"]"); + assertTrue(selenium.isTextPresent("200")); + selenium.click("css=input[type=\"button\"]"); + assertTrue(selenium.isTextPresent("304")); + selenium.type("id=uuid", "2"); + selenium.click("css=input[type=\"button\"]"); + assertTrue(selenium.isTextPresent("200")); + selenium.click("css=input[type=\"button\"]"); + assertTrue(selenium.isTextPresent("304")); + + // RESTEASY-789 + selenium.open("/resteasy-jsapi-testing/resteasy789.jsp"); + selenium.click("//input[@value='Test Add']"); + selenium.click("//input[@value='Test Minus']"); + assertTrue(selenium.isTextPresent("2")); + assertTrue(selenium.isTextPresent("0")); + + } + + @Test + public void testJSAPICache() throws Exception { + { + Client client = ClientBuilder.newBuilder().build(); + WebTarget target = client.target("http://127.0.0.1:8080/resteasy-jsapi-testing/rest-js"); + Response response = target.request().get(); + assertEquals(HttpStatus.SC_OK, response.getStatus()); + response.close(); + } + + String etag; + { + Client client = ClientBuilder.newBuilder().build(); + WebTarget target = client.target("http://127.0.0.1:8080/resteasy-jsapi-testing/rest-js"); + Response response = target.request().get(); + etag = response.getHeaderString("Etag"); + response.close(); + + } + + { + Client client = ClientBuilder.newBuilder().build(); + WebTarget target = client.target("http://127.0.0.1:8080/resteasy-jsapi-testing/rest-js"); + Response response = target.request().header("If-None-Match", etag).get(); + assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatus()); + response.close(); + } + } + + @After + public void tearDown() throws Exception { + selenium.stop(); + } } diff --git a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIServlet.java b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIServlet.java index a7d61c086cd..3fa0820b152 100755 --- a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIServlet.java +++ b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIServlet.java @@ -59,7 +59,7 @@ public void init(ServletConfig config) throws ServletException @Override protected void service(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException + throws ServletException, IOException { String pathInfo = req.getPathInfo(); String uri = req.getRequestURL().toString(); @@ -69,11 +69,12 @@ protected void service(HttpServletRequest req, HttpServletResponse resp) LogMessages.LOGGER.debug(Messages.MESSAGES.serving(pathInfo)); LogMessages.LOGGER.debug(Messages.MESSAGES.query(req.getQueryString())); } - if (this.services == null) try { - scanResources(); - } catch (Exception e) { - resp.sendError(503, Messages.MESSAGES.thereAreNoResteasyDeployments()); // FIXME should return internal error - } + if (this.services == null) + try { + scanResources(); + } catch (Exception e) { + resp.sendError(503, Messages.MESSAGES.thereAreNoResteasyDeployments()); // FIXME should return internal error + } if (this.services == null) { @@ -99,7 +100,7 @@ public void scanResources() throws Exception { { ResourceMethodRegistry registry = (ResourceMethodRegistry) entry.getValue().getRegistry(); ResteasyProviderFactory providerFactory = - (ResteasyProviderFactory) entry.getValue().getProviderFactory(); + (ResteasyProviderFactory) entry.getValue().getProviderFactory(); ServiceRegistry service = new ServiceRegistry(null, registry, providerFactory, null); services.put(entry.getKey(), service); } diff --git a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIWriter.java b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIWriter.java index 613876f4f2e..56e18feb08e 100755 --- a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIWriter.java +++ b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/JSAPIWriter.java @@ -174,10 +174,10 @@ private void declarePrefix(PrintWriter writer, String declaringPrefix, Set= 0) @@ -193,12 +193,12 @@ private void print(PrintWriter writer, String httpMethod, String uri = methodMetaData.getUri(); writer.println("// " + httpMethod + " " + uri); writer - .println(methodMetaData.getFunctionName() + " = function(_params){"); + .println(methodMetaData.getFunctionName() + " = function(_params){"); writer.println(" var params = _params ? _params : {};"); writer.println(" var request = new REST.Request();"); writer.println(" request.setMethod('" + httpMethod + "');"); writer - .println(" var uri = params.$apiURL ? params.$apiURL : REST.apiURL;"); + .println(" var uri = params.$apiURL ? params.$apiURL : REST.apiURL;"); if (uri.contains("{")) { printURIParams(uri, writer); @@ -211,7 +211,7 @@ private void print(PrintWriter writer, String httpMethod, writer.println(" request.setURI(uri);"); writer.println(" if(params.$username && params.$password)"); writer - .println(" request.setCredentials(params.$username, params.$password);"); + .println(" request.setCredentials(params.$username, params.$password);"); writer.println(" if(params.$accepts)"); writer.println(" request.setAccepts(params.$accepts);"); if (methodMetaData.getWants() != null) @@ -234,14 +234,14 @@ private void print(PrintWriter writer, String httpMethod, writer.println(" request.setContentType(params.$contentType);"); writer.println(" else"); writer.println(" request.setContentType('" - + methodMetaData.getConsumesMIMEType() + "');"); + + methodMetaData.getConsumesMIMEType() + "');"); writer.println(" if(params.$callback){"); writer.println(" request.execute(params.$callback);"); writer.println(" }else{"); writer.println(" var returnValue;"); writer.println(" request.setAsync(false);"); writer - .println(" var callback = function(httpCode, xmlHttpRequest, value){ returnValue = value;};"); + .println(" var callback = function(httpCode, xmlHttpRequest, value){ returnValue = value;};"); writer.println(" request.execute(callback);"); writer.println(" return returnValue;"); writer.println(" }"); @@ -309,7 +309,7 @@ private void printURIParams(String uri, PrintWriter writer) if (matcher.start() > i) { writer.println(" uri += '" - + replacedCurlyURI.substring(i, matcher.start()) + "';"); + + replacedCurlyURI.substring(i, matcher.start()) + "';"); } String name = matcher.group(1); writer.println(" uri += REST.Encoding.encodePathSegment(params." + name + ");"); diff --git a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/MethodMetaData.java b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/MethodMetaData.java index 856a42bee4f..8ed3d814dca 100644 --- a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/MethodMetaData.java +++ b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/MethodMetaData.java @@ -31,265 +31,265 @@ public class MethodMetaData { - private ResourceMethodInvoker invoker; - private Method method; - private ResourceMethod resourceMethod; - private Class klass; - private String wants; - private String consumesMIMEType; - private String uri; - private String functionName; - private List parameters = new ArrayList(); - private Collection httpMethods; - private ServiceRegistry registry; - private String functionPrefix; - private boolean wantsForm; - - public MethodMetaData(ServiceRegistry serviceRegistry, ResourceMethodInvoker invoker) throws Exception { - this.registry = serviceRegistry; - this.invoker = invoker; - this.method = invoker.getMethod(); - - this.resourceMethod = (ResourceMethod) getResourceLocator(invoker); - this.klass = invoker.getResourceClass(); - - String methodPath = resourceMethod.getPath(); - String klassPath = resourceMethod.getResourceClass().getPath(); - Produces produces = method.getAnnotation(Produces.class); - - if (produces == null) - produces = klass.getAnnotation(Produces.class); - this.wants = getWants(produces); - Consumes consumes = method.getAnnotation(Consumes.class); - if (consumes == null) - consumes = klass.getAnnotation(Consumes.class); - - - this.uri = appendURIFragments(registry, klassPath, methodPath); - - if(serviceRegistry.isRoot()) - this.functionPrefix = klass.getSimpleName(); - else - this.functionPrefix = serviceRegistry.getFunctionPrefix(); - this.functionName = this.functionPrefix + "." + method.getName(); - httpMethods = invoker.getHttpMethods(); - - // we need to add all parameters from parent resource locators until the root - List methodsUntilRoot = new ArrayList(); - methodsUntilRoot.add(method); - serviceRegistry.collectResourceMethodsUntilRoot(methodsUntilRoot); - for (Method method : methodsUntilRoot) { - Annotation[][] allAnnotations = method.getParameterAnnotations(); - Class[] parameterTypes = method.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) - { - processMetaData(parameterTypes[i], allAnnotations[i], true); - } - } - // this must be after we scan the params in case of @Form - this.consumesMIMEType = getConsumes(consumes); - if(wantsForm && !"application/x-www-form-urlencoded".equals(consumesMIMEType)){ - LogMessages.LOGGER.warn(Messages.MESSAGES.overridingConsumes()); - this.consumesMIMEType = "application/x-www-form-urlencoded"; - } - } - - public static ResourceLocator getResourceLocator(ResourceInvoker invoker) throws Exception { - Field resourceMethodField = null; - resourceMethodField = invoker.getClass().getDeclaredField("method"); - resourceMethodField.setAccessible(true); - return (ResourceLocator) resourceMethodField.get(invoker); - } - - protected void processMetaData(Class type, Annotation[] annotations, - boolean useBody) - { - QueryParam query; - HeaderParam header; - MatrixParam matrix; - PathParam uriParam; - CookieParam cookie; - FormParam formParam; - Form form; - - // boolean isEncoded = FindAnnotation.findAnnotation(annotations, - // Encoded.class) != null; - - if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) - { - addParameter(type, annotations, MethodParamType.QUERY_PARAMETER, query - .value()); - } else if ((header = FindAnnotation.findAnnotation(annotations, - HeaderParam.class)) != null) - { - addParameter(type, annotations, MethodParamType.HEADER_PARAMETER, - header.value()); - } else if ((cookie = FindAnnotation.findAnnotation(annotations, - CookieParam.class)) != null) - { - addParameter(type, annotations, MethodParamType.COOKIE_PARAMETER, - cookie.value()); - } else if ((uriParam = FindAnnotation.findAnnotation(annotations, - PathParam.class)) != null) - { - addParameter(type, annotations, MethodParamType.PATH_PARAMETER, - uriParam.value()); - } else if ((matrix = FindAnnotation.findAnnotation(annotations, - MatrixParam.class)) != null) - { - addParameter(type, annotations, MethodParamType.MATRIX_PARAMETER, - matrix.value()); - } else if ((formParam = FindAnnotation.findAnnotation(annotations, - FormParam.class)) != null) - { - addParameter(type, annotations, MethodParamType.FORM_PARAMETER, - formParam.value()); - this.wantsForm = true; - } else if ((form = FindAnnotation.findAnnotation(annotations, Form.class)) != null) - { - if (type == Map.class || type == List.class) { - addParameter(type, annotations, MethodParamType.FORM, form.prefix()); - this.wantsForm = true; - } else - walkForm(type); - } else if ((FindAnnotation.findAnnotation(annotations, Context.class)) != null) - { - // righfully ignore - } else if (useBody) - { - addParameter(type, annotations, MethodParamType.ENTITY_PARAMETER, null); - } - } - - private void walkForm(Class type) - { - for (Field field : type.getDeclaredFields()) - { - processMetaData(field.getType(), field.getAnnotations(), false); - } - for (Method method : type.getDeclaredMethods()) - { - if (method.getParameterTypes().length != 1 - || !method.getReturnType().equals(Void.class)) - continue; - processMetaData(method.getParameterTypes()[0], - method.getAnnotations(), false); - } - if (type.getSuperclass() != null) { - walkForm(type.getSuperclass()); - } - } - - private void addParameter(Class type, Annotation[] annotations, - MethodParamType paramType, String value) - { - this.parameters.add(new MethodParamMetaData(type, annotations, paramType, - value)); - } - - private String getWants(Produces produces) - { - if (produces == null) - return null; - String[] value = produces.value(); - if (value.length == 0) - return null; - if (value.length == 1) - return value[0]; - StringBuffer buf = new StringBuffer(); - for (String mime : produces.value()) - { - if (buf.length() != 0) - buf.append(","); - buf.append(mime); - } - return buf.toString(); - } - - private String getConsumes(Consumes consumes) - { - if (consumes == null) - return "text/plain"; - if (consumes.value().length > 0) - return consumes.value()[0]; - return "text/plain"; - } - - public static String appendURIFragments(ServiceRegistry registry, String classPath, String methodPath) { - return appendURIFragments(registry == null ? null : registry.getUri(), - notEmpty(classPath) ? classPath : null, - notEmpty(methodPath) ? methodPath : null); - } - - public static String appendURIFragments(String... fragments) - { - StringBuilder str = new StringBuilder(); - for (String fragment : fragments) - { - if (fragment == null || fragment.length() == 0 || fragment.equals("/")) - continue; - if (fragment.startsWith("/")) - fragment = fragment.substring(1); - if (fragment.endsWith("/")) - fragment = fragment.substring(0, fragment.length() - 1); - str.append('/').append(fragment); - } - if (str.length() == 0) - return "/"; - return str.toString(); - } - - public ResourceMethodInvoker getInvoker() - { - return invoker; - } - - public Method getMethod() - { - return method; - } - - public Class getKlass() - { - return klass; - } - - public String getWants() - { - return wants; - } - - public String getConsumesMIMEType() - { - return consumesMIMEType; - } - - public String getUri() - { - return uri; - } - - public String getFunctionName() - { - return functionName; - } - - public List getParameters() - { - return parameters; - } - - public Collection getHttpMethods() - { - return httpMethods; - } - - - private static boolean notEmpty(String string) { - return string != null && !string.isEmpty(); - } - - public String getFunctionPrefix() { - return functionPrefix; - } + private ResourceMethodInvoker invoker; + private Method method; + private ResourceMethod resourceMethod; + private Class klass; + private String wants; + private String consumesMIMEType; + private String uri; + private String functionName; + private List parameters = new ArrayList(); + private Collection httpMethods; + private ServiceRegistry registry; + private String functionPrefix; + private boolean wantsForm; + + public MethodMetaData(ServiceRegistry serviceRegistry, ResourceMethodInvoker invoker) throws Exception { + this.registry = serviceRegistry; + this.invoker = invoker; + this.method = invoker.getMethod(); + + this.resourceMethod = (ResourceMethod) getResourceLocator(invoker); + this.klass = invoker.getResourceClass(); + + String methodPath = resourceMethod.getPath(); + String klassPath = resourceMethod.getResourceClass().getPath(); + Produces produces = method.getAnnotation(Produces.class); + + if (produces == null) + produces = klass.getAnnotation(Produces.class); + this.wants = getWants(produces); + Consumes consumes = method.getAnnotation(Consumes.class); + if (consumes == null) + consumes = klass.getAnnotation(Consumes.class); + + + this.uri = appendURIFragments(registry, klassPath, methodPath); + + if(serviceRegistry.isRoot()) + this.functionPrefix = klass.getSimpleName(); + else + this.functionPrefix = serviceRegistry.getFunctionPrefix(); + this.functionName = this.functionPrefix + "." + method.getName(); + httpMethods = invoker.getHttpMethods(); + + // we need to add all parameters from parent resource locators until the root + List methodsUntilRoot = new ArrayList(); + methodsUntilRoot.add(method); + serviceRegistry.collectResourceMethodsUntilRoot(methodsUntilRoot); + for (Method method : methodsUntilRoot) { + Annotation[][] allAnnotations = method.getParameterAnnotations(); + Class[] parameterTypes = method.getParameterTypes(); + for (int i = 0; i < parameterTypes.length; i++) + { + processMetaData(parameterTypes[i], allAnnotations[i], true); + } + } + // this must be after we scan the params in case of @Form + this.consumesMIMEType = getConsumes(consumes); + if(wantsForm && !"application/x-www-form-urlencoded".equals(consumesMIMEType)){ + LogMessages.LOGGER.warn(Messages.MESSAGES.overridingConsumes()); + this.consumesMIMEType = "application/x-www-form-urlencoded"; + } + } + + public static ResourceLocator getResourceLocator(ResourceInvoker invoker) throws Exception { + Field resourceMethodField = null; + resourceMethodField = invoker.getClass().getDeclaredField("method"); + resourceMethodField.setAccessible(true); + return (ResourceLocator) resourceMethodField.get(invoker); + } + + protected void processMetaData(Class type, Annotation[] annotations, + boolean useBody) + { + QueryParam query; + HeaderParam header; + MatrixParam matrix; + PathParam uriParam; + CookieParam cookie; + FormParam formParam; + Form form; + + // boolean isEncoded = FindAnnotation.findAnnotation(annotations, + // Encoded.class) != null; + + if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) + { + addParameter(type, annotations, MethodParamType.QUERY_PARAMETER, query + .value()); + } else if ((header = FindAnnotation.findAnnotation(annotations, + HeaderParam.class)) != null) + { + addParameter(type, annotations, MethodParamType.HEADER_PARAMETER, + header.value()); + } else if ((cookie = FindAnnotation.findAnnotation(annotations, + CookieParam.class)) != null) + { + addParameter(type, annotations, MethodParamType.COOKIE_PARAMETER, + cookie.value()); + } else if ((uriParam = FindAnnotation.findAnnotation(annotations, + PathParam.class)) != null) + { + addParameter(type, annotations, MethodParamType.PATH_PARAMETER, + uriParam.value()); + } else if ((matrix = FindAnnotation.findAnnotation(annotations, + MatrixParam.class)) != null) + { + addParameter(type, annotations, MethodParamType.MATRIX_PARAMETER, + matrix.value()); + } else if ((formParam = FindAnnotation.findAnnotation(annotations, + FormParam.class)) != null) + { + addParameter(type, annotations, MethodParamType.FORM_PARAMETER, + formParam.value()); + this.wantsForm = true; + } else if ((form = FindAnnotation.findAnnotation(annotations, Form.class)) != null) + { + if (type == Map.class || type == List.class) { + addParameter(type, annotations, MethodParamType.FORM, form.prefix()); + this.wantsForm = true; + } else + walkForm(type); + } else if ((FindAnnotation.findAnnotation(annotations, Context.class)) != null) + { + // righfully ignore + } else if (useBody) + { + addParameter(type, annotations, MethodParamType.ENTITY_PARAMETER, null); + } + } + + private void walkForm(Class type) + { + for (Field field : type.getDeclaredFields()) + { + processMetaData(field.getType(), field.getAnnotations(), false); + } + for (Method method : type.getDeclaredMethods()) + { + if (method.getParameterTypes().length != 1 + || !method.getReturnType().equals(Void.class)) + continue; + processMetaData(method.getParameterTypes()[0], + method.getAnnotations(), false); + } + if (type.getSuperclass() != null) { + walkForm(type.getSuperclass()); + } + } + + private void addParameter(Class type, Annotation[] annotations, + MethodParamType paramType, String value) + { + this.parameters.add(new MethodParamMetaData(type, annotations, paramType, + value)); + } + + private String getWants(Produces produces) + { + if (produces == null) + return null; + String[] value = produces.value(); + if (value.length == 0) + return null; + if (value.length == 1) + return value[0]; + StringBuffer buf = new StringBuffer(); + for (String mime : produces.value()) + { + if (buf.length() != 0) + buf.append(","); + buf.append(mime); + } + return buf.toString(); + } + + private String getConsumes(Consumes consumes) + { + if (consumes == null) + return "text/plain"; + if (consumes.value().length > 0) + return consumes.value()[0]; + return "text/plain"; + } + + public static String appendURIFragments(ServiceRegistry registry, String classPath, String methodPath) { + return appendURIFragments(registry == null ? null : registry.getUri(), + notEmpty(classPath) ? classPath : null, + notEmpty(methodPath) ? methodPath : null); + } + + public static String appendURIFragments(String... fragments) + { + StringBuilder str = new StringBuilder(); + for (String fragment : fragments) + { + if (fragment == null || fragment.length() == 0 || fragment.equals("/")) + continue; + if (fragment.startsWith("/")) + fragment = fragment.substring(1); + if (fragment.endsWith("/")) + fragment = fragment.substring(0, fragment.length() - 1); + str.append('/').append(fragment); + } + if (str.length() == 0) + return "/"; + return str.toString(); + } + + public ResourceMethodInvoker getInvoker() + { + return invoker; + } + + public Method getMethod() + { + return method; + } + + public Class getKlass() + { + return klass; + } + + public String getWants() + { + return wants; + } + + public String getConsumesMIMEType() + { + return consumesMIMEType; + } + + public String getUri() + { + return uri; + } + + public String getFunctionName() + { + return functionName; + } + + public List getParameters() + { + return parameters; + } + + public Collection getHttpMethods() + { + return httpMethods; + } + + + private static boolean notEmpty(String string) { + return string != null && !string.isEmpty(); + } + + public String getFunctionPrefix() { + return functionPrefix; + } } diff --git a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/ServiceRegistry.java b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/ServiceRegistry.java index e10c29a8859..add8a80cbfd 100755 --- a/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/ServiceRegistry.java +++ b/resteasy-jsapi/src/main/java/org/jboss/resteasy/jsapi/ServiceRegistry.java @@ -21,116 +21,116 @@ */ public class ServiceRegistry { - private static final long serialVersionUID = -1985015444704126795L; - - private ResourceMethodRegistry registry; - - private ResteasyProviderFactory providerFactory; - - private ServiceRegistry parent; - - private ArrayList methods; - - private ArrayList locators; - - private ResourceLocatorInvoker invoker; - - private String uri; - - private String functionPrefix; - - public ServiceRegistry getParent() { - return parent; - } - - public ServiceRegistry(ServiceRegistry parent, ResourceMethodRegistry registry, - ResteasyProviderFactory providerFactory, ResourceLocatorInvoker invoker) throws Exception { - this.parent = parent; - this.registry = registry; - this.providerFactory = providerFactory; - this.invoker = invoker; - if(invoker != null){ - Method method = invoker.getMethod(); - - ResourceLocator resourceLocator = MethodMetaData.getResourceLocator(invoker); - - String methodPathVal = resourceLocator.getPath(); - String classPathVal = resourceLocator.getResourceClass().getPath(); - - this.uri = MethodMetaData.appendURIFragments(parent, classPathVal, methodPathVal); - - if(parent.isRoot()) - this.functionPrefix = method.getDeclaringClass().getSimpleName() + "." + method.getName(); - else - this.functionPrefix = parent.getFunctionPrefix() + "." + method.getName(); - } - scanRegistry(); - } - - private void scanRegistry() throws Exception { - methods = new ArrayList(); - locators = new ArrayList(); - for (Entry> entry : registry.getBounded().entrySet()) - { - List invokers = entry.getValue(); - for (ResourceInvoker invoker : invokers) - { - if (invoker instanceof ResourceMethodInvoker) - { - methods.add(new MethodMetaData(this, (ResourceMethodInvoker) invoker)); - } else if(invoker instanceof ResourceLocatorInvoker) - { - ResourceLocatorInvoker locator = (ResourceLocatorInvoker) invoker; - Method method = locator.getMethod(); - Class locatorType = method.getReturnType(); - Class[] locatorResourceTypes = GetRestful.getSubResourceClasses(locatorType); - for (Class locatorResourceType : locatorResourceTypes) - { - if (locatorResourceType == null) - { - // FIXME: we could generate an error for the client, which would be more informative than - // just logging this - if (LogMessages.LOGGER.isEnabled(Level.WARN)) - LogMessages.LOGGER.warn(Messages.MESSAGES.impossibleToGenerateJsapi(method.getDeclaringClass().getName(), method.getName())); - // skip this - continue; - } - ResourceMethodRegistry locatorRegistry = new ResourceMethodRegistry(providerFactory); - locatorRegistry.addResourceFactory(null, null, locatorResourceType); - locators.add(new ServiceRegistry(this, locatorRegistry, providerFactory, locator)); - } - } - } - } - } - - - public List getMethodMetaData() - { - return methods; - } - - public List getLocators() { - return locators; - } - - public String getUri() { - return uri; - } - - public boolean isRoot() { - return parent == null; - } - - public String getFunctionPrefix() { - return functionPrefix; - } - - public void collectResourceMethodsUntilRoot(List methods){ - if(isRoot()) - return; - methods.add(invoker.getMethod()); - parent.collectResourceMethodsUntilRoot(methods); - } + private static final long serialVersionUID = -1985015444704126795L; + + private ResourceMethodRegistry registry; + + private ResteasyProviderFactory providerFactory; + + private ServiceRegistry parent; + + private ArrayList methods; + + private ArrayList locators; + + private ResourceLocatorInvoker invoker; + + private String uri; + + private String functionPrefix; + + public ServiceRegistry getParent() { + return parent; + } + + public ServiceRegistry(ServiceRegistry parent, ResourceMethodRegistry registry, + ResteasyProviderFactory providerFactory, ResourceLocatorInvoker invoker) throws Exception { + this.parent = parent; + this.registry = registry; + this.providerFactory = providerFactory; + this.invoker = invoker; + if(invoker != null){ + Method method = invoker.getMethod(); + + ResourceLocator resourceLocator = MethodMetaData.getResourceLocator(invoker); + + String methodPathVal = resourceLocator.getPath(); + String classPathVal = resourceLocator.getResourceClass().getPath(); + + this.uri = MethodMetaData.appendURIFragments(parent, classPathVal, methodPathVal); + + if(parent.isRoot()) + this.functionPrefix = method.getDeclaringClass().getSimpleName() + "." + method.getName(); + else + this.functionPrefix = parent.getFunctionPrefix() + "." + method.getName(); + } + scanRegistry(); + } + + private void scanRegistry() throws Exception { + methods = new ArrayList(); + locators = new ArrayList(); + for (Entry> entry : registry.getBounded().entrySet()) + { + List invokers = entry.getValue(); + for (ResourceInvoker invoker : invokers) + { + if (invoker instanceof ResourceMethodInvoker) + { + methods.add(new MethodMetaData(this, (ResourceMethodInvoker) invoker)); + } else if(invoker instanceof ResourceLocatorInvoker) + { + ResourceLocatorInvoker locator = (ResourceLocatorInvoker) invoker; + Method method = locator.getMethod(); + Class locatorType = method.getReturnType(); + Class[] locatorResourceTypes = GetRestful.getSubResourceClasses(locatorType); + for (Class locatorResourceType : locatorResourceTypes) + { + if (locatorResourceType == null) + { + // FIXME: we could generate an error for the client, which would be more informative than + // just logging this + if (LogMessages.LOGGER.isEnabled(Level.WARN)) + LogMessages.LOGGER.warn(Messages.MESSAGES.impossibleToGenerateJsapi(method.getDeclaringClass().getName(), method.getName())); + // skip this + continue; + } + ResourceMethodRegistry locatorRegistry = new ResourceMethodRegistry(providerFactory); + locatorRegistry.addResourceFactory(null, null, locatorResourceType); + locators.add(new ServiceRegistry(this, locatorRegistry, providerFactory, locator)); + } + } + } + } + } + + + public List getMethodMetaData() + { + return methods; + } + + public List getLocators() { + return locators; + } + + public String getUri() { + return uri; + } + + public boolean isRoot() { + return parent == null; + } + + public String getFunctionPrefix() { + return functionPrefix; + } + + public void collectResourceMethodsUntilRoot(List methods){ + if(isRoot()) + return; + methods.add(invoker.getMethod()); + parent.collectResourceMethodsUntilRoot(methods); + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/AddLinks.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/AddLinks.java index 6121823b008..b29ce6ebcbc 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/AddLinks.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/AddLinks.java @@ -18,7 +18,7 @@ * @author Stéphane Épardaud */ @Target( { ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER, - ElementType.FIELD }) + ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) @Decorator(processor = LinkDecorator.class, target = Marshaller.class) @Documented diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/ELProvider.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/ELProvider.java index a2a154b28cb..2ba02a0ff48 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/ELProvider.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/ELProvider.java @@ -8,11 +8,11 @@ * @author Stéphane Épardaud */ public interface ELProvider { - /** - * Returns an ELContext to use for any @LinkResource constraint and pathParameters. - * You can wrap the given default context or extend it, but you must return something. - * @param ctx the default content to wrap, extend, or just return as is. - * @return the ELContext to use for @LinkResource - */ - ELContext getContext(ELContext ctx); + /** + * Returns an ELContext to use for any @LinkResource constraint and pathParameters. + * You can wrap the given default context or extend it, but you must return something. + * @param ctx the default content to wrap, extend, or just return as is. + * @return the ELContext to use for @LinkResource + */ + ELContext getContext(ELContext ctx); } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkELProvider.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkELProvider.java index c5e973912d7..9ed8c41660e 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkELProvider.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkELProvider.java @@ -16,9 +16,9 @@ @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LinkELProvider { - /** - * The class for the custom ELProvider that will set up the EL context for your - * resource discovery. - */ - Class value(); + /** + * The class for the custom ELProvider that will set up the EL context for your + * resource discovery. + */ + Class value(); } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResource.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResource.java index 422ae185fd1..5504ca493a9 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResource.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResource.java @@ -15,94 +15,94 @@ @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LinkResource { - /** - * The type of entity that should receive links for this service. Defaults to the request's body - * entity type, or the response entity type if they are not a {@link java.util.Collection Collection} or a {@link javax.ws.rs.core.Response Response}. - */ - Class value() default Void.class; + /** + * The type of entity that should receive links for this service. Defaults to the request's body + * entity type, or the response entity type if they are not a {@link java.util.Collection Collection} or a {@link javax.ws.rs.core.Response Response}. + */ + Class value() default Void.class; - /** - * The link relation. This defaults as follows: - *
- *
list
- *
{@link javax.ws.rs.GET GET} for {@link ResourceFacade} entities or methods that return a {@link java.util.Collection Collection}
- *
- *
- *
self
- *
{@link javax.ws.rs.GET GET} for non-{@link ResourceFacade} and non-{@link java.util.Collection Collection} entities
- *
- *
- *
remove
- *
{@link javax.ws.rs.DELETE DELETE}
- *
- *
- *
add
- *
{@link javax.ws.rs.POST POST}
- *
- *
- *
update
- *
{@link javax.ws.rs.PUT PUT}
- *
- */ - String rel() default ""; + /** + * The link relation. This defaults as follows: + *
+ *
list
+ *
{@link javax.ws.rs.GET GET} for {@link ResourceFacade} entities or methods that return a {@link java.util.Collection Collection}
+ *
+ *
+ *
self
+ *
{@link javax.ws.rs.GET GET} for non-{@link ResourceFacade} and non-{@link java.util.Collection Collection} entities
+ *
+ *
+ *
remove
+ *
{@link javax.ws.rs.DELETE DELETE}
+ *
+ *
+ *
add
+ *
{@link javax.ws.rs.POST POST}
+ *
+ *
+ *
update
+ *
{@link javax.ws.rs.PUT PUT}
+ *
+ */ + String rel() default ""; - /** - *

- * List of path parameter EL from the leftmost URI path parameter to the rightmost. These can be - * normal constant string values or EL expressions (${foo.bar}) that will resolve using either the - * default EL context, or the context specified by a {@link LinkELProvider @LinkELProvider} annotation. The default context - * resolves any non-qualified variable to properties of the response entity for whom we're discovering - * links, and has an extra binding for the "this" variable which is the response entity as well. - *

- *

- * If there are too many parameters for the current path, only the leftmost useful ones will be used. - *

- *

- * Defaults to using discovery of values from the entity itself with {@link ResourceID @ResourceID}, - * {@link ResourceIDs @ResourceIDs}, JAXB's @XmlID or JPA's @Id and {@link ParentResource @ParentResource}. - *

- *

- * This is not used for {@link ResourceFacade} entities, which provide their own list of path parameters. - *

- */ - String[] pathParameters() default {}; - - /** - *

- * List of query parameters which should be attached to the link. - *

- */ - ParamBinding[] queryParameters() default {}; - - /** - *

- * List of matrix parameters which should be attached to the link. - *

- */ - ParamBinding[] matrixParameters() default {}; - - /** - *

- * EL expression that should return a boolean indicating whether or not this service link should be used. - * This is useful for security constraints limiting access to resources. Defaults to using the - * {@link javax.annotation.security.RolesAllowed @RolesAllowed} annotation using the current - * {@link javax.ws.rs.core.SecurityContext SecurityContext} to check the current user's permissions. - *

- *

- * This can be a normal constant boolean value ("true" or "false") or an EL expression - * (${foo.bar}) that will resolve using either the - * default EL context, or the context specified by a {@link LinkELProvider @LinkELProvider} annotation. - *

- *

- * For entities that are not {@link ResourceFacade}, the default context - * resolves any non-qualified variable to properties of the response entity for whom we're discovering - * links, and has an extra binding for the "this" variable which is the response entity as well. - *

- *

- * For entities that are a {@link ResourceFacade}, the default context - * has single binding for the "this" variable which is the {@link ResourceFacade}'s entity type - * ({@link java.lang.Class Class} instance). - *

- */ - String constraint() default ""; + /** + *

+ * List of path parameter EL from the leftmost URI path parameter to the rightmost. These can be + * normal constant string values or EL expressions (${foo.bar}) that will resolve using either the + * default EL context, or the context specified by a {@link LinkELProvider @LinkELProvider} annotation. The default context + * resolves any non-qualified variable to properties of the response entity for whom we're discovering + * links, and has an extra binding for the "this" variable which is the response entity as well. + *

+ *

+ * If there are too many parameters for the current path, only the leftmost useful ones will be used. + *

+ *

+ * Defaults to using discovery of values from the entity itself with {@link ResourceID @ResourceID}, + * {@link ResourceIDs @ResourceIDs}, JAXB's @XmlID or JPA's @Id and {@link ParentResource @ParentResource}. + *

+ *

+ * This is not used for {@link ResourceFacade} entities, which provide their own list of path parameters. + *

+ */ + String[] pathParameters() default {}; + + /** + *

+ * List of query parameters which should be attached to the link. + *

+ */ + ParamBinding[] queryParameters() default {}; + + /** + *

+ * List of matrix parameters which should be attached to the link. + *

+ */ + ParamBinding[] matrixParameters() default {}; + + /** + *

+ * EL expression that should return a boolean indicating whether or not this service link should be used. + * This is useful for security constraints limiting access to resources. Defaults to using the + * {@link javax.annotation.security.RolesAllowed @RolesAllowed} annotation using the current + * {@link javax.ws.rs.core.SecurityContext SecurityContext} to check the current user's permissions. + *

+ *

+ * This can be a normal constant boolean value ("true" or "false") or an EL expression + * (${foo.bar}) that will resolve using either the + * default EL context, or the context specified by a {@link LinkELProvider @LinkELProvider} annotation. + *

+ *

+ * For entities that are not {@link ResourceFacade}, the default context + * resolves any non-qualified variable to properties of the response entity for whom we're discovering + * links, and has an extra binding for the "this" variable which is the response entity as well. + *

+ *

+ * For entities that are a {@link ResourceFacade}, the default context + * has single binding for the "this" variable which is the {@link ResourceFacade}'s entity type + * ({@link java.lang.Class Class} instance). + *

+ */ + String constraint() default ""; } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResources.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResources.java index 8461fa29541..8226aa506ca 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResources.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/LinkResources.java @@ -15,8 +15,8 @@ @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LinkResources { - /** - * The list of {@link LinkResource} that apply on this method - */ - LinkResource[] value(); + /** + * The list of {@link LinkResource} that apply on this method + */ + LinkResource[] value(); } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/ParamBinding.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/ParamBinding.java index 88284db9a43..4cc2609cf79 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/ParamBinding.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/ParamBinding.java @@ -7,22 +7,22 @@ */ public @interface ParamBinding { - /** - * Name of the URI template parameter. - */ - String name(); + /** + * Name of the URI template parameter. + */ + String name(); + + /** + *

+ * Expression language expression specifying the value of the parameter. + * These can be normal constant string values or EL expressions (${foo.bar}) + * that will resolve using either the default EL context, or the context + * specified by a {@link LinkELProvider @LinkELProvider} annotation. The + * default context resolves any non-qualified variable to properties of the + * response entity for whom we're discovering links, and has an extra + * binding for the "this" variable which is the response entity as well. + *

+ */ + String value(); - /** - *

- * Expression language expression specifying the value of the parameter. - * These can be normal constant string values or EL expressions (${foo.bar}) - * that will resolve using either the default EL context, or the context - * specified by a {@link LinkELProvider @LinkELProvider} annotation. The - * default context resolves any non-qualified variable to properties of the - * response entity for whom we're discovering links, and has an extra - * binding for the "this" variable which is the response entity as well. - *

- */ - String value(); - } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/RESTServiceDiscovery.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/RESTServiceDiscovery.java index 1b6c9f31dd6..ec907bca91d 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/RESTServiceDiscovery.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/RESTServiceDiscovery.java @@ -24,149 +24,149 @@ @XmlAccessorType(XmlAccessType.NONE) public class RESTServiceDiscovery extends ArrayList{ - /** - * An Atom link - * @author Stéphane Épardaud - */ - @XmlRootElement(name = "link", namespace = "http://www.w3.org/2005/Atom") - @XmlAccessorType(XmlAccessType.NONE) - public static class AtomLink { - @XmlAttribute - String rel; - @XmlAttribute - String href; - @XmlAttribute - String type; - @XmlAttribute - String hreflang; - @XmlAttribute - String title; - @XmlAttribute - String length; - - public AtomLink() { - } - - public AtomLink(String href, String rel) { - this.href = href; - this.rel = rel; - } - - public String getRel() { - return rel; - } - - public void setRel(String rel) { - this.rel = rel; - } - - public String getHref() { - return href; - } - - public void setHref(String href) { - this.href = href; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getHreflang() { - return hreflang; - } - - public void setHreflang(String hreflang) { - this.hreflang = hreflang; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getLength() { - return length; - } - - public void setLength(String length) { - this.length = length; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((href == null) ? 0 : href.hashCode()); - result = prime * result + ((hreflang == null) ? 0 : hreflang.hashCode()); - result = prime * result + ((length == null) ? 0 : length.hashCode()); - result = prime * result + ((rel == null) ? 0 : rel.hashCode()); - result = prime * result + ((title == null) ? 0 : title.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AtomLink other = (AtomLink) obj; - if (href == null) { - if (other.href != null) - return false; - } else if (!href.equals(other.href)) - return false; - if (hreflang == null) { - if (other.hreflang != null) - return false; - } else if (!hreflang.equals(other.hreflang)) - return false; - if (length == null) { - if (other.length != null) - return false; - } else if (!length.equals(other.length)) - return false; - if (rel == null) { - if (other.rel != null) - return false; - } else if (!rel.equals(other.rel)) - return false; - if (title == null) { - if (other.title != null) - return false; - } else if (!title.equals(other.title)) - return false; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - return true; - } - } - - public void addLink(URI uri, String rel) { - AtomLink link = new AtomLink(uri.toString(), rel); - if (!contains(link)) { - add(link); - } - } - - public AtomLink getLinkForRel(String rel){ - for(AtomLink link : this){ - if(rel.equals(link.getRel())) - return link; - } - return null; - } + /** + * An Atom link + * @author Stéphane Épardaud + */ + @XmlRootElement(name = "link", namespace = "http://www.w3.org/2005/Atom") + @XmlAccessorType(XmlAccessType.NONE) + public static class AtomLink { + @XmlAttribute + String rel; + @XmlAttribute + String href; + @XmlAttribute + String type; + @XmlAttribute + String hreflang; + @XmlAttribute + String title; + @XmlAttribute + String length; + + public AtomLink() { + } + + public AtomLink(String href, String rel) { + this.href = href; + this.rel = rel; + } + + public String getRel() { + return rel; + } + + public void setRel(String rel) { + this.rel = rel; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getHreflang() { + return hreflang; + } + + public void setHreflang(String hreflang) { + this.hreflang = hreflang; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getLength() { + return length; + } + + public void setLength(String length) { + this.length = length; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((href == null) ? 0 : href.hashCode()); + result = prime * result + ((hreflang == null) ? 0 : hreflang.hashCode()); + result = prime * result + ((length == null) ? 0 : length.hashCode()); + result = prime * result + ((rel == null) ? 0 : rel.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AtomLink other = (AtomLink) obj; + if (href == null) { + if (other.href != null) + return false; + } else if (!href.equals(other.href)) + return false; + if (hreflang == null) { + if (other.hreflang != null) + return false; + } else if (!hreflang.equals(other.hreflang)) + return false; + if (length == null) { + if (other.length != null) + return false; + } else if (!length.equals(other.length)) + return false; + if (rel == null) { + if (other.rel != null) + return false; + } else if (!rel.equals(other.rel)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + return true; + } + } + + public void addLink(URI uri, String rel) { + AtomLink link = new AtomLink(uri.toString(), rel); + if (!contains(link)) { + add(link); + } + } + + public AtomLink getLinkForRel(String rel){ + for(AtomLink link : this){ + if(rel.equals(link.getRel())) + return link; + } + return null; + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceFacade.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceFacade.java index 7f2c0f10096..8fb03f75546 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceFacade.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceFacade.java @@ -13,25 +13,25 @@ * @param the type of entity that this facade should receive links for */ public interface ResourceFacade { - /** - * Returns the type of entity that this facade should receive links for. If we represent - * a list of Comment entities, then that would be the type to return. - */ - Class facadeFor(); - - /** - *

- * Returns a map of path parameters to use to build any path to this facade's type's links. If there - * are too many path parameter for a link, the extra ones will be ignored, but if there are not enough - * path parameters the link will be skipped. - *

- *

- * For example, when scanning a facade for a list of order comments for an order with ID "foo", - * you should return a map for - * {orderId {@literal =>} "foo"}, which will get you links for "/order/{orderId}/comments" ("list" and "add") - * but not for "/order/{orderId}/comment/{commentId}" since those need actual Comment instances ("self" and - * "delete"). - *

- */ - Map pathParameters(); + /** + * Returns the type of entity that this facade should receive links for. If we represent + * a list of Comment entities, then that would be the type to return. + */ + Class facadeFor(); + + /** + *

+ * Returns a map of path parameters to use to build any path to this facade's type's links. If there + * are too many path parameter for a link, the extra ones will be ignored, but if there are not enough + * path parameters the link will be skipped. + *

+ *

+ * For example, when scanning a facade for a list of order comments for an order with ID "foo", + * you should return a map for + * {orderId {@literal =>} "foo"}, which will get you links for "/order/{orderId}/comments" ("list" and "add") + * but not for "/order/{orderId}/comment/{commentId}" since those need actual Comment instances ("self" and + * "delete"). + *

+ */ + Map pathParameters(); } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceIDs.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceIDs.java index 861c04827f0..59a06ce532a 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceIDs.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/ResourceIDs.java @@ -22,5 +22,5 @@ @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ResourceIDs { - String[] value(); + String[] value(); } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BaseELResolver.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BaseELResolver.java index 3bc7db80652..8d8d4e03fc6 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BaseELResolver.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BaseELResolver.java @@ -8,50 +8,50 @@ public class BaseELResolver extends ELResolver { - private final ELResolver delegateResolver; - private final Object base; - - public BaseELResolver(Object base) { - this.base = base; - this.delegateResolver = new BeanELResolver(true); - } - - @Override - public Class getCommonPropertyType(ELContext context, Object base) { - return null; - } - - @Override - public Iterator getFeatureDescriptors(ELContext context, - Object base) { - return null; - } - - @Override - public Class getType(ELContext context, Object base, Object property) { - return null; - } - - @Override - public Object getValue(ELContext context, Object base, Object property) { - if (base == null){ - if("this".equals(property)){ - context.setPropertyResolved(true); - return this.base; - } - return delegateResolver.getValue(context, this.base, property); - } - return null; - } - - @Override - public boolean isReadOnly(ELContext context, Object base, Object property) { - return true; - } - - @Override - public void setValue(ELContext context, Object base, Object property, - Object value) { - } + private final ELResolver delegateResolver; + private final Object base; + + public BaseELResolver(Object base) { + this.base = base; + this.delegateResolver = new BeanELResolver(true); + } + + @Override + public Class getCommonPropertyType(ELContext context, Object base) { + return null; + } + + @Override + public Iterator getFeatureDescriptors(ELContext context, + Object base) { + return null; + } + + @Override + public Class getType(ELContext context, Object base, Object property) { + return null; + } + + @Override + public Object getValue(ELContext context, Object base, Object property) { + if (base == null){ + if("this".equals(property)){ + context.setPropertyResolved(true); + return this.base; + } + return delegateResolver.getValue(context, this.base, property); + } + return null; + } + + @Override + public boolean isReadOnly(ELContext context, Object base, Object property) { + return true; + } + + @Override + public void setValue(ELContext context, Object base, Object property, + Object value) { + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BeanUtils.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BeanUtils.java index 8ec7e3fdfe3..372d0687d1b 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BeanUtils.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/BeanUtils.java @@ -16,156 +16,156 @@ import java.util.List; public class BeanUtils { - @SuppressWarnings(value = "unchecked") - private static final Class[] IdAnnotationList = new Class[]{ResourceID.class, XmlID.class, Id.class}; + @SuppressWarnings(value = "unchecked") + private static final Class[] IdAnnotationList = new Class[]{ResourceID.class, XmlID.class, Id.class}; - public static List findIDs(Object entity){ - Class klass = entity.getClass(); - ResourceIDs resourceIDs = findTypeAnnotation(klass, ResourceIDs.class); - if(resourceIDs != null){ - // return those properties - String[] names = resourceIDs.value(); - List values = new ArrayList(); - for (String name : names) { - try { - values.add(getPropertyValue(entity, entity.getClass(), name)); - } catch (NotFoundException e) { - throw new RuntimeException(Messages.MESSAGES.failedToFindBeanProperty(name)); - } - } - return values; - } - for(Class idAnnotationClass : IdAnnotationList){ - try { - return Collections.singletonList(findAnnotatedProperty(entity, klass, idAnnotationClass)); - } catch (NotFoundException e) { - // ignore - } - } - // we got nothing - return Collections.emptyList(); - } + public static List findIDs(Object entity){ + Class klass = entity.getClass(); + ResourceIDs resourceIDs = findTypeAnnotation(klass, ResourceIDs.class); + if(resourceIDs != null){ + // return those properties + String[] names = resourceIDs.value(); + List values = new ArrayList(); + for (String name : names) { + try { + values.add(getPropertyValue(entity, entity.getClass(), name)); + } catch (NotFoundException e) { + throw new RuntimeException(Messages.MESSAGES.failedToFindBeanProperty(name)); + } + } + return values; + } + for(Class idAnnotationClass : IdAnnotationList){ + try { + return Collections.singletonList(findAnnotatedProperty(entity, klass, idAnnotationClass)); + } catch (NotFoundException e) { + // ignore + } + } + // we got nothing + return Collections.emptyList(); + } - private static Object getPropertyValue(Object entity, - Class klass, String name) throws NotFoundException { - // easiest is a public property: - try { - return readPropertyMethods(entity, klass, name, false); - } catch (NotFoundException e) { - // ignore - } - // not found, try private properties - do{ - try { - return readPropertyMethods(entity, klass, name, true); - } catch (NotFoundException e) { - // ignore - } - // try the field - try { - Field f = klass.getDeclaredField(name); - return readField(f, entity); - } catch (SecurityException e) { - // there's one but it's not accessible? - throw new RuntimeException(Messages.MESSAGES.failedToReadProperty(name), e); - } catch (NoSuchFieldException e) { - // ignore - } - // go up - klass = klass.getSuperclass(); - }while(klass != null); - // we got nothing - throw new NotFoundException(); - } + private static Object getPropertyValue(Object entity, + Class klass, String name) throws NotFoundException { + // easiest is a public property: + try { + return readPropertyMethods(entity, klass, name, false); + } catch (NotFoundException e) { + // ignore + } + // not found, try private properties + do{ + try { + return readPropertyMethods(entity, klass, name, true); + } catch (NotFoundException e) { + // ignore + } + // try the field + try { + Field f = klass.getDeclaredField(name); + return readField(f, entity); + } catch (SecurityException e) { + // there's one but it's not accessible? + throw new RuntimeException(Messages.MESSAGES.failedToReadProperty(name), e); + } catch (NoSuchFieldException e) { + // ignore + } + // go up + klass = klass.getSuperclass(); + }while(klass != null); + // we got nothing + throw new NotFoundException(); + } - private static Object readPropertyMethods(Object entity, Class klass, - String propertyName, boolean b) throws NotFoundException { - try { - return readPropertyMethod(entity, klass, "is"+capitalise(propertyName), false); - } catch (NotFoundException e) { - // ignore - } - // let this one throw - return readPropertyMethod(entity, klass, "get"+capitalise(propertyName), false); - } + private static Object readPropertyMethods(Object entity, Class klass, + String propertyName, boolean b) throws NotFoundException { + try { + return readPropertyMethod(entity, klass, "is"+capitalise(propertyName), false); + } catch (NotFoundException e) { + // ignore + } + // let this one throw + return readPropertyMethod(entity, klass, "get"+capitalise(propertyName), false); + } - private static Object readPropertyMethod(Object entity, Class klass, - String methodName, boolean declared) throws NotFoundException { - try{ - Method getter = declared ? klass.getDeclaredMethod(methodName) : klass.getMethod(methodName); - return readMethod(getter, entity); - } catch (SecurityException e) { - // there's one but it's not accessible? - throw new RuntimeException(Messages.MESSAGES.failedToReadProperty(methodName), e); - } catch (NoSuchMethodException e) { - throw new NotFoundException(); - } - } + private static Object readPropertyMethod(Object entity, Class klass, + String methodName, boolean declared) throws NotFoundException { + try{ + Method getter = declared ? klass.getDeclaredMethod(methodName) : klass.getMethod(methodName); + return readMethod(getter, entity); + } catch (SecurityException e) { + // there's one but it's not accessible? + throw new RuntimeException(Messages.MESSAGES.failedToReadProperty(methodName), e); + } catch (NoSuchMethodException e) { + throw new NotFoundException(); + } + } - private static String capitalise(String name) { - return name.substring(0, 1).toUpperCase() + name.substring(1); - } + private static String capitalise(String name) { + return name.substring(0, 1).toUpperCase() + name.substring(1); + } - private static T findTypeAnnotation(Class klass, - Class annotationClass) { - do{ - if(klass.isAnnotationPresent(annotationClass)) - return klass.getAnnotation(annotationClass); - klass = klass.getSuperclass(); - }while(klass != null); - return null; - } + private static T findTypeAnnotation(Class klass, + Class annotationClass) { + do{ + if(klass.isAnnotationPresent(annotationClass)) + return klass.getAnnotation(annotationClass); + klass = klass.getSuperclass(); + }while(klass != null); + return null; + } - public static Object findParentResource(Object entity) { - try { - return findAnnotatedProperty(entity, entity.getClass(), ParentResource.class); - } catch (NotFoundException e) { - return null; - } - } + public static Object findParentResource(Object entity) { + try { + return findAnnotatedProperty(entity, entity.getClass(), ParentResource.class); + } catch (NotFoundException e) { + return null; + } + } - private static Object findAnnotatedProperty(Object entity, Class type, Class annotation) throws NotFoundException { - for(Field f : type.getDeclaredFields()){ - if(f.isAnnotationPresent(annotation)){ - return readField(f, entity); - } - } - for(Method m : type.getDeclaredMethods()){ - if(m.isAnnotationPresent(annotation) && isBeanAccessor(m)){ - return readMethod(m, entity); - } - } - if(type.getSuperclass() != null) - return findAnnotatedProperty(entity, type.getSuperclass(), annotation); - throw new NotFoundException(); - } + private static Object findAnnotatedProperty(Object entity, Class type, Class annotation) throws NotFoundException { + for(Field f : type.getDeclaredFields()){ + if(f.isAnnotationPresent(annotation)){ + return readField(f, entity); + } + } + for(Method m : type.getDeclaredMethods()){ + if(m.isAnnotationPresent(annotation) && isBeanAccessor(m)){ + return readMethod(m, entity); + } + } + if(type.getSuperclass() != null) + return findAnnotatedProperty(entity, type.getSuperclass(), annotation); + throw new NotFoundException(); + } - private static Object readMethod(Method m, Object entity) { - // read that property - m.setAccessible(true); - try { - return m.invoke(entity); - } catch (Exception e) { - throw new RuntimeException(Messages.MESSAGES.failedToReadPropertyFromMethod(m.getName()), e); - }finally{ - m.setAccessible(false); - } - } + private static Object readMethod(Method m, Object entity) { + // read that property + m.setAccessible(true); + try { + return m.invoke(entity); + } catch (Exception e) { + throw new RuntimeException(Messages.MESSAGES.failedToReadPropertyFromMethod(m.getName()), e); + }finally{ + m.setAccessible(false); + } + } - private static Object readField(Field f, Object entity) { - // read that field - f.setAccessible(true); - try { - return f.get(entity); - } catch (Exception e) { - throw new RuntimeException(Messages.MESSAGES.failedToReadField(f.getName()), e); - }finally{ - f.setAccessible(false); - } - } + private static Object readField(Field f, Object entity) { + // read that field + f.setAccessible(true); + try { + return f.get(entity); + } catch (Exception e) { + throw new RuntimeException(Messages.MESSAGES.failedToReadField(f.getName()), e); + }finally{ + f.setAccessible(false); + } + } - private static boolean isBeanAccessor(Method m) { - String name = m.getName(); - return (name.startsWith("get") || name.startsWith("is")) && m.getParameterTypes().length == 0; - } + private static boolean isBeanAccessor(Method m) { + String name = m.getName(); + return (name.startsWith("get") || name.startsWith("is")) && m.getParameterTypes().length == 0; + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/EL.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/EL.java index 2af35fe7ca5..2e75a71283a 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/EL.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/EL.java @@ -13,26 +13,26 @@ import javax.el.StandardELContext; public class EL { - public static final ExpressionFactory EXPRESSION_FACTORY = ExpressionFactory.newInstance(); + public static final ExpressionFactory EXPRESSION_FACTORY = ExpressionFactory.newInstance(); - private static ELResolver createELResolver(Object base) { - CompositeELResolver resolver = new CompositeELResolver(); - if (base != null) { resolver.add(new BaseELResolver(base)); } - resolver.add(new MapELResolver()); - resolver.add(new ListELResolver()); - resolver.add(new ArrayELResolver()); - resolver.add(new ResourceBundleELResolver()); - resolver.add(new BeanELResolver()); - return resolver; - } + private static ELResolver createELResolver(Object base) { + CompositeELResolver resolver = new CompositeELResolver(); + if (base != null) { resolver.add(new BaseELResolver(base)); } + resolver.add(new MapELResolver()); + resolver.add(new ListELResolver()); + resolver.add(new ArrayELResolver()); + resolver.add(new ResourceBundleELResolver()); + resolver.add(new BeanELResolver()); + return resolver; + } - public static ELContext createELContext(final Object base) { - return new StandardELContext(EXPRESSION_FACTORY) { - @Override - public ELResolver getELResolver() { - return createELResolver(base); - } + public static ELContext createELContext(final Object base) { + return new StandardELContext(EXPRESSION_FACTORY) { + @Override + public ELResolver getELResolver() { + return createELResolver(base); + } - }; - } + }; + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/LinkDecorator.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/LinkDecorator.java index c3e000b9398..1867cecbd14 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/LinkDecorator.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/LinkDecorator.java @@ -14,18 +14,18 @@ public class LinkDecorator implements DecoratorProcessor { - public Marshaller decorate(Marshaller target, final AddLinks annotation, - Class type, Annotation[] annotations, MediaType mediaType) { - target.setListener(new Listener() { - @Override - public void beforeMarshal(Object entity) { - UriInfo uriInfo = ResteasyProviderFactory.getContextData(UriInfo.class); - ResourceMethodRegistry registry = (ResourceMethodRegistry) ResteasyProviderFactory.getContextData(Registry.class); + public Marshaller decorate(Marshaller target, final AddLinks annotation, + Class type, Annotation[] annotations, MediaType mediaType) { + target.setListener(new Listener() { + @Override + public void beforeMarshal(Object entity) { + UriInfo uriInfo = ResteasyProviderFactory.getContextData(UriInfo.class); + ResourceMethodRegistry registry = (ResourceMethodRegistry) ResteasyProviderFactory.getContextData(Registry.class); - // find all rest service classes and scan them - RESTUtils.addDiscovery(entity, uriInfo, registry); - } - }); - return target; - } + // find all rest service classes and scan them + RESTUtils.addDiscovery(entity, uriInfo, registry); + } + }); + return target; + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/RESTUtils.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/RESTUtils.java index 66fd2958838..9327fe48cd7 100755 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/RESTUtils.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/RESTUtils.java @@ -43,309 +43,309 @@ public class RESTUtils { - public static T addDiscovery(T entity, UriInfo uriInfo, ResourceMethodRegistry registry) { - // find the field to inject first - Field injectionField = findInjectionField(entity); - if (injectionField == null) - return entity; - List methods = getServiceMethods(registry); - - RESTServiceDiscovery ret = null; - try { - injectionField.setAccessible(true); - ret = (RESTServiceDiscovery) injectionField.get(entity); - } catch (Exception e) { - LogMessages.LOGGER.error(Messages.MESSAGES.failedToReuseServiceDiscovery(entity), e); - } - if (ret == null) { - ret = new RESTServiceDiscovery(); - } - for(Method m : methods){ - processLinkResources(m, entity, uriInfo, ret); - } - // do not inject an empty service - if(ret.isEmpty()) - return entity; - // now inject - try { - injectionField.set(entity, ret); - injectionField.setAccessible(false); - } catch (Exception e) { - LogMessages.LOGGER.error(Messages.MESSAGES.failedToInjectLinks(entity), e); - } - return entity; - } + public static T addDiscovery(T entity, UriInfo uriInfo, ResourceMethodRegistry registry) { + // find the field to inject first + Field injectionField = findInjectionField(entity); + if (injectionField == null) + return entity; + List methods = getServiceMethods(registry); - private static Field findInjectionField(Object entity) { - Class klass = entity.getClass(); - do{ - for(Field f : klass.getDeclaredFields()){ - if(f.getType().equals(RESTServiceDiscovery.class)) - return f; - } - klass = klass.getSuperclass(); - }while(klass != null); - return null; - } + RESTServiceDiscovery ret = null; + try { + injectionField.setAccessible(true); + ret = (RESTServiceDiscovery) injectionField.get(entity); + } catch (Exception e) { + LogMessages.LOGGER.error(Messages.MESSAGES.failedToReuseServiceDiscovery(entity), e); + } + if (ret == null) { + ret = new RESTServiceDiscovery(); + } + for(Method m : methods){ + processLinkResources(m, entity, uriInfo, ret); + } + // do not inject an empty service + if(ret.isEmpty()) + return entity; + // now inject + try { + injectionField.set(entity, ret); + injectionField.setAccessible(false); + } catch (Exception e) { + LogMessages.LOGGER.error(Messages.MESSAGES.failedToInjectLinks(entity), e); + } + return entity; + } - public static List getServiceMethods(ResourceMethodRegistry registry){ - ArrayList results = new ArrayList(); - for (Entry> entry : registry.getBounded().entrySet()) - { - List invokers = entry.getValue(); - for (ResourceInvoker invoker : invokers) - { - if (invoker instanceof ResourceMethodInvoker) - { - ResourceMethodInvoker resourceMethod = (ResourceMethodInvoker)invoker; - Method method = resourceMethod.getMethod(); - results.add(method); - } else - { - // TODO: fix this? - } - } - } - return results; - } + private static Field findInjectionField(Object entity) { + Class klass = entity.getClass(); + do{ + for(Field f : klass.getDeclaredFields()){ + if(f.getType().equals(RESTServiceDiscovery.class)) + return f; + } + klass = klass.getSuperclass(); + }while(klass != null); + return null; + } - private static void processLinkResources(Method m, Object entity, UriInfo uriInfo, - RESTServiceDiscovery ret) { - // find a single service - LinkResource service = m - .getAnnotation(LinkResource.class); - if(service != null) - processLinkResource(m, entity, uriInfo, ret, service); - // find a multi-service - LinkResources services = m - .getAnnotation(LinkResources.class); - if(services != null) - for(LinkResource service2 : services.value()) - processLinkResource(m, entity, uriInfo, ret, service2); - } + public static List getServiceMethods(ResourceMethodRegistry registry){ + ArrayList results = new ArrayList(); + for (Entry> entry : registry.getBounded().entrySet()) + { + List invokers = entry.getValue(); + for (ResourceInvoker invoker : invokers) + { + if (invoker instanceof ResourceMethodInvoker) + { + ResourceMethodInvoker resourceMethod = (ResourceMethodInvoker)invoker; + Method method = resourceMethod.getMethod(); + results.add(method); + } else + { + // TODO: fix this? + } + } + } + return results; + } - private static void processLinkResource(Method m, Object entity, UriInfo uriInfo, - RESTServiceDiscovery ret, LinkResource service) { - String rel = service.rel(); - // if we have uri templates, we need a compatible instance - Class type = getServiceType(service, m); - if(type.isInstance(entity)){ - if(checkConstraint(service, entity, m)) - addInstanceService(m, entity, uriInfo, ret, service, rel); - }else if(entity instanceof ResourceFacade && ((ResourceFacade)entity).facadeFor() == type){ - if(checkConstraint(service, type, m)) - addService(m, (ResourceFacade) entity, uriInfo, ret, service, rel); - } - } + private static void processLinkResources(Method m, Object entity, UriInfo uriInfo, + RESTServiceDiscovery ret) { + // find a single service + LinkResource service = m + .getAnnotation(LinkResource.class); + if(service != null) + processLinkResource(m, entity, uriInfo, ret, service); + // find a multi-service + LinkResources services = m + .getAnnotation(LinkResources.class); + if(services != null) + for(LinkResource service2 : services.value()) + processLinkResource(m, entity, uriInfo, ret, service2); + } - private static Class getServiceType(LinkResource service, Method m) { - Class type = service.value(); - if(type != Void.class) - return type; - // are we looking at the return type or the body type? - type = findBodyType(m); - if(type == null){ - // our next best bet is the return type - type = m.getReturnType(); - } - if(Void.TYPE == type) - throw new ServiceDiscoveryException(m, Messages.MESSAGES.cannotGuessResourceType()); - if(Collection.class.isAssignableFrom(type)) - throw new ServiceDiscoveryException(m, Messages.MESSAGES.cannotGuessCollectionType()); - if(Response.class.isAssignableFrom(type)) - throw new ServiceDiscoveryException(m, Messages.MESSAGES.cannotGuessType()); - return type; - } + private static void processLinkResource(Method m, Object entity, UriInfo uriInfo, + RESTServiceDiscovery ret, LinkResource service) { + String rel = service.rel(); + // if we have uri templates, we need a compatible instance + Class type = getServiceType(service, m); + if(type.isInstance(entity)){ + if(checkConstraint(service, entity, m)) + addInstanceService(m, entity, uriInfo, ret, service, rel); + }else if(entity instanceof ResourceFacade && ((ResourceFacade)entity).facadeFor() == type){ + if(checkConstraint(service, type, m)) + addService(m, (ResourceFacade) entity, uriInfo, ret, service, rel); + } + } - private static Class findBodyType(Method m) { - Annotation[][] annotations = m.getParameterAnnotations(); - Class[] types = m.getParameterTypes(); - for (int i = 0; i < types.length; i++) { - // if there's no JAXRS annotation nor @Form, it's a body right? - if(FindAnnotation.findJaxRSAnnotations(annotations[i]).length == 0 - && FindAnnotation.findAnnotation(annotations[i], Form.class) == null) - return types[i]; - } - return null; - } + private static Class getServiceType(LinkResource service, Method m) { + Class type = service.value(); + if(type != Void.class) + return type; + // are we looking at the return type or the body type? + type = findBodyType(m); + if(type == null){ + // our next best bet is the return type + type = m.getReturnType(); + } + if(Void.TYPE == type) + throw new ServiceDiscoveryException(m, Messages.MESSAGES.cannotGuessResourceType()); + if(Collection.class.isAssignableFrom(type)) + throw new ServiceDiscoveryException(m, Messages.MESSAGES.cannotGuessCollectionType()); + if(Response.class.isAssignableFrom(type)) + throw new ServiceDiscoveryException(m, Messages.MESSAGES.cannotGuessType()); + return type; + } - private static boolean checkConstraint(LinkResource service, Object object, Method m) { - String constraint = service.constraint(); - if(constraint == null || constraint.length() == 0) - return checkEJBConstraint(m); - Boolean ret = evaluateELBoolean(m, getELContext(m, object), object, constraint); - return ret != null && ret.booleanValue(); - } + private static Class findBodyType(Method m) { + Annotation[][] annotations = m.getParameterAnnotations(); + Class[] types = m.getParameterTypes(); + for (int i = 0; i < types.length; i++) { + // if there's no JAXRS annotation nor @Form, it's a body right? + if(FindAnnotation.findJaxRSAnnotations(annotations[i]).length == 0 + && FindAnnotation.findAnnotation(annotations[i], Form.class) == null) + return types[i]; + } + return null; + } - private static boolean checkEJBConstraint(Method m) { - // Use dynamic class loading here since if the EJB annotation class is not present - // it cannot be on the method, so we don't have to check for it - try { - Class.forName("javax.annotation.security.RolesAllowed"); - } catch (ClassNotFoundException e) { - // class not here, therefore not on method either - return true; - } - // From now on we can use this class since it's there. I (Stef Epardaud) don't think we need to - // remove the reference here and use reflection. - RolesAllowed rolesAllowed = m.getAnnotation(RolesAllowed.class); - if(rolesAllowed == null) - return true; - SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class); - for(String role : rolesAllowed.value()) - if(context.isUserInRole(role)) - return true; - return false; - } + private static boolean checkConstraint(LinkResource service, Object object, Method m) { + String constraint = service.constraint(); + if(constraint == null || constraint.length() == 0) + return checkEJBConstraint(m); + Boolean ret = evaluateELBoolean(m, getELContext(m, object), object, constraint); + return ret != null && ret.booleanValue(); + } - private static void addService(Method m, ResourceFacade entity, UriInfo uriInfo, - RESTServiceDiscovery ret, LinkResource service, String rel) { - Map pathParameters = entity.pathParameters(); - // do we need any path parameters? - UriBuilder uriBuilder = uriInfo.getBaseUriBuilder().path(m.getDeclaringClass()); - if(m.isAnnotationPresent(Path.class)) - uriBuilder.path(m); - URI uri; - List paramNames = ((ResteasyUriBuilder)uriBuilder).getPathParamNamesInDeclarationOrder(); - if(paramNames.isEmpty()) - uri = uriBuilder.build(); - else if(pathParameters.size() >= paramNames.size()) - uri = uriBuilder.buildFromMap(pathParameters); - else - // just bail out since we don't have enough parameters, that must be an instance service - return; - if(rel.length() == 0){ - if (m.isAnnotationPresent(GET.class)) - rel = "list"; - else if (m.isAnnotationPresent(POST.class)) - rel = "add"; - } - ret.addLink(uri, rel); - } + private static boolean checkEJBConstraint(Method m) { + // Use dynamic class loading here since if the EJB annotation class is not present + // it cannot be on the method, so we don't have to check for it + try { + Class.forName("javax.annotation.security.RolesAllowed"); + } catch (ClassNotFoundException e) { + // class not here, therefore not on method either + return true; + } + // From now on we can use this class since it's there. I (Stef Epardaud) don't think we need to + // remove the reference here and use reflection. + RolesAllowed rolesAllowed = m.getAnnotation(RolesAllowed.class); + if(rolesAllowed == null) + return true; + SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class); + for(String role : rolesAllowed.value()) + if(context.isUserInRole(role)) + return true; + return false; + } - private static void addInstanceService(Method m, Object entity, - UriInfo uriInfo, RESTServiceDiscovery ret, LinkResource service, - String rel) { - UriBuilder uriBuilder = uriInfo.getBaseUriBuilder().path(m.getDeclaringClass()); - if(m.isAnnotationPresent(Path.class)) - uriBuilder.path(m); - URI uri = buildURI(uriBuilder, service, entity, m); + private static void addService(Method m, ResourceFacade entity, UriInfo uriInfo, + RESTServiceDiscovery ret, LinkResource service, String rel) { + Map pathParameters = entity.pathParameters(); + // do we need any path parameters? + UriBuilder uriBuilder = uriInfo.getBaseUriBuilder().path(m.getDeclaringClass()); + if(m.isAnnotationPresent(Path.class)) + uriBuilder.path(m); + URI uri; + List paramNames = ((ResteasyUriBuilder)uriBuilder).getPathParamNamesInDeclarationOrder(); + if(paramNames.isEmpty()) + uri = uriBuilder.build(); + else if(pathParameters.size() >= paramNames.size()) + uri = uriBuilder.buildFromMap(pathParameters); + else + // just bail out since we don't have enough parameters, that must be an instance service + return; + if(rel.length() == 0){ + if (m.isAnnotationPresent(GET.class)) + rel = "list"; + else if (m.isAnnotationPresent(POST.class)) + rel = "add"; + } + ret.addLink(uri, rel); + } - if (rel.length() == 0) { - if (m.isAnnotationPresent(GET.class)){ - Class type = m.getReturnType(); - if(Collection.class.isAssignableFrom(type)) - rel = "list"; - else - rel = "self"; - }else if (m.isAnnotationPresent(PUT.class)) - rel = "update"; - else if (m.isAnnotationPresent(POST.class)) - rel = "add"; - else if (m.isAnnotationPresent(DELETE.class)) - rel = "remove"; - } - ret.addLink(uri, rel); - } + private static void addInstanceService(Method m, Object entity, + UriInfo uriInfo, RESTServiceDiscovery ret, LinkResource service, + String rel) { + UriBuilder uriBuilder = uriInfo.getBaseUriBuilder().path(m.getDeclaringClass()); + if(m.isAnnotationPresent(Path.class)) + uriBuilder.path(m); + URI uri = buildURI(uriBuilder, service, entity, m); - private static URI buildURI(UriBuilder uriBuilder, LinkResource service, - Object entity, Method m) { - for (ParamBinding binding : service.queryParameters()) { - uriBuilder.queryParam(binding.name(), evaluateEL(m, getELContext(m, entity), entity, binding.value())); - } - for (ParamBinding binding : service.matrixParameters()) { - uriBuilder.matrixParam(binding.name(), evaluateEL(m, getELContext(m, entity), entity, binding.value())); - } - - String[] uriTemplates = service.pathParameters(); - if (uriTemplates.length > 0) { - Object[] values = new Object[uriTemplates.length]; - for (int i = 0; i < values.length; i++) - values[i] = evaluateEL(m, getELContext(m, entity), entity, uriTemplates[i]); - return uriBuilder.build(values); - } - // do we need any path parameters? - List paramNames = ((ResteasyUriBuilder)uriBuilder).getPathParamNamesInDeclarationOrder(); - if(paramNames.isEmpty()) - return uriBuilder.build(); - // try to find the IDs - List params = findURIParamsFromResource(entity); - if(params.size() == paramNames.size()) - return uriBuilder.build(params.toArray()); - // if we have too many, ignore the last ones - if(params.size() > paramNames.size()) - return uriBuilder.build(params.subList(0, paramNames.size()).toArray()); - throw new ServiceDiscoveryException(m, Messages.MESSAGES.notEnoughtUriParameters(paramNames.size(), params.size())); - } + if (rel.length() == 0) { + if (m.isAnnotationPresent(GET.class)){ + Class type = m.getReturnType(); + if(Collection.class.isAssignableFrom(type)) + rel = "list"; + else + rel = "self"; + }else if (m.isAnnotationPresent(PUT.class)) + rel = "update"; + else if (m.isAnnotationPresent(POST.class)) + rel = "add"; + else if (m.isAnnotationPresent(DELETE.class)) + rel = "remove"; + } + ret.addLink(uri, rel); + } - private static List findURIParamsFromResource(Object entity) { - List ids = new ArrayList(); - do{ - List theseIDs = BeanUtils.findIDs(entity); - ids.addAll(0, theseIDs); - }while((entity = BeanUtils.findParentResource(entity)) != null); - return ids; - } + private static URI buildURI(UriBuilder uriBuilder, LinkResource service, + Object entity, Method m) { + for (ParamBinding binding : service.queryParameters()) { + uriBuilder.queryParam(binding.name(), evaluateEL(m, getELContext(m, entity), entity, binding.value())); + } + for (ParamBinding binding : service.matrixParameters()) { + uriBuilder.matrixParam(binding.name(), evaluateEL(m, getELContext(m, entity), entity, binding.value())); + } - private static LinkELProvider findLinkELProvider(Method m){ - if(m.isAnnotationPresent(LinkELProvider.class)) - return m.getAnnotation(LinkELProvider.class); - Class c = m.getDeclaringClass(); - if(c.isAnnotationPresent(LinkELProvider.class)) - return c.getAnnotation(LinkELProvider.class); - Package p = c.getPackage(); - if(p != null && p.isAnnotationPresent(LinkELProvider.class)) - return p.getAnnotation(LinkELProvider.class); - return null; - } + String[] uriTemplates = service.pathParameters(); + if (uriTemplates.length > 0) { + Object[] values = new Object[uriTemplates.length]; + for (int i = 0; i < values.length; i++) + values[i] = evaluateEL(m, getELContext(m, entity), entity, uriTemplates[i]); + return uriBuilder.build(values); + } + // do we need any path parameters? + List paramNames = ((ResteasyUriBuilder)uriBuilder).getPathParamNamesInDeclarationOrder(); + if(paramNames.isEmpty()) + return uriBuilder.build(); + // try to find the IDs + List params = findURIParamsFromResource(entity); + if(params.size() == paramNames.size()) + return uriBuilder.build(params.toArray()); + // if we have too many, ignore the last ones + if(params.size() > paramNames.size()) + return uriBuilder.build(params.subList(0, paramNames.size()).toArray()); + throw new ServiceDiscoveryException(m, Messages.MESSAGES.notEnoughtUriParameters(paramNames.size(), params.size())); + } - private static ELProvider getELProvider(Method m){ - LinkELProvider linkElProvider = findLinkELProvider(m); - if(linkElProvider == null) - return null; - Class elProviderClass = linkElProvider.value(); - try{ - return elProviderClass.newInstance(); - }catch(Exception x){ - LogMessages.LOGGER.error(Messages.MESSAGES.couldNotInstantiateELProviderClass(elProviderClass.getName()), x); - throw new ServiceDiscoveryException(m, Messages.MESSAGES.failedToInstantiateELProvider(elProviderClass.getName()), x); - } - } + private static List findURIParamsFromResource(Object entity) { + List ids = new ArrayList(); + do{ + List theseIDs = BeanUtils.findIDs(entity); + ids.addAll(0, theseIDs); + }while((entity = BeanUtils.findParentResource(entity)) != null); + return ids; + } - private static ELContext getELContext(Method m, Object base){ - ELContext ours = EL.createELContext(base); - ELProvider elProvider = getELProvider(m); - if(elProvider != null) - return elProvider.getContext(ours); - return ours; - } + private static LinkELProvider findLinkELProvider(Method m){ + if(m.isAnnotationPresent(LinkELProvider.class)) + return m.getAnnotation(LinkELProvider.class); + Class c = m.getDeclaringClass(); + if(c.isAnnotationPresent(LinkELProvider.class)) + return c.getAnnotation(LinkELProvider.class); + Package p = c.getPackage(); + if(p != null && p.isAnnotationPresent(LinkELProvider.class)) + return p.getAnnotation(LinkELProvider.class); + return null; + } - public static Map derivePathParameters(UriInfo uriInfo){ - MultivaluedMap pathParameters = uriInfo.getPathParameters(); - Map ret = new HashMap(); - for(Entry> entry: pathParameters.entrySet()){ - ret.put(entry.getKey(), entry.getValue().get(0)); - } - return ret; - } + private static ELProvider getELProvider(Method m){ + LinkELProvider linkElProvider = findLinkELProvider(m); + if(linkElProvider == null) + return null; + Class elProviderClass = linkElProvider.value(); + try{ + return elProviderClass.newInstance(); + }catch(Exception x){ + LogMessages.LOGGER.error(Messages.MESSAGES.couldNotInstantiateELProviderClass(elProviderClass.getName()), x); + throw new ServiceDiscoveryException(m, Messages.MESSAGES.failedToInstantiateELProvider(elProviderClass.getName()), x); + } + } - public static Object evaluateEL(Method m, ELContext context, Object base, String expression) { - try{ - return EL.EXPRESSION_FACTORY.createValueExpression(context, expression, - Object.class).getValue(context); - }catch(Exception x){ - throw new ServiceDiscoveryException(m, Messages.MESSAGES.failedToEvaluateELExpression(expression), x); - } - } + private static ELContext getELContext(Method m, Object base){ + ELContext ours = EL.createELContext(base); + ELProvider elProvider = getELProvider(m); + if(elProvider != null) + return elProvider.getContext(ours); + return ours; + } - public static Boolean evaluateELBoolean(Method m, ELContext context, Object base, String expression) { - try{ - return (Boolean) EL.EXPRESSION_FACTORY.createValueExpression(context, expression, - Boolean.class).getValue(context); - }catch(Exception x){ - throw new ServiceDiscoveryException(m, Messages.MESSAGES.failedToEvaluateELExpression(expression), x); + public static Map derivePathParameters(UriInfo uriInfo){ + MultivaluedMap pathParameters = uriInfo.getPathParameters(); + Map ret = new HashMap(); + for(Entry> entry: pathParameters.entrySet()){ + ret.put(entry.getKey(), entry.getValue().get(0)); + } + return ret; + } - } - } + public static Object evaluateEL(Method m, ELContext context, Object base, String expression) { + try{ + return EL.EXPRESSION_FACTORY.createValueExpression(context, expression, + Object.class).getValue(context); + }catch(Exception x){ + throw new ServiceDiscoveryException(m, Messages.MESSAGES.failedToEvaluateELExpression(expression), x); + } + } + + public static Boolean evaluateELBoolean(Method m, ELContext context, Object base, String expression) { + try{ + return (Boolean) EL.EXPRESSION_FACTORY.createValueExpression(context, expression, + Boolean.class).getValue(context); + }catch(Exception x){ + throw new ServiceDiscoveryException(m, Messages.MESSAGES.failedToEvaluateELExpression(expression), x); + + } + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/ServiceDiscoveryException.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/ServiceDiscoveryException.java index 8050e9aa6ba..66949fa95cd 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/ServiceDiscoveryException.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/impl/ServiceDiscoveryException.java @@ -7,12 +7,12 @@ public class ServiceDiscoveryException extends Failure { - public ServiceDiscoveryException(Method m, String s) { - super(Messages.MESSAGES.discoveryFailedForMethod(m.getDeclaringClass().getName(), m.getName(), s)); - } + public ServiceDiscoveryException(Method m, String s) { + super(Messages.MESSAGES.discoveryFailedForMethod(m.getDeclaringClass().getName(), m.getName(), s)); + } - public ServiceDiscoveryException(Method m, String s, Throwable cause) { - super(Messages.MESSAGES.discoveryFailedForMethod(m.getDeclaringClass().getName(), m.getName(), s), cause); - } + public ServiceDiscoveryException(Method m, String s, Throwable cause) { + super(Messages.MESSAGES.discoveryFailedForMethod(m.getDeclaringClass().getName(), m.getName(), s), cause); + } } diff --git a/resteasy-links/src/main/java/org/jboss/resteasy/links/package-info.java b/resteasy-links/src/main/java/org/jboss/resteasy/links/package-info.java index 3fe9e08ade4..79cd9a00ceb 100644 --- a/resteasy-links/src/main/java/org/jboss/resteasy/links/package-info.java +++ b/resteasy-links/src/main/java/org/jboss/resteasy/links/package-info.java @@ -2,4 +2,4 @@ package org.jboss.resteasy.links; import javax.xml.bind.annotation.XmlNs; -import javax.xml.bind.annotation.XmlSchema; \ No newline at end of file +import javax.xml.bind.annotation.XmlSchema; diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Book.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Book.java index f1d6896b11f..c81fa2ed40b 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Book.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Book.java @@ -17,67 +17,67 @@ @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) public class Book { - @XmlAttribute - private String author; - @XmlID - @XmlAttribute - private String title; - @XmlElement - // These both fail deserialisation for some reason -// @XmlElement(name = "link", namespace = "http://www.w3.org/2005/Atom") -// @XmlElementRef - private RESTServiceDiscovery rest; - - private List comments = new ArrayList(); - - public Book(String title, String author) { - this.author = author; - this.title = title; - } - - public Book() { - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public RESTServiceDiscovery getRest() { - return rest; - } - - public void setRest(RESTServiceDiscovery rest) { - this.rest = rest; - } - - public List getComments() { - return comments; - } - - public void setComments(List comments) { - this.comments = comments; - } - - public void addComment(int id, String text){ - comments.add(new Comment(id, text, this)); - } - - public Comment getComment(int commentId) { - for(Comment c : comments) - if(c.getId() == commentId) - return c; - return null; - } + @XmlAttribute + private String author; + @XmlID + @XmlAttribute + private String title; + @XmlElement + // These both fail deserialisation for some reason +// @XmlElement(name = "link", namespace = "http://www.w3.org/2005/Atom") +// @XmlElementRef + private RESTServiceDiscovery rest; + + private List comments = new ArrayList(); + + public Book(String title, String author) { + this.author = author; + this.title = title; + } + + public Book() { + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public RESTServiceDiscovery getRest() { + return rest; + } + + public void setRest(RESTServiceDiscovery rest) { + this.rest = rest; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + public void addComment(int id, String text){ + comments.add(new Comment(id, text, this)); + } + + public Comment getComment(int commentId) { + for(Comment c : comments) + if(c.getId() == commentId) + return c; + return null; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStore.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStore.java index 007f3ad977a..a1d5339f32f 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStore.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStore.java @@ -28,137 +28,137 @@ @Path("/") public class BookStore { - - private Map books = new HashMap(); - - { - Book book = new Book("foo", "bar"); - book.addComment(0, "great book"); - book.addComment(1, "terrible book"); - books.put(book.getTitle(), book); - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Book.class, rel = "list") - @GET - @Path("books") - public Collection getBooks(){ - return books.values(); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource(value = Book.class, rel = "add") - @POST - @Path("books") - public void addBook(Book book){ - books.put(book.getTitle(), book); - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Book.class, pathParameters = "${title}") - @GET - @Path("book/{id}") - public Book getBook(@PathParam("id") String id){ - return books.get(id); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource(value = Book.class, pathParameters = "${title}") - @PUT - @Path("book/{id}") - public void updateBook(@PathParam("id") String id, Book book){ - books.put(id, book); - } - - @LinkResource(value = Book.class, pathParameters = "${title}") - @DELETE - @Path("book/{id}") - public void deleteBook(@PathParam("id") String id){ - books.remove(id); - } - - // comments - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResources({ - @LinkResource(value = Book.class, rel = "comments", pathParameters = "${title}"), - @LinkResource(value = Comment.class, rel = "list", pathParameters = "${book.title}") - }) - @GET - @Path("book/{id}/comments") - public Collection getComments(@PathParam("id") String bookId){ - return books.get(bookId).getComments(); - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResources({ - @LinkResource(value = Book.class, rel="comment-collection"), - @LinkResource(value = Comment.class, rel="collection"), - @LinkResource(value = ScrollableCollection.class, rel = "prev", constraint = "${this.start - this.limit >= 0}", queryParameters = { - @ParamBinding(name = "start", value = "${this.start - this.limit}"), - @ParamBinding(name = "limit", value = "${this.limit}") }), - @LinkResource(value = ScrollableCollection.class, rel = "next", constraint = "${this.start + this.limit < this.totalRecords}", queryParameters = { - @ParamBinding(name = "start", value = "${this.start + this.limit}"), - @ParamBinding(name = "limit", value = "${this.limit}") - }, matrixParameters = {@ParamBinding(name = "query", value = "${this.query}")}) - }) - @GET - @Path("book/{id}/comment-collection") - public ScrollableCollection getScrollableComments(@Context UriInfo uriInfo, @PathParam("id") String id, @QueryParam("start") int start, @QueryParam("limit") @DefaultValue("1") int limit, @MatrixParam("query") String query){ - List comments = new ArrayList(); - for (Comment comment : books.get(id).getComments()) { - if (comment.getText().contains(query)) { - comments.add(comment); - } - } - start = start < 0 ? 0 : start; - limit = limit < 1 ? 1 : limit; - limit = (start + limit) > comments.size() ? comments.size() - start : limit; - ScrollableCollection result = new ScrollableCollection(id, start, limit, comments.size(), comments.subList(start, start + limit), query); - - RESTServiceDiscovery discovery = new RESTServiceDiscovery(); - discovery.addLink(uriInfo.getBaseUriBuilder().build(), "home"); - result.setRest(discovery); - - return result; - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Comment.class, rel = "self", pathParameters = {"${book.title}", "${id}"}) - @GET - @Path("book/{id}/comment/{cid}") - public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ - return books.get(bookId).getComment(commentId); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource(value = Comment.class, rel = "add", pathParameters = {"${book.title}"}) - @POST - @Path("book/{id}/comments") - public void addComment(@PathParam("id") String bookId, Comment comment){ - books.get(bookId).getComments().add(comment); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource(value = Comment.class, rel = "update", pathParameters = {"${book.title}", "${id}"}) - @PUT - @Path("book/{id}/comment/{cid}") - public void updateComment(@PathParam("id") String bookId, @PathParam("cid") int commentId, Comment comment){ - books.get(bookId).getComment(commentId).setText(comment.getText()); - } - - @LinkResource(value = Comment.class, rel = "remove", pathParameters = {"${book.title}", "${id}"}) - @DELETE - @Path("book/{id}/comment/{cid}") - public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ - Book book = books.get(bookId); - Comment c = book.getComment(commentId); - book.getComments().remove(c); - } + + private Map books = new HashMap(); + + { + Book book = new Book("foo", "bar"); + book.addComment(0, "great book"); + book.addComment(1, "terrible book"); + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Book.class, rel = "list") + @GET + @Path("books") + public Collection getBooks(){ + return books.values(); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource(value = Book.class, rel = "add") + @POST + @Path("books") + public void addBook(Book book){ + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Book.class, pathParameters = "${title}") + @GET + @Path("book/{id}") + public Book getBook(@PathParam("id") String id){ + return books.get(id); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource(value = Book.class, pathParameters = "${title}") + @PUT + @Path("book/{id}") + public void updateBook(@PathParam("id") String id, Book book){ + books.put(id, book); + } + + @LinkResource(value = Book.class, pathParameters = "${title}") + @DELETE + @Path("book/{id}") + public void deleteBook(@PathParam("id") String id){ + books.remove(id); + } + + // comments + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResources({ + @LinkResource(value = Book.class, rel = "comments", pathParameters = "${title}"), + @LinkResource(value = Comment.class, rel = "list", pathParameters = "${book.title}") + }) + @GET + @Path("book/{id}/comments") + public Collection getComments(@PathParam("id") String bookId){ + return books.get(bookId).getComments(); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResources({ + @LinkResource(value = Book.class, rel="comment-collection"), + @LinkResource(value = Comment.class, rel="collection"), + @LinkResource(value = ScrollableCollection.class, rel = "prev", constraint = "${this.start - this.limit >= 0}", queryParameters = { + @ParamBinding(name = "start", value = "${this.start - this.limit}"), + @ParamBinding(name = "limit", value = "${this.limit}") }), + @LinkResource(value = ScrollableCollection.class, rel = "next", constraint = "${this.start + this.limit < this.totalRecords}", queryParameters = { + @ParamBinding(name = "start", value = "${this.start + this.limit}"), + @ParamBinding(name = "limit", value = "${this.limit}") + }, matrixParameters = {@ParamBinding(name = "query", value = "${this.query}")}) + }) + @GET + @Path("book/{id}/comment-collection") + public ScrollableCollection getScrollableComments(@Context UriInfo uriInfo, @PathParam("id") String id, @QueryParam("start") int start, @QueryParam("limit") @DefaultValue("1") int limit, @MatrixParam("query") String query){ + List comments = new ArrayList(); + for (Comment comment : books.get(id).getComments()) { + if (comment.getText().contains(query)) { + comments.add(comment); + } + } + start = start < 0 ? 0 : start; + limit = limit < 1 ? 1 : limit; + limit = (start + limit) > comments.size() ? comments.size() - start : limit; + ScrollableCollection result = new ScrollableCollection(id, start, limit, comments.size(), comments.subList(start, start + limit), query); + + RESTServiceDiscovery discovery = new RESTServiceDiscovery(); + discovery.addLink(uriInfo.getBaseUriBuilder().build(), "home"); + result.setRest(discovery); + + return result; + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Comment.class, rel = "self", pathParameters = {"${book.title}", "${id}"}) + @GET + @Path("book/{id}/comment/{cid}") + public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ + return books.get(bookId).getComment(commentId); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource(value = Comment.class, rel = "add", pathParameters = {"${book.title}"}) + @POST + @Path("book/{id}/comments") + public void addComment(@PathParam("id") String bookId, Comment comment){ + books.get(bookId).getComments().add(comment); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource(value = Comment.class, rel = "update", pathParameters = {"${book.title}", "${id}"}) + @PUT + @Path("book/{id}/comment/{cid}") + public void updateComment(@PathParam("id") String bookId, @PathParam("cid") int commentId, Comment comment){ + books.get(bookId).getComment(commentId).setText(comment.getText()); + } + + @LinkResource(value = Comment.class, rel = "remove", pathParameters = {"${book.title}", "${id}"}) + @DELETE + @Path("book/{id}/comment/{cid}") + public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ + Book book = books.get(bookId); + Comment c = book.getComment(commentId); + book.getComments().remove(c); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreMinimal.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreMinimal.java index 06fe7f65f6f..9c3cac6011a 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreMinimal.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreMinimal.java @@ -29,136 +29,136 @@ @Path("/") public class BookStoreMinimal { - private Map books = new HashMap(); - - { - Book book = new Book("foo", "bar"); - book.addComment(0, "great book"); - book.addComment(1, "terrible book"); - books.put(book.getTitle(), book); - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Book.class) - @GET - @Path("books") - public Collection getBooks(){ - return books.values(); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource() - @POST - @Path("books") - public void addBook(Book book){ - books.put(book.getTitle(), book); - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource() - @GET - @Path("book/{id}") - public Book getBook(@PathParam("id") String id){ - return books.get(id); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource() - @PUT - @Path("book/{id}") - public void updateBook(@PathParam("id") String id, Book book){ - books.put(id, book); - } - - @LinkResource(value = Book.class) - @DELETE - @Path("book/{id}") - public void deleteBook(@PathParam("id") String id){ - books.remove(id); - } - - // comments - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResources({ - @LinkResource(value = Book.class, rel = "comments"), - @LinkResource(value = Comment.class) - }) - @GET - @Path("book/{id}/comments") - public Collection getComments(@PathParam("id") String bookId){ - return books.get(bookId).getComments(); - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResources({ - @LinkResource(value = Book.class, rel="comment-collection"), - @LinkResource(value = Comment.class, rel="collection"), - @LinkResource(value = ScrollableCollection.class, rel = "prev", constraint = "${this.start - this.limit >= 0}", queryParameters = { - @ParamBinding(name = "start", value = "${this.start - this.limit}"), - @ParamBinding(name = "limit", value = "${this.limit}") }), - @LinkResource(value = ScrollableCollection.class, rel = "next", constraint = "${this.start + this.limit < this.totalRecords}", queryParameters = { - @ParamBinding(name = "start", value = "${this.start + this.limit}"), - @ParamBinding(name = "limit", value = "${this.limit}") - }, matrixParameters = {@ParamBinding(name = "query", value = "${this.query}")}) - }) - @GET - @Path("book/{id}/comment-collection") - public ScrollableCollection getScrollableComments(@Context UriInfo uriInfo, @PathParam("id") String id, @QueryParam("start") int start, @QueryParam("limit") @DefaultValue("1") int limit, @MatrixParam("query") String query){ - List comments = new ArrayList(); - for (Comment comment : books.get(id).getComments()) { - if (comment.getText().contains(query)) { - comments.add(comment); - } - } - start = start < 0 ? 0 : start; - limit = limit < 1 ? 1 : limit; - limit = (start + limit) > comments.size() ? comments.size() - start : limit; - ScrollableCollection result = new ScrollableCollection(id, start, limit, comments.size(), comments.subList(start, start + limit), query); - - RESTServiceDiscovery discovery = new RESTServiceDiscovery(); - discovery.addLink(uriInfo.getBaseUriBuilder().build(), "home"); - result.setRest(discovery); - - return result; - } - - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource() - @GET - @Path("book/{id}/comment/{cid}") - public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ - return books.get(bookId).getComment(commentId); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource() - @POST - @Path("book/{id}/comments") - public void addComment(@PathParam("id") String bookId, Comment comment){ - books.get(bookId).getComments().add(comment); - } - - @Consumes({"application/xml", "application/json"}) - @LinkResource() - @PUT - @Path("book/{id}/comment/{cid}") - public void updateComment(@PathParam("id") String bookId, @PathParam("cid") int commentId, Comment comment){ - books.get(bookId).getComment(commentId).setText(comment.getText()); - } - - @LinkResource(Comment.class) - @DELETE - @Path("book/{id}/comment/{cid}") - public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ - Book book = books.get(bookId); - Comment c = book.getComment(commentId); - book.getComments().remove(c); - } + private Map books = new HashMap(); + + { + Book book = new Book("foo", "bar"); + book.addComment(0, "great book"); + book.addComment(1, "terrible book"); + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Book.class) + @GET + @Path("books") + public Collection getBooks(){ + return books.values(); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource() + @POST + @Path("books") + public void addBook(Book book){ + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource() + @GET + @Path("book/{id}") + public Book getBook(@PathParam("id") String id){ + return books.get(id); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource() + @PUT + @Path("book/{id}") + public void updateBook(@PathParam("id") String id, Book book){ + books.put(id, book); + } + + @LinkResource(value = Book.class) + @DELETE + @Path("book/{id}") + public void deleteBook(@PathParam("id") String id){ + books.remove(id); + } + + // comments + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResources({ + @LinkResource(value = Book.class, rel = "comments"), + @LinkResource(value = Comment.class) + }) + @GET + @Path("book/{id}/comments") + public Collection getComments(@PathParam("id") String bookId){ + return books.get(bookId).getComments(); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResources({ + @LinkResource(value = Book.class, rel="comment-collection"), + @LinkResource(value = Comment.class, rel="collection"), + @LinkResource(value = ScrollableCollection.class, rel = "prev", constraint = "${this.start - this.limit >= 0}", queryParameters = { + @ParamBinding(name = "start", value = "${this.start - this.limit}"), + @ParamBinding(name = "limit", value = "${this.limit}") }), + @LinkResource(value = ScrollableCollection.class, rel = "next", constraint = "${this.start + this.limit < this.totalRecords}", queryParameters = { + @ParamBinding(name = "start", value = "${this.start + this.limit}"), + @ParamBinding(name = "limit", value = "${this.limit}") + }, matrixParameters = {@ParamBinding(name = "query", value = "${this.query}")}) + }) + @GET + @Path("book/{id}/comment-collection") + public ScrollableCollection getScrollableComments(@Context UriInfo uriInfo, @PathParam("id") String id, @QueryParam("start") int start, @QueryParam("limit") @DefaultValue("1") int limit, @MatrixParam("query") String query){ + List comments = new ArrayList(); + for (Comment comment : books.get(id).getComments()) { + if (comment.getText().contains(query)) { + comments.add(comment); + } + } + start = start < 0 ? 0 : start; + limit = limit < 1 ? 1 : limit; + limit = (start + limit) > comments.size() ? comments.size() - start : limit; + ScrollableCollection result = new ScrollableCollection(id, start, limit, comments.size(), comments.subList(start, start + limit), query); + + RESTServiceDiscovery discovery = new RESTServiceDiscovery(); + discovery.addLink(uriInfo.getBaseUriBuilder().build(), "home"); + result.setRest(discovery); + + return result; + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource() + @GET + @Path("book/{id}/comment/{cid}") + public Comment getComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ + return books.get(bookId).getComment(commentId); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource() + @POST + @Path("book/{id}/comments") + public void addComment(@PathParam("id") String bookId, Comment comment){ + books.get(bookId).getComments().add(comment); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource() + @PUT + @Path("book/{id}/comment/{cid}") + public void updateComment(@PathParam("id") String bookId, @PathParam("cid") int commentId, Comment comment){ + books.get(bookId).getComment(commentId).setText(comment.getText()); + } + + @LinkResource(Comment.class) + @DELETE + @Path("book/{id}/comment/{cid}") + public void deleteComment(@PathParam("id") String bookId, @PathParam("cid") int commentId){ + Book book = books.get(bookId); + Comment c = book.getComment(commentId); + book.getComments().remove(c); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreService.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreService.java index b7386a318b7..aa75215ffd0 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreService.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/BookStoreService.java @@ -9,35 +9,35 @@ @Path("/") public interface BookStoreService { - - @Produces({"application/xml"}) - @Path("book/{id}") - @GET - Book getBookXML(@PathParam("id") String id); - - @Produces({"application/json"}) - @Path("book/{id}") - @GET - Book getBookJSON(@PathParam("id") String id); - - @Produces({"application/xml"}) - @Path("book/{id}/comments") - @GET - List getBookCommentsXML(@PathParam("id") String id); - - @Produces({"application/json"}) - @Path("book/{id}/comments") - @GET - List getBookCommentsJSON(@PathParam("id") String id); - - @Produces({"application/xml"}) - @GET - @Path("book/{id}/comment-collection") - ScrollableCollection getScrollableCommentsXML(@PathParam("id") String id, @MatrixParam("query") String query); - - @Produces({"application/json"}) - @GET - @Path("book/{id}/comment-collection") - ScrollableCollection getScrollableCommentsJSON(@PathParam("id") String id, @MatrixParam("query") String query); + + @Produces({"application/xml"}) + @Path("book/{id}") + @GET + Book getBookXML(@PathParam("id") String id); + + @Produces({"application/json"}) + @Path("book/{id}") + @GET + Book getBookJSON(@PathParam("id") String id); + + @Produces({"application/xml"}) + @Path("book/{id}/comments") + @GET + List getBookCommentsXML(@PathParam("id") String id); + + @Produces({"application/json"}) + @Path("book/{id}/comments") + @GET + List getBookCommentsJSON(@PathParam("id") String id); + + @Produces({"application/xml"}) + @GET + @Path("book/{id}/comment-collection") + ScrollableCollection getScrollableCommentsXML(@PathParam("id") String id, @MatrixParam("query") String query); + + @Produces({"application/json"}) + @GET + @Path("book/{id}/comment-collection") + ScrollableCollection getScrollableCommentsJSON(@PathParam("id") String id, @MatrixParam("query") String query); } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Comment.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Comment.java index b5feac48126..258fbe4bbae 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Comment.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/Comment.java @@ -13,58 +13,58 @@ @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) public class Comment { - public int id; - @XmlElement - public String text; - @ParentResource - public Book book; + public int id; + @XmlElement + public String text; + @ParentResource + public Book book; - @XmlElement - // These both fail deserialisation for some reason -// @XmlElement(name = "link", namespace = "http://www.w3.org/2005/Atom") -// @XmlElementRef - private RESTServiceDiscovery rest; + @XmlElement + // These both fail deserialisation for some reason +// @XmlElement(name = "link", namespace = "http://www.w3.org/2005/Atom") +// @XmlElementRef + private RESTServiceDiscovery rest; - public Comment() { - } + public Comment() { + } - public Comment(int id, String text, Book book) { - this.id = id; - this.text = text; - this.book = book; - } + public Comment(int id, String text, Book book) { + this.id = id; + this.text = text; + this.book = book; + } - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - public String getText() { - return text; - } - public void setText(String text) { - this.text = text; - } - public Book getBook() { - return book; - } - public void setBook(Book book) { - this.book = book; - } + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public String getText() { + return text; + } + public void setText(String text) { + this.text = text; + } + public Book getBook() { + return book; + } + public void setBook(Book book) { + this.book = book; + } - public RESTServiceDiscovery getRest() { - return rest; - } + public RESTServiceDiscovery getRest() { + return rest; + } - public void setRest(RESTServiceDiscovery rest) { - this.rest = rest; - } + public void setRest(RESTServiceDiscovery rest) { + this.rest = rest; + } - // JAXB wants an ID to be a String... - @XmlAttribute - @XmlID - public String getXMLID(){ - return Integer.toString(id); - } + // JAXB wants an ID to be a String... + @XmlAttribute + @XmlID + public String getXMLID(){ + return Integer.toString(id); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTest.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTest.java index 4e5a560239b..efd36f2706c 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTest.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTest.java @@ -11,43 +11,43 @@ @Produces("application/xml") @Path("/") public interface IDServiceTest { - @GET - @AddLinks - @LinkResource - @Path("jpa-id/book/{name}") - JpaIdBook getJpaIdBook(@PathParam("name") String name); - - @GET - @AddLinks - @LinkResource - @Path("xml-id/book/{name}") - XmlIdBook getXmlIdBook(@PathParam("name")String name); - - - @GET - @AddLinks - @LinkResource - @Path("resource-id/book/{name}") - ResourceIdBook getResourceIdBook(@PathParam("name")String name); - - - @GET - @AddLinks - @LinkResource - @Path("resource-ids/book/{namea}/{nameb}") - ResourceIdsBook getResourceIdsBook(@PathParam("namea")String namea, @PathParam("nameb")String nameb); - - @GET - @AddLinks - @LinkResource - @Path("resource-id-method/book/{name}") - ResourceIdMethodBook getResourceIdMethodBook(@PathParam("name")String name); - - - @GET - @AddLinks - @LinkResource - @Path("resource-ids-method/book/{namea}/{nameb}") - ResourceIdsMethodBook getResourceIdsMethodBook(@PathParam("namea")String namea, @PathParam("nameb")String nameb); + @GET + @AddLinks + @LinkResource + @Path("jpa-id/book/{name}") + JpaIdBook getJpaIdBook(@PathParam("name") String name); + + @GET + @AddLinks + @LinkResource + @Path("xml-id/book/{name}") + XmlIdBook getXmlIdBook(@PathParam("name")String name); + + + @GET + @AddLinks + @LinkResource + @Path("resource-id/book/{name}") + ResourceIdBook getResourceIdBook(@PathParam("name")String name); + + + @GET + @AddLinks + @LinkResource + @Path("resource-ids/book/{namea}/{nameb}") + ResourceIdsBook getResourceIdsBook(@PathParam("namea")String namea, @PathParam("nameb")String nameb); + + @GET + @AddLinks + @LinkResource + @Path("resource-id-method/book/{name}") + ResourceIdMethodBook getResourceIdMethodBook(@PathParam("name")String name); + + + @GET + @AddLinks + @LinkResource + @Path("resource-ids-method/book/{namea}/{nameb}") + ResourceIdsMethodBook getResourceIdsMethodBook(@PathParam("namea")String namea, @PathParam("nameb")String nameb); } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTestBean.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTestBean.java index 3bc46194264..4c10700fa06 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTestBean.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IDServiceTestBean.java @@ -2,29 +2,29 @@ public class IDServiceTestBean implements IDServiceTest { - public JpaIdBook getJpaIdBook(String name){ - return new JpaIdBook(name); - } - - public XmlIdBook getXmlIdBook(String name){ - return new XmlIdBook(name); - } - - public ResourceIdBook getResourceIdBook(String name){ - return new ResourceIdBook(name); - } - - public ResourceIdsBook getResourceIdsBook(String namea, String nameb){ - return new ResourceIdsBook(namea, nameb); - } - - public ResourceIdMethodBook getResourceIdMethodBook(String name) { - return new ResourceIdMethodBook(name); - } - - public ResourceIdsMethodBook getResourceIdsMethodBook(String namea, - String nameb) { - return new ResourceIdsMethodBook(namea, nameb); - } + public JpaIdBook getJpaIdBook(String name){ + return new JpaIdBook(name); + } + + public XmlIdBook getXmlIdBook(String name){ + return new XmlIdBook(name); + } + + public ResourceIdBook getResourceIdBook(String name){ + return new ResourceIdBook(name); + } + + public ResourceIdsBook getResourceIdsBook(String namea, String nameb){ + return new ResourceIdsBook(namea, nameb); + } + + public ResourceIdMethodBook getResourceIdMethodBook(String name) { + return new ResourceIdMethodBook(name); + } + + public ResourceIdsMethodBook getResourceIdsMethodBook(String namea, + String nameb) { + return new ResourceIdsMethodBook(namea, nameb); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IdBook.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IdBook.java index 4165bec8003..a7f58edf836 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IdBook.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/IdBook.java @@ -10,14 +10,14 @@ @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) public class IdBook { - @XmlElement - private RESTServiceDiscovery rest; + @XmlElement + private RESTServiceDiscovery rest; - public RESTServiceDiscovery getRest() { - return rest; - } + public RESTServiceDiscovery getRest() { + return rest; + } - public void setRest(RESTServiceDiscovery rest) { - this.rest = rest; - } + public void setRest(RESTServiceDiscovery rest) { + this.rest = rest; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/JpaIdBook.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/JpaIdBook.java index 90f1dadd4bf..58440640b37 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/JpaIdBook.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/JpaIdBook.java @@ -6,14 +6,14 @@ @XmlRootElement public class JpaIdBook extends IdBook{ - @Id - private String name; - - public JpaIdBook() { - } + @Id + private String name; - public JpaIdBook(String name) { - this.name = name; - } + public JpaIdBook() { + } + + public JpaIdBook(String name) { + this.name = name; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdBook.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdBook.java index 6f07acef20e..49100b41e50 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdBook.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdBook.java @@ -7,13 +7,13 @@ @XmlRootElement public class ResourceIdBook extends IdBook{ - @ResourceID - private String name; - public ResourceIdBook() { - } + @ResourceID + private String name; + public ResourceIdBook() { + } - public ResourceIdBook(String name) { - this.name = name; - } + public ResourceIdBook(String name) { + this.name = name; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdMethodBook.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdMethodBook.java index 904b61194ae..b69d4ec684b 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdMethodBook.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdMethodBook.java @@ -7,22 +7,22 @@ @XmlRootElement public class ResourceIdMethodBook extends IdBook{ - private String name; + private String name; - public ResourceIdMethodBook() { - } + public ResourceIdMethodBook() { + } - public ResourceIdMethodBook(String name) { - this.name = name; - } + public ResourceIdMethodBook(String name) { + this.name = name; + } - @ResourceID - public String getName() { - return name; - } + @ResourceID + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsBook.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsBook.java index 18b0e74be89..32d6a4ee0ba 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsBook.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsBook.java @@ -8,14 +8,14 @@ @ResourceIDs({"namea", "nameb"}) public class ResourceIdsBook extends IdBook{ - private String namea; - private String nameb; - public ResourceIdsBook() { - } + private String namea; + private String nameb; + public ResourceIdsBook() { + } - public ResourceIdsBook(String namea, String nameb) { - this.namea = namea; - this.nameb = nameb; - } + public ResourceIdsBook(String namea, String nameb) { + this.namea = namea; + this.nameb = nameb; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsMethodBook.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsMethodBook.java index 1d6c7bc988e..d4cef3c2732 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsMethodBook.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ResourceIdsMethodBook.java @@ -8,31 +8,31 @@ @ResourceIDs({"namea", "nameb"}) public class ResourceIdsMethodBook extends IdBook{ - private String _namea; - private String _nameb; - - public ResourceIdsMethodBook() { - } - - public ResourceIdsMethodBook(String namea, String nameb) { - this._namea = namea; - this._nameb = nameb; - } - - public String getNamea() { - return _namea; - } - - public void setNamea(String namea) { - this._namea = namea; - } - - public String getNameb() { - return _nameb; - } - - public void setNameb(String nameb) { - this._nameb = nameb; - } + private String _namea; + private String _nameb; + + public ResourceIdsMethodBook() { + } + + public ResourceIdsMethodBook(String namea, String nameb) { + this._namea = namea; + this._nameb = nameb; + } + + public String getNamea() { + return _namea; + } + + public void setNamea(String namea) { + this._namea = namea; + } + + public String getNameb() { + return _nameb; + } + + public void setNameb(String nameb) { + this._nameb = nameb; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ScrollableCollection.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ScrollableCollection.java index 82eeb696c75..e502835b1a8 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ScrollableCollection.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/ScrollableCollection.java @@ -19,89 +19,89 @@ @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) public class ScrollableCollection implements ResourceFacade { - @ResourceID - private String id; - @XmlAttribute - private int start; - @XmlAttribute - private int limit; - @XmlAttribute - private int totalRecords; - @XmlTransient - private String query; - @XmlElement - private List comments = new ArrayList(); - @XmlElement - private RESTServiceDiscovery rest; - - public ScrollableCollection() {} - - public ScrollableCollection(String id, int start, int limit, int totalRecords, - List comments, String query) { - this.id = id; - this.start = start; - this.limit = limit; - this.totalRecords = totalRecords; - this.comments.addAll(comments); - this.setQuery(query); - } - - public Class facadeFor() { - return Comment.class; - } - - public Map pathParameters() { - HashMap map = new HashMap(); - map.put("id", id); - return map; - } - - public int getStart() { - return start; - } - - public void setStart(int start) { - this.start = start; - } - - public int getLimit() { - return limit; - } - - public void setLimit(int limit) { - this.limit = limit; - } - - public int getTotalRecords() { - return totalRecords; - } - - public void setTotalRecords(int totalRecords) { - this.totalRecords = totalRecords; - } - - public RESTServiceDiscovery getRest() { - return rest; - } - - public void setRest(RESTServiceDiscovery rest) { - this.rest = rest; - } - - public List getComments() { - return comments; - } - - public void setComments(List comments) { - this.comments = comments; - } - - public String getQuery() { - return query; - } - - public void setQuery(String query) { - this.query = query; - } + @ResourceID + private String id; + @XmlAttribute + private int start; + @XmlAttribute + private int limit; + @XmlAttribute + private int totalRecords; + @XmlTransient + private String query; + @XmlElement + private List comments = new ArrayList(); + @XmlElement + private RESTServiceDiscovery rest; + + public ScrollableCollection() {} + + public ScrollableCollection(String id, int start, int limit, int totalRecords, + List comments, String query) { + this.id = id; + this.start = start; + this.limit = limit; + this.totalRecords = totalRecords; + this.comments.addAll(comments); + this.setQuery(query); + } + + public Class facadeFor() { + return Comment.class; + } + + public Map pathParameters() { + HashMap map = new HashMap(); + map.put("id", id); + return map; + } + + public int getStart() { + return start; + } + + public void setStart(int start) { + this.start = start; + } + + public int getLimit() { + return limit; + } + + public void setLimit(int limit) { + this.limit = limit; + } + + public int getTotalRecords() { + return totalRecords; + } + + public void setTotalRecords(int totalRecords) { + this.totalRecords = totalRecords; + } + + public RESTServiceDiscovery getRest() { + return rest; + } + + public void setRest(RESTServiceDiscovery rest) { + this.rest = rest; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + public String getQuery() { + return query; + } + + public void setQuery(String query) { + this.query = query; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamELProvider.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamELProvider.java index 1a2ad120a57..ffee5149064 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamELProvider.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamELProvider.java @@ -9,29 +9,29 @@ public class SeamELProvider implements ELProvider { - public ELContext getContext(final ELContext ctx) { - return new ELContext() { - - private SeamFunctionMapper functionMapper; - - @Override - public ELResolver getELResolver() { - return ctx.getELResolver(); - } - - @Override - public FunctionMapper getFunctionMapper() { - if (functionMapper == null) - functionMapper = new SeamFunctionMapper(ctx - .getFunctionMapper()); - return functionMapper; - } - - @Override - public VariableMapper getVariableMapper() { - return ctx.getVariableMapper(); - } - }; - } + public ELContext getContext(final ELContext ctx) { + return new ELContext() { + + private SeamFunctionMapper functionMapper; + + @Override + public ELResolver getELResolver() { + return ctx.getELResolver(); + } + + @Override + public FunctionMapper getFunctionMapper() { + if (functionMapper == null) + functionMapper = new SeamFunctionMapper(ctx + .getFunctionMapper()); + return functionMapper; + } + + @Override + public VariableMapper getVariableMapper() { + return ctx.getVariableMapper(); + } + }; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamFunctionMapper.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamFunctionMapper.java index cfdeb48259c..06c534beaf2 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamFunctionMapper.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SeamFunctionMapper.java @@ -53,10 +53,10 @@ else if (functionMapper != null) } } - @Override - public void mapFunction(String prefix, String localName, Method meth) { - super.mapFunction(prefix, localName, meth); - } + @Override + public void mapFunction(String prefix, String localName, Method meth) { + super.mapFunction(prefix, localName, meth); + } /* @Override public Method resolveFunction(String prefix, String localName, int paramCount) diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStore.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStore.java index a6d06d525bc..700d0dc48b5 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStore.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStore.java @@ -18,55 +18,55 @@ @Path("/") public class SecureBookStore { - - private Map books = new HashMap(); - - { - Book book = new Book("foo", "bar"); - book.addComment(0, "great book"); - book.addComment(1, "terrible book"); - books.put(book.getTitle(), book); - } - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Book.class, constraint = "${s:hasPermission(this, 'read')}") - @GET - @Path("books") - public Collection getBooks(){ - return books.values(); - } + private Map books = new HashMap(); - @Consumes({"application/xml", "application/json"}) - @LinkResource(constraint = "${s:hasPermission(this, 'add')}") - @POST - @Path("books") - public void addBook(Book book){ - books.put(book.getTitle(), book); - } + { + Book book = new Book("foo", "bar"); + book.addComment(0, "great book"); + book.addComment(1, "terrible book"); + books.put(book.getTitle(), book); + } - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(constraint = "${s:hasPermission(this, 'read')}") - @GET - @Path("book/{id}") - public Book getBook(@PathParam("id") String id){ - return books.get(id); - } + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Book.class, constraint = "${s:hasPermission(this, 'read')}") + @GET + @Path("books") + public Collection getBooks(){ + return books.values(); + } - @Consumes({"application/xml", "application/json"}) - @LinkResource(constraint = "${s:hasPermission(this, 'update')}") - @PUT - @Path("book/{id}") - public void updateBook(@PathParam("id") String id, Book book){ - books.put(id, book); - } + @Consumes({"application/xml", "application/json"}) + @LinkResource(constraint = "${s:hasPermission(this, 'add')}") + @POST + @Path("books") + public void addBook(Book book){ + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(constraint = "${s:hasPermission(this, 'read')}") + @GET + @Path("book/{id}") + public Book getBook(@PathParam("id") String id){ + return books.get(id); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource(constraint = "${s:hasPermission(this, 'update')}") + @PUT + @Path("book/{id}") + public void updateBook(@PathParam("id") String id, Book book){ + books.put(id, book); + } + + @LinkResource(value = Book.class, constraint = "${s:hasPermission(this, 'delete')}") + @DELETE + @Path("book/{id}") + public void deleteBook(@PathParam("id") String id){ + books.remove(id); + } - @LinkResource(value = Book.class, constraint = "${s:hasPermission(this, 'delete')}") - @DELETE - @Path("book/{id}") - public void deleteBook(@PathParam("id") String id){ - books.remove(id); - } - } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStoreMinimal.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStoreMinimal.java index 5a4420481da..0e165c8a414 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStoreMinimal.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecureBookStoreMinimal.java @@ -18,58 +18,58 @@ @Path("/") public class SecureBookStoreMinimal { - - private Map books = new HashMap(); - - { - Book book = new Book("foo", "bar"); - book.addComment(0, "great book"); - book.addComment(1, "terrible book"); - books.put(book.getTitle(), book); - } - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Book.class) - @GET - @Path("books") - public Collection getBooks(){ - return books.values(); - } + private Map books = new HashMap(); - @Consumes({"application/xml", "application/json"}) - @LinkResource() - @POST - @Path("books") - @RolesAllowed({"admin", "power-user"}) - public void addBook(Book book){ - books.put(book.getTitle(), book); - } + { + Book book = new Book("foo", "bar"); + book.addComment(0, "great book"); + book.addComment(1, "terrible book"); + books.put(book.getTitle(), book); + } - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource() - @GET - @Path("book/{id}") - public Book getBook(@PathParam("id") String id){ - return books.get(id); - } + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Book.class) + @GET + @Path("books") + public Collection getBooks(){ + return books.values(); + } - @Consumes({"application/xml", "application/json"}) - @LinkResource() - @PUT - @Path("book/{id}") - @RolesAllowed({"admin", "power-user"}) - public void updateBook(@PathParam("id") String id, Book book){ - books.put(id, book); - } + @Consumes({"application/xml", "application/json"}) + @LinkResource() + @POST + @Path("books") + @RolesAllowed({"admin", "power-user"}) + public void addBook(Book book){ + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource() + @GET + @Path("book/{id}") + public Book getBook(@PathParam("id") String id){ + return books.get(id); + } + + @Consumes({"application/xml", "application/json"}) + @LinkResource() + @PUT + @Path("book/{id}") + @RolesAllowed({"admin", "power-user"}) + public void updateBook(@PathParam("id") String id, Book book){ + books.put(id, book); + } + + @LinkResource(value = Book.class) + @DELETE + @Path("book/{id}") + @RolesAllowed({"admin"}) + public void deleteBook(@PathParam("id") String id){ + books.remove(id); + } - @LinkResource(value = Book.class) - @DELETE - @Path("book/{id}") - @RolesAllowed({"admin"}) - public void deleteBook(@PathParam("id") String id){ - books.remove(id); - } - } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecurityFunctions.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecurityFunctions.java index 353c0d2bb40..1cd7a924a04 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecurityFunctions.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/SecurityFunctions.java @@ -5,26 +5,26 @@ import javax.ws.rs.core.SecurityContext; public class SecurityFunctions { - public static boolean hasPermission(Object target, String permission){ - SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class); - if(context.isUserInRole("admin")) - return true; - if(context.isUserInRole("power-user")){ - return allow(permission, "add", "update", "read"); - } - return allow(permission, "read"); - } + public static boolean hasPermission(Object target, String permission){ + SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class); + if(context.isUserInRole("admin")) + return true; + if(context.isUserInRole("power-user")){ + return allow(permission, "add", "update", "read"); + } + return allow(permission, "read"); + } - private static boolean allow(String permission, String... allowedPermissions) { - for (String allowedPermission : allowedPermissions) { - if(permission.equals(allowedPermission)) - return true; - } - return false; - } + private static boolean allow(String permission, String... allowedPermissions) { + for (String allowedPermission : allowedPermissions) { + if(permission.equals(allowedPermission)) + return true; + } + return false; + } - public static boolean hasRole(String role){ - SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class); - return context.isUserInRole(role); - } + public static boolean hasRole(String role){ + SecurityContext context = ResteasyProviderFactory.getContextData(SecurityContext.class); + return context.isUserInRole(role); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestFacadeLinks.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestFacadeLinks.java index 27b5e838a77..e9c0e60aee0 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestFacadeLinks.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestFacadeLinks.java @@ -50,104 +50,104 @@ public static void afterClass() throws Exception dispatcher = null; } - @Parameters - public static List[]> getParameters(){ - return Arrays.asList(new Class[]{BookStore.class}, new Class[]{BookStoreMinimal.class}); - } + @Parameters + public static List[]> getParameters(){ + return Arrays.asList(new Class[]{BookStore.class}, new Class[]{BookStoreMinimal.class}); + } + + private Class resourceType; + private String url; + private BookStoreService client; + private HttpClient httpClient; - private Class resourceType; - private String url; - private BookStoreService client; - private HttpClient httpClient; - - public TestFacadeLinks(Class resourceType){ - this.resourceType = resourceType; - } - - @Before - public void before(){ - POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); - dispatcher.getRegistry().addResourceFactory(noDefaults); - httpClient = new DefaultHttpClient(); - ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); - url = generateBaseUrl(); - client = ProxyFactory.create(BookStoreService.class, url, - executor); - } + public TestFacadeLinks(Class resourceType){ + this.resourceType = resourceType; + } - @After - public void after(){ - // TJWS does not support chunk encodings well so I need to kill kept - // alive connections - httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); - dispatcher.getRegistry().removeRegistrations(resourceType); - } - - @Test - public void testLinks() throws Exception - { - ScrollableCollection comments = client.getScrollableCommentsXML("foo", "book"); - checkCommentsLinks(url, comments); - comments = client.getScrollableCommentsJSON("foo", "book"); - checkCommentsLinks(url, comments); - } + @Before + public void before(){ + POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); + dispatcher.getRegistry().addResourceFactory(noDefaults); + httpClient = new DefaultHttpClient(); + ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); + url = generateBaseUrl(); + client = ProxyFactory.create(BookStoreService.class, url, + executor); + } - private void checkCommentsLinks(String url, ScrollableCollection comments) { - Assert.assertNotNull(comments); - RESTServiceDiscovery links = comments.getRest(); - Assert.assertNotNull(links); - Assert.assertEquals(5, links.size()); - // list - AtomLink atomLink = links.getLinkForRel("list"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); - // add - atomLink = links.getLinkForRel("add"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); - // comment collection - atomLink = links.getLinkForRel("collection"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); - // next - atomLink = links.getLinkForRel("next"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment-collection;query=book?start=1&limit=1", atomLink.getHref()); - // home - atomLink = links.getLinkForRel("home"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/", atomLink.getHref()); - } + @After + public void after(){ + // TJWS does not support chunk encodings well so I need to kill kept + // alive connections + httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); + dispatcher.getRegistry().removeRegistrations(resourceType); + } - private void checkCommentLinks(String url, Comment comment) { - Assert.assertNotNull(comment); - Assert.assertEquals(0, comment.getId()); - RESTServiceDiscovery links = comment.getRest(); - Assert.assertNotNull(links); - Assert.assertEquals(6, links.size()); - // self - AtomLink atomLink = links.getLinkForRel("self"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); - // update - atomLink = links.getLinkForRel("update"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); - // remove - atomLink = links.getLinkForRel("remove"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); - // list - atomLink = links.getLinkForRel("list"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); - // add - atomLink = links.getLinkForRel("add"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); - // collection - atomLink = links.getLinkForRel("collection"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); - } -} \ No newline at end of file + @Test + public void testLinks() throws Exception + { + ScrollableCollection comments = client.getScrollableCommentsXML("foo", "book"); + checkCommentsLinks(url, comments); + comments = client.getScrollableCommentsJSON("foo", "book"); + checkCommentsLinks(url, comments); + } + + private void checkCommentsLinks(String url, ScrollableCollection comments) { + Assert.assertNotNull(comments); + RESTServiceDiscovery links = comments.getRest(); + Assert.assertNotNull(links); + Assert.assertEquals(5, links.size()); + // list + AtomLink atomLink = links.getLinkForRel("list"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); + // add + atomLink = links.getLinkForRel("add"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); + // comment collection + atomLink = links.getLinkForRel("collection"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); + // next + atomLink = links.getLinkForRel("next"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment-collection;query=book?start=1&limit=1", atomLink.getHref()); + // home + atomLink = links.getLinkForRel("home"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/", atomLink.getHref()); + } + + private void checkCommentLinks(String url, Comment comment) { + Assert.assertNotNull(comment); + Assert.assertEquals(0, comment.getId()); + RESTServiceDiscovery links = comment.getRest(); + Assert.assertNotNull(links); + Assert.assertEquals(6, links.size()); + // self + AtomLink atomLink = links.getLinkForRel("self"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); + // update + atomLink = links.getLinkForRel("update"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); + // remove + atomLink = links.getLinkForRel("remove"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); + // list + atomLink = links.getLinkForRel("list"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); + // add + atomLink = links.getLinkForRel("add"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); + // collection + atomLink = links.getLinkForRel("collection"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); + } +} diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinkIds.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinkIds.java index 8d06ba4ad4f..6b27e58c35c 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinkIds.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinkIds.java @@ -52,67 +52,67 @@ public static void afterClass() throws Exception dispatcher = null; } - private static Class resourceType; - private static String url; - private static IDServiceTest client; - private static HttpClient httpClient; - - @After - public void after(){ - // TJWS does not support chunk encodings well so I need to kill kept - // alive connections - httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); - } - - @Test - public void testResourceId() throws Exception - { - IdBook book = client.getResourceIdBook("foo"); - checkBook(book, "/resource-id/book/foo"); - } - - @Test - public void testResourceIds() throws Exception - { - IdBook book = client.getResourceIdsBook("foo", "bar"); - checkBook(book, "/resource-ids/book/foo/bar"); - } - - @Test - public void testResourceIdMethod() throws Exception - { - IdBook book = client.getResourceIdMethodBook("foo"); - checkBook(book, "/resource-id-method/book/foo"); - } - - @Test - public void testResourceIdsMethod() throws Exception - { - IdBook book = client.getResourceIdsMethodBook("foo", "bar"); - checkBook(book, "/resource-ids-method/book/foo/bar"); - } - - @Test - public void testXmlId() throws Exception - { - IdBook book = client.getXmlIdBook("foo"); - checkBook(book, "/xml-id/book/foo"); - } - - @Test - public void testJpaId() throws Exception - { - IdBook book = client.getJpaIdBook("foo"); - checkBook(book, "/jpa-id/book/foo"); - } - - private void checkBook(IdBook book, String relativeUrl) { - Assert.assertNotNull(book); - RESTServiceDiscovery links = book.getRest(); - Assert.assertNotNull(links); - Assert.assertEquals(1, links.size()); - AtomLink link = links.get(0); - Assert.assertEquals("self", link.getRel()); - Assert.assertEquals(url + relativeUrl, link.getHref()); - } + private static Class resourceType; + private static String url; + private static IDServiceTest client; + private static HttpClient httpClient; + + @After + public void after(){ + // TJWS does not support chunk encodings well so I need to kill kept + // alive connections + httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); + } + + @Test + public void testResourceId() throws Exception + { + IdBook book = client.getResourceIdBook("foo"); + checkBook(book, "/resource-id/book/foo"); + } + + @Test + public void testResourceIds() throws Exception + { + IdBook book = client.getResourceIdsBook("foo", "bar"); + checkBook(book, "/resource-ids/book/foo/bar"); + } + + @Test + public void testResourceIdMethod() throws Exception + { + IdBook book = client.getResourceIdMethodBook("foo"); + checkBook(book, "/resource-id-method/book/foo"); + } + + @Test + public void testResourceIdsMethod() throws Exception + { + IdBook book = client.getResourceIdsMethodBook("foo", "bar"); + checkBook(book, "/resource-ids-method/book/foo/bar"); + } + + @Test + public void testXmlId() throws Exception + { + IdBook book = client.getXmlIdBook("foo"); + checkBook(book, "/xml-id/book/foo"); + } + + @Test + public void testJpaId() throws Exception + { + IdBook book = client.getJpaIdBook("foo"); + checkBook(book, "/jpa-id/book/foo"); + } + + private void checkBook(IdBook book, String relativeUrl) { + Assert.assertNotNull(book); + RESTServiceDiscovery links = book.getRest(); + Assert.assertNotNull(links); + Assert.assertEquals(1, links.size()); + AtomLink link = links.get(0); + Assert.assertEquals("self", link.getRel()); + Assert.assertEquals(url + relativeUrl, link.getHref()); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinks.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinks.java index fb18e60e2f4..281e649e288 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinks.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestLinks.java @@ -50,127 +50,127 @@ public static void afterClass() throws Exception dispatcher = null; } - @Parameters - public static List[]> getParameters(){ - return Arrays.asList(new Class[]{BookStore.class}, new Class[]{BookStoreMinimal.class}); - } + @Parameters + public static List[]> getParameters(){ + return Arrays.asList(new Class[]{BookStore.class}, new Class[]{BookStoreMinimal.class}); + } - private Class resourceType; - private String url; - private BookStoreService client; - private HttpClient httpClient; - - public TestLinks(Class resourceType){ - this.resourceType = resourceType; - } - - @Before - public void before(){ - POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); - dispatcher.getRegistry().addResourceFactory(noDefaults); - httpClient = new DefaultHttpClient(); - ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); - url = generateBaseUrl(); - client = ProxyFactory.create(BookStoreService.class, url, - executor); - } + private Class resourceType; + private String url; + private BookStoreService client; + private HttpClient httpClient; - @After - public void after(){ - // TJWS does not support chunk encodings well so I need to kill kept - // alive connections - httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); - dispatcher.getRegistry().removeRegistrations(resourceType); - } - - @Test - public void testLinks() throws Exception - { - Book book = client.getBookXML("foo"); - checkBookLinks1(url, book); - book = client.getBookJSON("foo"); - checkBookLinks1(url, book); - } + public TestLinks(Class resourceType){ + this.resourceType = resourceType; + } - @Test - public void testComments() throws Exception - { - List comments = client.getBookCommentsXML("foo"); - Assert.assertNotNull(comments); - Assert.assertFalse(comments.isEmpty()); - checkCommentLinks(url, comments.get(0)); - comments = client.getBookCommentsJSON("foo"); - Assert.assertNotNull(comments); - Assert.assertFalse(comments.isEmpty()); - checkCommentLinks(url, comments.get(0)); - } + @Before + public void before(){ + POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); + dispatcher.getRegistry().addResourceFactory(noDefaults); + httpClient = new DefaultHttpClient(); + ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); + url = generateBaseUrl(); + client = ProxyFactory.create(BookStoreService.class, url, + executor); + } - private void checkBookLinks1(String url, Book book) { - Assert.assertNotNull(book); - Assert.assertEquals("foo", book.getTitle()); - Assert.assertEquals("bar", book.getAuthor()); - RESTServiceDiscovery links = book.getRest(); - Assert.assertNotNull(links); - Assert.assertEquals(7, links.size()); - // self - AtomLink atomLink = links.getLinkForRel("self"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo", atomLink.getHref()); - // update - atomLink = links.getLinkForRel("update"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo", atomLink.getHref()); - // remove - atomLink = links.getLinkForRel("remove"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo", atomLink.getHref()); - // list - atomLink = links.getLinkForRel("list"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/books", atomLink.getHref()); - // add - atomLink = links.getLinkForRel("add"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/books", atomLink.getHref()); - // comments - atomLink = links.getLinkForRel("comments"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); - // comment collection - atomLink = links.getLinkForRel("comment-collection"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); - } + @After + public void after(){ + // TJWS does not support chunk encodings well so I need to kill kept + // alive connections + httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); + dispatcher.getRegistry().removeRegistrations(resourceType); + } + + @Test + public void testLinks() throws Exception + { + Book book = client.getBookXML("foo"); + checkBookLinks1(url, book); + book = client.getBookJSON("foo"); + checkBookLinks1(url, book); + } - private void checkCommentLinks(String url, Comment comment) { - Assert.assertNotNull(comment); - Assert.assertEquals(0, comment.getId()); - RESTServiceDiscovery links = comment.getRest(); - Assert.assertNotNull(links); - Assert.assertEquals(6, links.size()); - // self - AtomLink atomLink = links.getLinkForRel("self"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); - // update - atomLink = links.getLinkForRel("update"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); - // remove - atomLink = links.getLinkForRel("remove"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); - // list - atomLink = links.getLinkForRel("list"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); - // add - atomLink = links.getLinkForRel("add"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); - // collection - atomLink = links.getLinkForRel("collection"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); - } -} \ No newline at end of file + @Test + public void testComments() throws Exception + { + List comments = client.getBookCommentsXML("foo"); + Assert.assertNotNull(comments); + Assert.assertFalse(comments.isEmpty()); + checkCommentLinks(url, comments.get(0)); + comments = client.getBookCommentsJSON("foo"); + Assert.assertNotNull(comments); + Assert.assertFalse(comments.isEmpty()); + checkCommentLinks(url, comments.get(0)); + } + + private void checkBookLinks1(String url, Book book) { + Assert.assertNotNull(book); + Assert.assertEquals("foo", book.getTitle()); + Assert.assertEquals("bar", book.getAuthor()); + RESTServiceDiscovery links = book.getRest(); + Assert.assertNotNull(links); + Assert.assertEquals(7, links.size()); + // self + AtomLink atomLink = links.getLinkForRel("self"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo", atomLink.getHref()); + // update + atomLink = links.getLinkForRel("update"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo", atomLink.getHref()); + // remove + atomLink = links.getLinkForRel("remove"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo", atomLink.getHref()); + // list + atomLink = links.getLinkForRel("list"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/books", atomLink.getHref()); + // add + atomLink = links.getLinkForRel("add"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/books", atomLink.getHref()); + // comments + atomLink = links.getLinkForRel("comments"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); + // comment collection + atomLink = links.getLinkForRel("comment-collection"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); + } + + private void checkCommentLinks(String url, Comment comment) { + Assert.assertNotNull(comment); + Assert.assertEquals(0, comment.getId()); + RESTServiceDiscovery links = comment.getRest(); + Assert.assertNotNull(links); + Assert.assertEquals(6, links.size()); + // self + AtomLink atomLink = links.getLinkForRel("self"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); + // update + atomLink = links.getLinkForRel("update"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); + // remove + atomLink = links.getLinkForRel("remove"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment/0", atomLink.getHref()); + // list + atomLink = links.getLinkForRel("list"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); + // add + atomLink = links.getLinkForRel("add"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comments", atomLink.getHref()); + // collection + atomLink = links.getLinkForRel("collection"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo/comment-collection", atomLink.getHref()); + } +} diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestSecureLinks.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestSecureLinks.java index 8b2701e7d38..ed76aef3620 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestSecureLinks.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/TestSecureLinks.java @@ -74,94 +74,94 @@ public static void afterClass() throws Exception dispatcher = null; } - @Parameters - public static List[]> getParameters(){ - return Arrays.asList(new Class[]{SecureBookStore.class}, new Class[]{SecureBookStoreMinimal.class}); - } - - private Class resourceType; - private String url; - private BookStoreService client; - private DefaultHttpClient httpClient; - public TestSecureLinks(Class resourceType){ - this.resourceType = resourceType; - } - - @Before - public void before(){ - POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); - dispatcher.getRegistry().addResourceFactory(noDefaults); - url = generateBaseUrl(); - - // Configure HttpClient to authenticate preemptively - // by prepopulating the authentication data cache. - // 1. Create AuthCache instance - AuthCache authCache = new BasicAuthCache(); - // 2. Generate BASIC scheme object and add it to the local auth cache - BasicScheme basicAuth = new BasicScheme(); - authCache.put(getHttpHost(url), basicAuth); - // 3. Add AuthCache to the execution context - BasicHttpContext localContext = new BasicHttpContext(); - localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); - - httpClient = new DefaultHttpClient(); - ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext); - client = ProxyFactory.create(BookStoreService.class, url, executor); - } - - @After - public void after(){ - dispatcher.getRegistry().removeRegistrations(resourceType); - } - - @Test - public void testSecureLinksAdmin() throws Exception - { - CredentialsProvider cp = httpClient.getCredentialsProvider(); - cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "asd")); - Book book = client.getBookXML("foo"); - checkBookLinks1(url, book, "add", "update", "list", "self", "remove"); - } - - @Test - public void testSecureLinksPowerUser() throws Exception - { - CredentialsProvider cp = httpClient.getCredentialsProvider(); - cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("power-user", "asd")); - Book book = client.getBookXML("foo"); - checkBookLinks1(url, book, "add", "update", "list", "self"); - } - - @Test - public void testSecureLinksUser() throws Exception - { - CredentialsProvider cp = httpClient.getCredentialsProvider(); - cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "asd")); - Book book = client.getBookXML("foo"); - checkBookLinks1(url, book, "list", "self"); - } - - private void checkBookLinks1(String url, Book book, String... expectedLinks) { - Assert.assertNotNull(book); - Assert.assertEquals("foo", book.getTitle()); - Assert.assertEquals("bar", book.getAuthor()); - RESTServiceDiscovery links = book.getRest(); - Assert.assertNotNull(links); - Assert.assertEquals(expectedLinks.length, links.size()); - for (String expectedLink : expectedLinks) { - Assert.assertNotNull(links.getLinkForRel(expectedLink)); - } - } - - private HttpHost getHttpHost(String url) - { - int i1 = url.indexOf(':'); - String scheme = url.substring(0, i1); - int i2 = url.indexOf(':', i1 + 1); - String host = url.substring(i1 + 3, i2); - int i3 = url.indexOf('/', i2 + 1); - String port = i3 == -1 ? url.substring(i2 + 1) - : url.substring(i2 + 1, i3); - return new HttpHost(host, Integer.valueOf(port), scheme); - } + @Parameters + public static List[]> getParameters(){ + return Arrays.asList(new Class[]{SecureBookStore.class}, new Class[]{SecureBookStoreMinimal.class}); + } + + private Class resourceType; + private String url; + private BookStoreService client; + private DefaultHttpClient httpClient; + public TestSecureLinks(Class resourceType){ + this.resourceType = resourceType; + } + + @Before + public void before(){ + POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); + dispatcher.getRegistry().addResourceFactory(noDefaults); + url = generateBaseUrl(); + + // Configure HttpClient to authenticate preemptively + // by prepopulating the authentication data cache. + // 1. Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + // 2. Generate BASIC scheme object and add it to the local auth cache + BasicScheme basicAuth = new BasicScheme(); + authCache.put(getHttpHost(url), basicAuth); + // 3. Add AuthCache to the execution context + BasicHttpContext localContext = new BasicHttpContext(); + localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); + + httpClient = new DefaultHttpClient(); + ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext); + client = ProxyFactory.create(BookStoreService.class, url, executor); + } + + @After + public void after(){ + dispatcher.getRegistry().removeRegistrations(resourceType); + } + + @Test + public void testSecureLinksAdmin() throws Exception + { + CredentialsProvider cp = httpClient.getCredentialsProvider(); + cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "asd")); + Book book = client.getBookXML("foo"); + checkBookLinks1(url, book, "add", "update", "list", "self", "remove"); + } + + @Test + public void testSecureLinksPowerUser() throws Exception + { + CredentialsProvider cp = httpClient.getCredentialsProvider(); + cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("power-user", "asd")); + Book book = client.getBookXML("foo"); + checkBookLinks1(url, book, "add", "update", "list", "self"); + } + + @Test + public void testSecureLinksUser() throws Exception + { + CredentialsProvider cp = httpClient.getCredentialsProvider(); + cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "asd")); + Book book = client.getBookXML("foo"); + checkBookLinks1(url, book, "list", "self"); + } + + private void checkBookLinks1(String url, Book book, String... expectedLinks) { + Assert.assertNotNull(book); + Assert.assertEquals("foo", book.getTitle()); + Assert.assertEquals("bar", book.getAuthor()); + RESTServiceDiscovery links = book.getRest(); + Assert.assertNotNull(links); + Assert.assertEquals(expectedLinks.length, links.size()); + for (String expectedLink : expectedLinks) { + Assert.assertNotNull(links.getLinkForRel(expectedLink)); + } + } + + private HttpHost getHttpHost(String url) + { + int i1 = url.indexOf(':'); + String scheme = url.substring(0, i1); + int i2 = url.indexOf(':', i1 + 1); + String host = url.substring(i1 + 3, i2); + int i3 = url.indexOf('/', i2 + 1); + String port = i3 == -1 ? url.substring(i2 + 1) + : url.substring(i2 + 1, i3); + return new HttpHost(host, Integer.valueOf(port), scheme); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/XmlIdBook.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/XmlIdBook.java index 07552f08bc5..357aee3cea8 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/XmlIdBook.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/XmlIdBook.java @@ -6,13 +6,13 @@ @XmlRootElement public class XmlIdBook extends IdBook { - @XmlID - private String name; - public XmlIdBook() { - } + @XmlID + private String name; + public XmlIdBook() { + } - public XmlIdBook(String name) { - this.name = name; - } + public XmlIdBook(String name) { + this.name = name; + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreInvalidEL.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreInvalidEL.java index e9fdec2cd01..571dbf93e35 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreInvalidEL.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreInvalidEL.java @@ -13,22 +13,22 @@ @Path("/") public class BookStoreInvalidEL { - - private Map books = new HashMap(); - - { - Book book = new Book("foo", "bar"); - book.addComment(0, "great book"); - book.addComment(1, "terrible book"); - books.put(book.getTitle(), book); - } - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Book.class, pathParameters = "${tile}") - @GET - @Path("book/{id}") - public Book getBook(@PathParam("id") String id){ - return books.get(id); - } + private Map books = new HashMap(); + + { + Book book = new Book("foo", "bar"); + book.addComment(0, "great book"); + book.addComment(1, "terrible book"); + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Book.class, pathParameters = "${tile}") + @GET + @Path("book/{id}") + public Book getBook(@PathParam("id") String id){ + return books.get(id); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreNoPackage.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreNoPackage.java index 6d6d4bcb17c..6e94f23d707 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreNoPackage.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreNoPackage.java @@ -13,22 +13,22 @@ @Path("/") public class BookStoreNoPackage { - - private Map books = new HashMap(); - - { - Book book = new Book("foo", "bar"); - book.addComment(0, "great book"); - book.addComment(1, "terrible book"); - books.put(book.getTitle(), book); - } - @Produces({"application/xml", "application/json"}) - @AddLinks - @LinkResource(value = Book.class, pathParameters = "${title}") - @GET - @Path("book/{id}") - public Book getBook(@PathParam("id") String id){ - return books.get(id); - } + private Map books = new HashMap(); + + { + Book book = new Book("foo", "bar"); + book.addComment(0, "great book"); + book.addComment(1, "terrible book"); + books.put(book.getTitle(), book); + } + + @Produces({"application/xml", "application/json"}) + @AddLinks + @LinkResource(value = Book.class, pathParameters = "${title}") + @GET + @Path("book/{id}") + public Book getBook(@PathParam("id") String id){ + return books.get(id); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreService.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreService.java index 5559df99498..9f29fbf46d2 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreService.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/BookStoreService.java @@ -9,14 +9,14 @@ @Path("/") public interface BookStoreService { - - @Produces({"application/xml"}) - @Path("book/{id}") - @GET - Book getBookXML(@PathParam("id") String id); - @Produces({"application/json"}) - @Path("book/{id}") - @GET - Book getBookJSON(@PathParam("id") String id); + @Produces({"application/xml"}) + @Path("book/{id}") + @GET + Book getBookXML(@PathParam("id") String id); + + @Produces({"application/json"}) + @Path("book/{id}") + @GET + Book getBookJSON(@PathParam("id") String id); } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksInvalidEL.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksInvalidEL.java index f8e96a06ace..293ea63a995 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksInvalidEL.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksInvalidEL.java @@ -53,63 +53,63 @@ public static void afterClass() throws Exception dispatcher = null; } - @Parameters - public static List[]> getParameters(){ - List[]> classes = new ArrayList[]>(); - classes.add(new Class[]{BookStoreInvalidEL.class}); - return classes; - } + @Parameters + public static List[]> getParameters(){ + List[]> classes = new ArrayList[]>(); + classes.add(new Class[]{BookStoreInvalidEL.class}); + return classes; + } + + private Class resourceType; + private String url; + private BookStoreService client; + private HttpClient httpClient; + + public TestLinksInvalidEL(Class resourceType){ + this.resourceType = resourceType; + } - private Class resourceType; - private String url; - private BookStoreService client; - private HttpClient httpClient; - - public TestLinksInvalidEL(Class resourceType){ - this.resourceType = resourceType; - } - - @Before - public void before(){ - POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); - dispatcher.getRegistry().addResourceFactory(noDefaults); - httpClient = new DefaultHttpClient(); - ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); - url = generateBaseUrl(); - client = ProxyFactory.create(BookStoreService.class, url, - executor); - } + @Before + public void before(){ + POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); + dispatcher.getRegistry().addResourceFactory(noDefaults); + httpClient = new DefaultHttpClient(); + ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); + url = generateBaseUrl(); + client = ProxyFactory.create(BookStoreService.class, url, + executor); + } - @After - public void after(){ - // TJWS does not support chunk encodings well so I need to kill kept - // alive connections - httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); - dispatcher.getRegistry().removeRegistrations(resourceType); - } - - @SuppressWarnings("unchecked") - @Test - public void testELWorksWithoutPackageXML() throws Exception - { - try{ - client.getBookXML("foo"); - Assert.fail("This should have caused a 500"); - }catch(ClientResponseFailure x){ - LOG.error("Failure is "+x.getResponse().getEntity(String.class)); - Assert.assertEquals(500, x.getResponse().getStatus()); - } - } - @SuppressWarnings("unchecked") - @Test - public void testELWorksWithoutPackageJSON() throws Exception - { - try{ - client.getBookJSON("foo"); - Assert.fail("This should have caused a 500"); - }catch(ClientResponseFailure x){ - LOG.error("Failure is "+x.getResponse().getEntity(String.class)); - Assert.assertEquals(500, x.getResponse().getStatus()); - } - } + @After + public void after(){ + // TJWS does not support chunk encodings well so I need to kill kept + // alive connections + httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); + dispatcher.getRegistry().removeRegistrations(resourceType); + } + + @SuppressWarnings("unchecked") + @Test + public void testELWorksWithoutPackageXML() throws Exception + { + try{ + client.getBookXML("foo"); + Assert.fail("This should have caused a 500"); + }catch(ClientResponseFailure x){ + LOG.error("Failure is "+x.getResponse().getEntity(String.class)); + Assert.assertEquals(500, x.getResponse().getStatus()); + } + } + @SuppressWarnings("unchecked") + @Test + public void testELWorksWithoutPackageJSON() throws Exception + { + try{ + client.getBookJSON("foo"); + Assert.fail("This should have caused a 500"); + }catch(ClientResponseFailure x){ + LOG.error("Failure is "+x.getResponse().getEntity(String.class)); + Assert.assertEquals(500, x.getResponse().getStatus()); + } + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksNoPackage.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksNoPackage.java index 1b73abf5ec2..22cccca0a37 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksNoPackage.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/el/TestLinksNoPackage.java @@ -53,60 +53,60 @@ public static void afterClass() throws Exception dispatcher = null; } - @Parameters - public static List[]> getParameters(){ - List[]> classes = new ArrayList[]>(); - classes.add(new Class[]{BookStoreNoPackage.class}); - return classes; - } + @Parameters + public static List[]> getParameters(){ + List[]> classes = new ArrayList[]>(); + classes.add(new Class[]{BookStoreNoPackage.class}); + return classes; + } + + private Class resourceType; + private String url; + private BookStoreService client; + private HttpClient httpClient; + + public TestLinksNoPackage(Class resourceType){ + this.resourceType = resourceType; + } + + @Before + public void before(){ + POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); + dispatcher.getRegistry().addResourceFactory(noDefaults); + httpClient = new DefaultHttpClient(); + ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); + url = generateBaseUrl(); + client = ProxyFactory.create(BookStoreService.class, url, + executor); + } - private Class resourceType; - private String url; - private BookStoreService client; - private HttpClient httpClient; - - public TestLinksNoPackage(Class resourceType){ - this.resourceType = resourceType; - } - - @Before - public void before(){ - POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType); - dispatcher.getRegistry().addResourceFactory(noDefaults); - httpClient = new DefaultHttpClient(); - ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient); - url = generateBaseUrl(); - client = ProxyFactory.create(BookStoreService.class, url, - executor); - } + @After + public void after(){ + // TJWS does not support chunk encodings well so I need to kill kept + // alive connections + httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); + dispatcher.getRegistry().removeRegistrations(resourceType); + } - @After - public void after(){ - // TJWS does not support chunk encodings well so I need to kill kept - // alive connections - httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); - dispatcher.getRegistry().removeRegistrations(resourceType); - } - - @Test - public void testELWorksWithoutPackage() throws Exception - { - Book book = client.getBookXML("foo"); - checkBookLinks1(url, book); - book = client.getBookJSON("foo"); - checkBookLinks1(url, book); - } + @Test + public void testELWorksWithoutPackage() throws Exception + { + Book book = client.getBookXML("foo"); + checkBookLinks1(url, book); + book = client.getBookJSON("foo"); + checkBookLinks1(url, book); + } - private void checkBookLinks1(String url, Book book) { - Assert.assertNotNull(book); - Assert.assertEquals("foo", book.getTitle()); - Assert.assertEquals("bar", book.getAuthor()); - RESTServiceDiscovery links = book.getRest(); - Assert.assertNotNull(links); - Assert.assertEquals(1, links.size()); - // self - AtomLink atomLink = links.getLinkForRel("self"); - Assert.assertNotNull(atomLink); - Assert.assertEquals(url+"/book/foo", atomLink.getHref()); - } + private void checkBookLinks1(String url, Book book) { + Assert.assertNotNull(book); + Assert.assertEquals("foo", book.getTitle()); + Assert.assertEquals("bar", book.getAuthor()); + RESTServiceDiscovery links = book.getRest(); + Assert.assertNotNull(links); + Assert.assertEquals(1, links.size()); + // self + AtomLink atomLink = links.getLinkForRel("self"); + Assert.assertNotNull(atomLink); + Assert.assertEquals(url+"/book/foo", atomLink.getHref()); + } } diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/package-info.java b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/package-info.java index 971221abee9..ad25d53c15a 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/links/test/package-info.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/links/test/package-info.java @@ -1,4 +1,4 @@ @LinkELProvider(SeamELProvider.class) package org.jboss.resteasy.links.test; -import org.jboss.resteasy.links.LinkELProvider; \ No newline at end of file +import org.jboss.resteasy.links.LinkELProvider; diff --git a/resteasy-links/src/test/java/org/jboss/resteasy/test/i18n/TestMessagesParent.java b/resteasy-links/src/test/java/org/jboss/resteasy/test/i18n/TestMessagesParent.java index 1762e99e90e..78c4c3de457 100644 --- a/resteasy-links/src/test/java/org/jboss/resteasy/test/i18n/TestMessagesParent.java +++ b/resteasy-links/src/test/java/org/jboss/resteasy/test/i18n/TestMessagesParent.java @@ -84,4 +84,4 @@ protected String replacePositionalSpecifiers(String s) abstract protected int getExpectedNumberOfMethods(); abstract protected Locale getLocale(); -} \ No newline at end of file +} diff --git a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableProvider.java b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableProvider.java index 404471a2683..7ed5008f4f8 100644 --- a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableProvider.java +++ b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableProvider.java @@ -10,14 +10,14 @@ import rx.plugins.RxJavaHooks; /** - * @deprecated: - * - * "RxJava 1.x is now officially end-of-life (EOL). No further developments, - * bugfixes, enhancements, javadoc changes or maintenance will be provided by - * this project after version 1.3.8." - From https://github.com/ReactiveX/RxJava/releases - * - * Please upgrade to resteasy-rxjava2 and RxJava 2.x. - */ + * @deprecated: + * + * "RxJava 1.x is now officially end-of-life (EOL). No further developments, + * bugfixes, enhancements, javadoc changes or maintenance will be provided by + * this project after version 1.3.8." - From https://github.com/ReactiveX/RxJava/releases + * + * Please upgrade to resteasy-rxjava2 and RxJava 2.x. + */ @Provider @Deprecated public class ObservableProvider implements AsyncStreamProvider> diff --git a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableRxInvokerImpl.java b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableRxInvokerImpl.java index 09d8ad284b8..51c9af5ddd0 100644 --- a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableRxInvokerImpl.java +++ b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ObservableRxInvokerImpl.java @@ -33,242 +33,242 @@ @Deprecated public class ObservableRxInvokerImpl implements ObservableRxInvoker { - private static Object monitor = new Object(); - private ClientInvocationBuilder syncInvoker; - private ScheduledExecutorService executorService; - - public ObservableRxInvokerImpl(SyncInvoker syncInvoker, ExecutorService executorService) - { - if (!(syncInvoker instanceof ClientInvocationBuilder)) - { - throw new ProcessingException(Messages.MESSAGES.expectedClientInvocationBuilder(syncInvoker.getClass().getName())); - } - this.syncInvoker = (ClientInvocationBuilder) syncInvoker; - if (executorService instanceof ScheduledExecutorService) - { - this.executorService = (ScheduledExecutorService) executorService; - } - } - - @Override - public Observable get() - { - return eventSourceToObservable(getEventSource(), String.class, "GET", null, getAccept()); - } - - @Override - public Observable get(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); - } - - @Override - public Observable get(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); - } - - @Override - public Observable put(Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, "PUT", entity, getAccept()); - } - - @Override - public Observable put(Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); - } - - @Override - public Observable put(Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); - } - - @Override - public Observable post(Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, "POST", entity, getAccept()); - } - - @Override - public Observable post(Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); - } - - @Override - public Observable post(Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); - } - - @Override - public Observable delete() - { - return eventSourceToObservable(getEventSource(), String.class, "DELETE", null, getAccept()); - } - - @Override - public Observable delete(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); - } - - @Override - public Observable delete(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); - } - - @Override - public Observable head() - { - return eventSourceToObservable(getEventSource(), String.class, "HEAD", null, getAccept()); - } - - @Override - public Observable options() - { - return eventSourceToObservable(getEventSource(), String.class, "OPTIONS", null, getAccept()); - } - - @Override - public Observable options(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); - } - - @Override - public Observable options(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); - } - - @Override - public Observable trace() - { - return eventSourceToObservable(getEventSource(), String.class, "TRACE", null, getAccept()); - } - - @Override - public Observable trace(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); - } - - @Override - public Observable trace(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); - } - - @Override - public Observable method(String name) - { - return eventSourceToObservable(getEventSource(), String.class, name, null, getAccept()); - } - - @Override - public Observable method(String name, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); - } - - @Override - public Observable method(String name, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); - } - - @Override - public Observable method(String name, Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, name, entity, getAccept()); - } - - @Override - public Observable method(String name, Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); - } - - @Override - public Observable method(String name, Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); - } - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, Class clazz, String verb, Entity entity, MediaType[] mediaTypes) - { - Observable observable = Observable.create( - new Observable.OnSubscribe() { - @Override - public void call(Subscriber sub) { - sseEventSource.register( - (InboundSseEvent e) -> {T t = e.readData(clazz, ((InboundSseEventImpl) e).getMediaType()); sub.onNext(t);}, - (Throwable t) -> sub.onError(t), - () -> sub.onCompleted()); - synchronized (monitor) - { - if (!sseEventSource.isOpen()) - { - sseEventSource.open(null, verb, entity, mediaTypes); - } - } - } - }); - return observable; - } - - private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, GenericType type, String verb, Entity entity, MediaType[] mediaTypes) - { - Observable observable = Observable.create( - new Observable.OnSubscribe() { - @Override - public void call(Subscriber sub) { - sseEventSource.register( - (InboundSseEvent e) -> {T t = e.readData(type, ((InboundSseEventImpl) e).getMediaType()); sub.onNext(t);}, - (Throwable t) -> sub.onError(t), - () -> sub.onCompleted()); - synchronized (monitor) - { - if (!sseEventSource.isOpen()) - { - sseEventSource.open(null, verb, entity, mediaTypes); - } - } - } - }); - return observable; - } - - private SseEventSourceImpl getEventSource() - { - SourceBuilder builder = (SourceBuilder) SseEventSource.target(syncInvoker.getTarget()); - if (executorService != null) - { - builder.executor(executorService); - } - SseEventSourceImpl sseEventSource = (SseEventSourceImpl) builder.build(); - sseEventSource.setAlwaysReconnect(false); - return sseEventSource; - } - - private MediaType[] getAccept() - { - if (syncInvoker instanceof ClientInvocationBuilder) - { - ClientInvocationBuilder builder = (ClientInvocationBuilder) syncInvoker; - List accept = builder.getHeaders().getAcceptableMediaTypes(); - return accept.toArray(new MediaType[accept.size()]); - } - else - { - return null; - } - } + private static Object monitor = new Object(); + private ClientInvocationBuilder syncInvoker; + private ScheduledExecutorService executorService; + + public ObservableRxInvokerImpl(SyncInvoker syncInvoker, ExecutorService executorService) + { + if (!(syncInvoker instanceof ClientInvocationBuilder)) + { + throw new ProcessingException(Messages.MESSAGES.expectedClientInvocationBuilder(syncInvoker.getClass().getName())); + } + this.syncInvoker = (ClientInvocationBuilder) syncInvoker; + if (executorService instanceof ScheduledExecutorService) + { + this.executorService = (ScheduledExecutorService) executorService; + } + } + + @Override + public Observable get() + { + return eventSourceToObservable(getEventSource(), String.class, "GET", null, getAccept()); + } + + @Override + public Observable get(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); + } + + @Override + public Observable get(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); + } + + @Override + public Observable put(Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, "PUT", entity, getAccept()); + } + + @Override + public Observable put(Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); + } + + @Override + public Observable put(Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); + } + + @Override + public Observable post(Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, "POST", entity, getAccept()); + } + + @Override + public Observable post(Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); + } + + @Override + public Observable post(Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); + } + + @Override + public Observable delete() + { + return eventSourceToObservable(getEventSource(), String.class, "DELETE", null, getAccept()); + } + + @Override + public Observable delete(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); + } + + @Override + public Observable delete(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); + } + + @Override + public Observable head() + { + return eventSourceToObservable(getEventSource(), String.class, "HEAD", null, getAccept()); + } + + @Override + public Observable options() + { + return eventSourceToObservable(getEventSource(), String.class, "OPTIONS", null, getAccept()); + } + + @Override + public Observable options(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); + } + + @Override + public Observable options(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); + } + + @Override + public Observable trace() + { + return eventSourceToObservable(getEventSource(), String.class, "TRACE", null, getAccept()); + } + + @Override + public Observable trace(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); + } + + @Override + public Observable trace(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); + } + + @Override + public Observable method(String name) + { + return eventSourceToObservable(getEventSource(), String.class, name, null, getAccept()); + } + + @Override + public Observable method(String name, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); + } + + @Override + public Observable method(String name, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); + } + + @Override + public Observable method(String name, Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, name, entity, getAccept()); + } + + @Override + public Observable method(String name, Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); + } + + @Override + public Observable method(String name, Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, Class clazz, String verb, Entity entity, MediaType[] mediaTypes) + { + Observable observable = Observable.create( + new Observable.OnSubscribe() { + @Override + public void call(Subscriber sub) { + sseEventSource.register( + (InboundSseEvent e) -> {T t = e.readData(clazz, ((InboundSseEventImpl) e).getMediaType()); sub.onNext(t);}, + (Throwable t) -> sub.onError(t), + () -> sub.onCompleted()); + synchronized (monitor) + { + if (!sseEventSource.isOpen()) + { + sseEventSource.open(null, verb, entity, mediaTypes); + } + } + } + }); + return observable; + } + + private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, GenericType type, String verb, Entity entity, MediaType[] mediaTypes) + { + Observable observable = Observable.create( + new Observable.OnSubscribe() { + @Override + public void call(Subscriber sub) { + sseEventSource.register( + (InboundSseEvent e) -> {T t = e.readData(type, ((InboundSseEventImpl) e).getMediaType()); sub.onNext(t);}, + (Throwable t) -> sub.onError(t), + () -> sub.onCompleted()); + synchronized (monitor) + { + if (!sseEventSource.isOpen()) + { + sseEventSource.open(null, verb, entity, mediaTypes); + } + } + } + }); + return observable; + } + + private SseEventSourceImpl getEventSource() + { + SourceBuilder builder = (SourceBuilder) SseEventSource.target(syncInvoker.getTarget()); + if (executorService != null) + { + builder.executor(executorService); + } + SseEventSourceImpl sseEventSource = (SseEventSourceImpl) builder.build(); + sseEventSource.setAlwaysReconnect(false); + return sseEventSource; + } + + private MediaType[] getAccept() + { + if (syncInvoker instanceof ClientInvocationBuilder) + { + ClientInvocationBuilder builder = (ClientInvocationBuilder) syncInvoker; + List accept = builder.getHeaders().getAcceptableMediaTypes(); + return accept.toArray(new MediaType[accept.size()]); + } + else + { + return null; + } + } } diff --git a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnObservableCreateAction.java b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnObservableCreateAction.java index 912aaa6de3a..0eaf54ccda9 100644 --- a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnObservableCreateAction.java +++ b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnObservableCreateAction.java @@ -9,14 +9,14 @@ import rx.functions.Func1; /** - * @deprecated: - * - * "RxJava 1.x is now officially end-of-life (EOL). No further developments, - * bugfixes, enhancements, javadoc changes or maintenance will be provided by - * this project after version 1.3.8." - From https://github.com/ReactiveX/RxJava/releases - * - * Please upgrade to resteasy-rxjava2 and RxJava 2.x. - */ + * @deprecated: + * + * "RxJava 1.x is now officially end-of-life (EOL). No further developments, + * bugfixes, enhancements, javadoc changes or maintenance will be provided by + * this project after version 1.3.8." - From https://github.com/ReactiveX/RxJava/releases + * + * Please upgrade to resteasy-rxjava2 and RxJava 2.x. + */ @SuppressWarnings("rawtypes") @Deprecated public class ResteasyContextPropagatingOnObservableCreateAction implements Func1 diff --git a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnSingleCreateAction.java b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnSingleCreateAction.java index 80e92930a35..42c3f4600ae 100644 --- a/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnSingleCreateAction.java +++ b/resteasy-rxjava/src/main/java/org/jboss/resteasy/rxjava/ResteasyContextPropagatingOnSingleCreateAction.java @@ -10,14 +10,14 @@ import rx.functions.Func1; /** - * @deprecated: - * - * "RxJava 1.x is now officially end-of-life (EOL). No further developments, - * bugfixes, enhancements, javadoc changes or maintenance will be provided by - * this project after version 1.3.8." - From https://github.com/ReactiveX/RxJava/releases - * - * Please upgrade to resteasy-rxjava2 and RxJava 2.x. - */ + * @deprecated: + * + * "RxJava 1.x is now officially end-of-life (EOL). No further developments, + * bugfixes, enhancements, javadoc changes or maintenance will be provided by + * this project after version 1.3.8." - From https://github.com/ReactiveX/RxJava/releases + * + * Please upgrade to resteasy-rxjava2 and RxJava 2.x. + */ @SuppressWarnings("rawtypes") @Deprecated public class ResteasyContextPropagatingOnSingleCreateAction implements Func1 diff --git a/resteasy-rxjava/src/test/java/org/jboss/resteasy/rxjava/RxTest.java b/resteasy-rxjava/src/test/java/org/jboss/resteasy/rxjava/RxTest.java index f3b3a3c7629..755cb4af658 100644 --- a/resteasy-rxjava/src/test/java/org/jboss/resteasy/rxjava/RxTest.java +++ b/resteasy-rxjava/src/test/java/org/jboss/resteasy/rxjava/RxTest.java @@ -133,4 +133,4 @@ public void testInjection() data = client.target(generateURL("/injection-async")).request().get(Integer.class); assertEquals((Integer)42, data); } -} \ No newline at end of file +} diff --git a/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvoker.java b/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvoker.java index de612ebd7e6..1641bbc254a 100644 --- a/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvoker.java +++ b/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvoker.java @@ -7,7 +7,7 @@ public interface FlowableRxInvoker extends RxInvoker> { - BackpressureStrategy getBackpressureStrategy(); + BackpressureStrategy getBackpressureStrategy(); - void setBackpressureStrategy(BackpressureStrategy backpressureStrategy); + void setBackpressureStrategy(BackpressureStrategy backpressureStrategy); } diff --git a/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvokerImpl.java b/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvokerImpl.java index d708de8e0bc..53ba256ffc6 100644 --- a/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvokerImpl.java +++ b/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/FlowableRxInvokerImpl.java @@ -25,258 +25,258 @@ public class FlowableRxInvokerImpl implements FlowableRxInvoker { - private static Object monitor = new Object(); - private ClientInvocationBuilder syncInvoker; - private ScheduledExecutorService executorService; - private BackpressureStrategy backpressureStrategy = BackpressureStrategy.BUFFER; - - public FlowableRxInvokerImpl(SyncInvoker syncInvoker, ExecutorService executorService) - { - if (!(syncInvoker instanceof ClientInvocationBuilder)) - { + private static Object monitor = new Object(); + private ClientInvocationBuilder syncInvoker; + private ScheduledExecutorService executorService; + private BackpressureStrategy backpressureStrategy = BackpressureStrategy.BUFFER; + + public FlowableRxInvokerImpl(SyncInvoker syncInvoker, ExecutorService executorService) + { + if (!(syncInvoker instanceof ClientInvocationBuilder)) + { throw new ProcessingException(Messages.MESSAGES.expectedClientInvocationBuilder(syncInvoker.getClass().getName())); - } - this.syncInvoker = (ClientInvocationBuilder) syncInvoker; - if (executorService instanceof ScheduledExecutorService) - { - this.executorService = (ScheduledExecutorService) executorService; - } - } - - @Override - public Flowable get() - { - return eventSourceToObservable(getEventSource(), String.class, "GET", null, getAccept()); - } - - @Override - public Flowable get(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); - } - - @Override - public Flowable get(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); - } - - @Override - public Flowable put(Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, "PUT", entity, getAccept()); - } - - @Override - public Flowable put(Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); - } - - @Override - public Flowable put(Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); - } - - @Override - public Flowable post(Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, "POST", entity, getAccept()); - } - - @Override - public Flowable post(Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); - } - - @Override - public Flowable post(Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); - } - - @Override - public Flowable delete() - { - return eventSourceToObservable(getEventSource(), String.class, "DELETE", null, getAccept()); - } - - @Override - public Flowable delete(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); - } - - @Override - public Flowable delete(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); - } - - @Override - public Flowable head() - { - return eventSourceToObservable(getEventSource(), String.class, "HEAD", null, getAccept()); - } - - @Override - public Flowable options() - { - return eventSourceToObservable(getEventSource(), String.class, "OPTIONS", null, getAccept()); - } - - @Override - public Flowable options(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); - } - - @Override - public Flowable options(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); - } - - @Override - public Flowable trace() - { - return eventSourceToObservable(getEventSource(), String.class, "TRACE", null, getAccept()); - } - - @Override - public Flowable trace(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); - } - - @Override - public Flowable trace(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); - } - - @Override - public Flowable method(String name) - { - return eventSourceToObservable(getEventSource(), String.class, name, null, getAccept()); - } - - @Override - public Flowable method(String name, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); - } - - @Override - public Flowable method(String name, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); - } - - @Override - public Flowable method(String name, Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, name, entity, getAccept()); - } - - @Override - public Flowable method(String name, Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); - } - - @Override - public Flowable method(String name, Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); - } - - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - @Override - public BackpressureStrategy getBackpressureStrategy() { - return backpressureStrategy; - } - - @Override - public void setBackpressureStrategy(BackpressureStrategy backpressureStrategy) { - this.backpressureStrategy = backpressureStrategy; - } - - private Flowable eventSourceToObservable(SseEventSourceImpl sseEventSource, Class clazz, String verb, Entity entity, MediaType[] mediaTypes) - { - Flowable flowable = Flowable.create( - new FlowableOnSubscribe() { - - @Override - public void subscribe(FlowableEmitter emitter) throws Exception { - sseEventSource.register( - (InboundSseEvent e) -> {T t = e.readData(clazz, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, - (Throwable t) -> emitter.onError(t), - () -> emitter.onComplete()); - synchronized (monitor) - { - if (!sseEventSource.isOpen()) - { - sseEventSource.open(null, verb, entity, mediaTypes); - } - } - } - }, - backpressureStrategy); - return flowable; - } - - private Flowable eventSourceToObservable(SseEventSourceImpl sseEventSource, GenericType type, String verb, Entity entity, MediaType[] mediaTypes) - { - Flowable flowable = Flowable.create( - new FlowableOnSubscribe() { - - @Override - public void subscribe(FlowableEmitter emitter) throws Exception { - sseEventSource.register( - (InboundSseEvent e) -> {T t = e.readData(type, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, - (Throwable t) -> emitter.onError(t), - () -> emitter.onComplete()); - synchronized (monitor) - { - if (!sseEventSource.isOpen()) - { - sseEventSource.open(null, verb, entity, mediaTypes); - } - } - } - }, - backpressureStrategy); - return flowable; - } - - private SseEventSourceImpl getEventSource() - { - SourceBuilder builder = (SourceBuilder) SseEventSource.target(syncInvoker.getTarget()); - if (executorService != null) - { - builder.executor(executorService); - } - SseEventSourceImpl sseEventSource = (SseEventSourceImpl) builder.build(); - sseEventSource.setAlwaysReconnect(false); - return sseEventSource; - } - - private MediaType[] getAccept() - { - if (syncInvoker instanceof ClientInvocationBuilder) - { - ClientInvocationBuilder builder = (ClientInvocationBuilder) syncInvoker; - List accept = builder.getHeaders().getAcceptableMediaTypes(); - return accept.toArray(new MediaType[accept.size()]); - } - else - { - return null; - } - } + } + this.syncInvoker = (ClientInvocationBuilder) syncInvoker; + if (executorService instanceof ScheduledExecutorService) + { + this.executorService = (ScheduledExecutorService) executorService; + } + } + + @Override + public Flowable get() + { + return eventSourceToObservable(getEventSource(), String.class, "GET", null, getAccept()); + } + + @Override + public Flowable get(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); + } + + @Override + public Flowable get(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); + } + + @Override + public Flowable put(Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, "PUT", entity, getAccept()); + } + + @Override + public Flowable put(Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); + } + + @Override + public Flowable put(Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); + } + + @Override + public Flowable post(Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, "POST", entity, getAccept()); + } + + @Override + public Flowable post(Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); + } + + @Override + public Flowable post(Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); + } + + @Override + public Flowable delete() + { + return eventSourceToObservable(getEventSource(), String.class, "DELETE", null, getAccept()); + } + + @Override + public Flowable delete(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); + } + + @Override + public Flowable delete(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); + } + + @Override + public Flowable head() + { + return eventSourceToObservable(getEventSource(), String.class, "HEAD", null, getAccept()); + } + + @Override + public Flowable options() + { + return eventSourceToObservable(getEventSource(), String.class, "OPTIONS", null, getAccept()); + } + + @Override + public Flowable options(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); + } + + @Override + public Flowable options(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); + } + + @Override + public Flowable trace() + { + return eventSourceToObservable(getEventSource(), String.class, "TRACE", null, getAccept()); + } + + @Override + public Flowable trace(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); + } + + @Override + public Flowable trace(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); + } + + @Override + public Flowable method(String name) + { + return eventSourceToObservable(getEventSource(), String.class, name, null, getAccept()); + } + + @Override + public Flowable method(String name, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); + } + + @Override + public Flowable method(String name, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); + } + + @Override + public Flowable method(String name, Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, name, entity, getAccept()); + } + + @Override + public Flowable method(String name, Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); + } + + @Override + public Flowable method(String name, Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); + } + + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + @Override + public BackpressureStrategy getBackpressureStrategy() { + return backpressureStrategy; + } + + @Override + public void setBackpressureStrategy(BackpressureStrategy backpressureStrategy) { + this.backpressureStrategy = backpressureStrategy; + } + + private Flowable eventSourceToObservable(SseEventSourceImpl sseEventSource, Class clazz, String verb, Entity entity, MediaType[] mediaTypes) + { + Flowable flowable = Flowable.create( + new FlowableOnSubscribe() { + + @Override + public void subscribe(FlowableEmitter emitter) throws Exception { + sseEventSource.register( + (InboundSseEvent e) -> {T t = e.readData(clazz, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, + (Throwable t) -> emitter.onError(t), + () -> emitter.onComplete()); + synchronized (monitor) + { + if (!sseEventSource.isOpen()) + { + sseEventSource.open(null, verb, entity, mediaTypes); + } + } + } + }, + backpressureStrategy); + return flowable; + } + + private Flowable eventSourceToObservable(SseEventSourceImpl sseEventSource, GenericType type, String verb, Entity entity, MediaType[] mediaTypes) + { + Flowable flowable = Flowable.create( + new FlowableOnSubscribe() { + + @Override + public void subscribe(FlowableEmitter emitter) throws Exception { + sseEventSource.register( + (InboundSseEvent e) -> {T t = e.readData(type, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, + (Throwable t) -> emitter.onError(t), + () -> emitter.onComplete()); + synchronized (monitor) + { + if (!sseEventSource.isOpen()) + { + sseEventSource.open(null, verb, entity, mediaTypes); + } + } + } + }, + backpressureStrategy); + return flowable; + } + + private SseEventSourceImpl getEventSource() + { + SourceBuilder builder = (SourceBuilder) SseEventSource.target(syncInvoker.getTarget()); + if (executorService != null) + { + builder.executor(executorService); + } + SseEventSourceImpl sseEventSource = (SseEventSourceImpl) builder.build(); + sseEventSource.setAlwaysReconnect(false); + return sseEventSource; + } + + private MediaType[] getAccept() + { + if (syncInvoker instanceof ClientInvocationBuilder) + { + ClientInvocationBuilder builder = (ClientInvocationBuilder) syncInvoker; + List accept = builder.getHeaders().getAcceptableMediaTypes(); + return accept.toArray(new MediaType[accept.size()]); + } + else + { + return null; + } + } } diff --git a/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/ObservableRxInvokerImpl.java b/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/ObservableRxInvokerImpl.java index 7aeba99e8bc..89d86367873 100644 --- a/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/ObservableRxInvokerImpl.java +++ b/resteasy-rxjava2/src/main/java/org/jboss/resteasy/rxjava2/ObservableRxInvokerImpl.java @@ -24,244 +24,244 @@ public class ObservableRxInvokerImpl implements ObservableRxInvoker { - private static Object monitor = new Object(); - private ClientInvocationBuilder syncInvoker; - private ScheduledExecutorService executorService; - - public ObservableRxInvokerImpl(SyncInvoker syncInvoker, ExecutorService executorService) - { - if (!(syncInvoker instanceof ClientInvocationBuilder)) - { - throw new ProcessingException(Messages.MESSAGES.expectedClientInvocationBuilder(syncInvoker.getClass().getName())); - } - this.syncInvoker = (ClientInvocationBuilder) syncInvoker; - if (executorService instanceof ScheduledExecutorService) - { - this.executorService = (ScheduledExecutorService) executorService; - } - } - - @Override - public Observable get() - { - return eventSourceToObservable(getEventSource(), String.class, "GET", null, getAccept()); - } - - @Override - public Observable get(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); - } - - @Override - public Observable get(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); - } - - @Override - public Observable put(Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, "PUT", entity, getAccept()); - } - - @Override - public Observable put(Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); - } - - @Override - public Observable put(Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); - } - - @Override - public Observable post(Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, "POST", entity, getAccept()); - } - - @Override - public Observable post(Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); - } - - @Override - public Observable post(Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); - } - - @Override - public Observable delete() - { - return eventSourceToObservable(getEventSource(), String.class, "DELETE", null, getAccept()); - } - - @Override - public Observable delete(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); - } - - @Override - public Observable delete(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); - } - - @Override - public Observable head() - { - return eventSourceToObservable(getEventSource(), String.class, "HEAD", null, getAccept()); - } - - @Override - public Observable options() - { - return eventSourceToObservable(getEventSource(), String.class, "OPTIONS", null, getAccept()); - } - - @Override - public Observable options(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); - } - - @Override - public Observable options(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); - } - - @Override - public Observable trace() - { - return eventSourceToObservable(getEventSource(), String.class, "TRACE", null, getAccept()); - } - - @Override - public Observable trace(Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); - } - - @Override - public Observable trace(GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); - } - - @Override - public Observable method(String name) - { - return eventSourceToObservable(getEventSource(), String.class, name, null, getAccept()); - } - - @Override - public Observable method(String name, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); - } - - @Override - public Observable method(String name, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); - } - - @Override - public Observable method(String name, Entity entity) - { - return eventSourceToObservable(getEventSource(), String.class, name, entity, getAccept()); - } - - @Override - public Observable method(String name, Entity entity, Class responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); - } - - @Override - public Observable method(String name, Entity entity, GenericType responseType) - { - return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); - } - - /////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, Class clazz, String verb, Entity entity, MediaType[] mediaTypes) - { - Observable observable = Observable.create( - new ObservableOnSubscribe() { - - @Override - public void subscribe(ObservableEmitter emitter) throws Exception { - sseEventSource.register( - (InboundSseEvent e) -> {T t = e.readData(clazz, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, - (Throwable t) -> emitter.onError(t), - () -> emitter.onComplete()); - synchronized (monitor) - { - if (!sseEventSource.isOpen()) - { - sseEventSource.open(null, verb, entity, mediaTypes); - } - } - } - }); - return observable; - } - - private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, GenericType type, String verb, Entity entity, MediaType[] mediaTypes) - { - Observable observable = Observable.create( - new ObservableOnSubscribe() { - - @Override - public void subscribe(ObservableEmitter emitter) throws Exception { - sseEventSource.register( - (InboundSseEvent e) -> {T t = e.readData(type, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, - (Throwable t) -> emitter.onError(t), - () -> emitter.onComplete()); - synchronized (monitor) - { - if (!sseEventSource.isOpen()) - { - sseEventSource.open(null, verb, entity, mediaTypes); - } - } - } - }); - return observable; - } - - private SseEventSourceImpl getEventSource() - { - SourceBuilder builder = (SourceBuilder) SseEventSource.target(syncInvoker.getTarget()); - if (executorService != null) - { - builder.executor(executorService); - } - SseEventSourceImpl sseEventSource = (SseEventSourceImpl) builder.build(); - sseEventSource.setAlwaysReconnect(false); - return sseEventSource; - } - - private MediaType[] getAccept() - { - if (syncInvoker instanceof ClientInvocationBuilder) - { - ClientInvocationBuilder builder = (ClientInvocationBuilder) syncInvoker; - List accept = builder.getHeaders().getAcceptableMediaTypes(); - return accept.toArray(new MediaType[accept.size()]); - } - else - { - return null; - } - } + private static Object monitor = new Object(); + private ClientInvocationBuilder syncInvoker; + private ScheduledExecutorService executorService; + + public ObservableRxInvokerImpl(SyncInvoker syncInvoker, ExecutorService executorService) + { + if (!(syncInvoker instanceof ClientInvocationBuilder)) + { + throw new ProcessingException(Messages.MESSAGES.expectedClientInvocationBuilder(syncInvoker.getClass().getName())); + } + this.syncInvoker = (ClientInvocationBuilder) syncInvoker; + if (executorService instanceof ScheduledExecutorService) + { + this.executorService = (ScheduledExecutorService) executorService; + } + } + + @Override + public Observable get() + { + return eventSourceToObservable(getEventSource(), String.class, "GET", null, getAccept()); + } + + @Override + public Observable get(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); + } + + @Override + public Observable get(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "GET", null, getAccept()); + } + + @Override + public Observable put(Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, "PUT", entity, getAccept()); + } + + @Override + public Observable put(Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); + } + + @Override + public Observable put(Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "PUT", entity, getAccept()); + } + + @Override + public Observable post(Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, "POST", entity, getAccept()); + } + + @Override + public Observable post(Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); + } + + @Override + public Observable post(Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "POST", entity, getAccept()); + } + + @Override + public Observable delete() + { + return eventSourceToObservable(getEventSource(), String.class, "DELETE", null, getAccept()); + } + + @Override + public Observable delete(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); + } + + @Override + public Observable delete(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "DELETE", null, getAccept()); + } + + @Override + public Observable head() + { + return eventSourceToObservable(getEventSource(), String.class, "HEAD", null, getAccept()); + } + + @Override + public Observable options() + { + return eventSourceToObservable(getEventSource(), String.class, "OPTIONS", null, getAccept()); + } + + @Override + public Observable options(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); + } + + @Override + public Observable options(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "OPTIONS", null, getAccept()); + } + + @Override + public Observable trace() + { + return eventSourceToObservable(getEventSource(), String.class, "TRACE", null, getAccept()); + } + + @Override + public Observable trace(Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); + } + + @Override + public Observable trace(GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, "TRACE", null, getAccept()); + } + + @Override + public Observable method(String name) + { + return eventSourceToObservable(getEventSource(), String.class, name, null, getAccept()); + } + + @Override + public Observable method(String name, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); + } + + @Override + public Observable method(String name, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, null, getAccept()); + } + + @Override + public Observable method(String name, Entity entity) + { + return eventSourceToObservable(getEventSource(), String.class, name, entity, getAccept()); + } + + @Override + public Observable method(String name, Entity entity, Class responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); + } + + @Override + public Observable method(String name, Entity entity, GenericType responseType) + { + return eventSourceToObservable(getEventSource(), responseType, name, entity, getAccept()); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, Class clazz, String verb, Entity entity, MediaType[] mediaTypes) + { + Observable observable = Observable.create( + new ObservableOnSubscribe() { + + @Override + public void subscribe(ObservableEmitter emitter) throws Exception { + sseEventSource.register( + (InboundSseEvent e) -> {T t = e.readData(clazz, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, + (Throwable t) -> emitter.onError(t), + () -> emitter.onComplete()); + synchronized (monitor) + { + if (!sseEventSource.isOpen()) + { + sseEventSource.open(null, verb, entity, mediaTypes); + } + } + } + }); + return observable; + } + + private Observable eventSourceToObservable(SseEventSourceImpl sseEventSource, GenericType type, String verb, Entity entity, MediaType[] mediaTypes) + { + Observable observable = Observable.create( + new ObservableOnSubscribe() { + + @Override + public void subscribe(ObservableEmitter emitter) throws Exception { + sseEventSource.register( + (InboundSseEvent e) -> {T t = e.readData(type, ((InboundSseEventImpl) e).getMediaType()); emitter.onNext(t);}, + (Throwable t) -> emitter.onError(t), + () -> emitter.onComplete()); + synchronized (monitor) + { + if (!sseEventSource.isOpen()) + { + sseEventSource.open(null, verb, entity, mediaTypes); + } + } + } + }); + return observable; + } + + private SseEventSourceImpl getEventSource() + { + SourceBuilder builder = (SourceBuilder) SseEventSource.target(syncInvoker.getTarget()); + if (executorService != null) + { + builder.executor(executorService); + } + SseEventSourceImpl sseEventSource = (SseEventSourceImpl) builder.build(); + sseEventSource.setAlwaysReconnect(false); + return sseEventSource; + } + + private MediaType[] getAccept() + { + if (syncInvoker instanceof ClientInvocationBuilder) + { + ClientInvocationBuilder builder = (ClientInvocationBuilder) syncInvoker; + List accept = builder.getHeaders().getAcceptableMediaTypes(); + return accept.toArray(new MediaType[accept.size()]); + } + else + { + return null; + } + } } diff --git a/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxInjector.java b/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxInjector.java index 31c7bfed363..15fdcdf470b 100644 --- a/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxInjector.java +++ b/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxInjector.java @@ -13,20 +13,20 @@ @Provider public class RxInjector implements ContextInjector, Integer>{ - @Override - public Single resolve(Class> rawType, Type genericType, - Annotation[] annotations) { - boolean async = false; - for (Annotation annotation : annotations) + @Override + public Single resolve(Class> rawType, Type genericType, + Annotation[] annotations) { + boolean async = false; + for (Annotation annotation : annotations) { if(annotation.annotationType() == Async.class) async = true; } - if(!async) - return Single.just(42); - return Single.create(emitter -> { - new Thread(() -> { - try + if(!async) + return Single.just(42); + return Single.create(emitter -> { + new Thread(() -> { + try { Thread.sleep(1000); } catch (InterruptedException e) @@ -34,9 +34,9 @@ public Single resolve(Class> rawType, Type ge emitter.onError(e); return; } - emitter.onSuccess(42); - }).start(); - }); - } + emitter.onSuccess(42); + }).start(); + }); + } } diff --git a/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxTest.java b/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxTest.java index 2feb530f4df..3ffbc29bcd2 100644 --- a/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxTest.java +++ b/resteasy-rxjava2/src/test/java/org/jboss/resteasy/rxjava2/RxTest.java @@ -32,11 +32,11 @@ public class RxTest { - private static NettyJaxrsServer server; + private static NettyJaxrsServer server; - private static CountDownLatch latch; - private static AtomicReference value = new AtomicReference(); - private static final Logger LOG = Logger.getLogger(NettyJaxrsServer.class); + private static CountDownLatch latch; + private static AtomicReference value = new AtomicReference(); + private static final Logger LOG = Logger.getLogger(NettyJaxrsServer.class); @BeforeClass public static void beforeClass() throws Exception @@ -69,97 +69,97 @@ public void before() .connectionCheckoutTimeout(5, TimeUnit.SECONDS) .connectTimeout(5, TimeUnit.SECONDS) .build(); - value.set(null); - latch = new CountDownLatch(1); - } - - @After - public void after() - { - client.close(); - } - - @Test - public void testSingle() throws Exception { - Single single = client.target(generateURL("/single")).request().rx(SingleRxInvoker.class).get(); - single.subscribe((Response r) -> {value.set(r.readEntity(String.class)); latch.countDown();}); - latch.await(); - assertEquals("got it", value.get()); - } - - @Test - public void testSingleContext() throws Exception { - Single single = client.target(generateURL("/context/single")).request().rx(SingleRxInvoker.class).get(); - single.subscribe((Response r) -> {value.set(r.readEntity(String.class)); latch.countDown();}); - latch.await(); - assertEquals("got it", value.get()); - } - - @Test - public void testObservable() throws Exception { - ObservableRxInvoker invoker = client.target(generateURL("/observable")).request().rx(ObservableRxInvoker.class); - @SuppressWarnings("unchecked") - Observable observable = (Observable) invoker.get(); - List data = new ArrayList(); - observable.subscribe( + value.set(null); + latch = new CountDownLatch(1); + } + + @After + public void after() + { + client.close(); + } + + @Test + public void testSingle() throws Exception { + Single single = client.target(generateURL("/single")).request().rx(SingleRxInvoker.class).get(); + single.subscribe((Response r) -> {value.set(r.readEntity(String.class)); latch.countDown();}); + latch.await(); + assertEquals("got it", value.get()); + } + + @Test + public void testSingleContext() throws Exception { + Single single = client.target(generateURL("/context/single")).request().rx(SingleRxInvoker.class).get(); + single.subscribe((Response r) -> {value.set(r.readEntity(String.class)); latch.countDown();}); + latch.await(); + assertEquals("got it", value.get()); + } + + @Test + public void testObservable() throws Exception { + ObservableRxInvoker invoker = client.target(generateURL("/observable")).request().rx(ObservableRxInvoker.class); + @SuppressWarnings("unchecked") + Observable observable = (Observable) invoker.get(); + List data = new ArrayList(); + observable.subscribe( (String s) -> data.add(s), (Throwable t) -> LOG.error(t.getMessage(), t), () -> latch.countDown()); - latch.await(); - assertArrayEquals(new String[] {"one", "two"}, data.toArray()); - } - - @Test - public void testObservableContext() throws Exception { - ObservableRxInvoker invoker = ClientBuilder.newClient().target(generateURL("/context/observable")).request().rx(ObservableRxInvoker.class); - @SuppressWarnings("unchecked") - Observable observable = (Observable) invoker.get(); - List data = new ArrayList(); - observable.subscribe( + latch.await(); + assertArrayEquals(new String[] {"one", "two"}, data.toArray()); + } + + @Test + public void testObservableContext() throws Exception { + ObservableRxInvoker invoker = ClientBuilder.newClient().target(generateURL("/context/observable")).request().rx(ObservableRxInvoker.class); + @SuppressWarnings("unchecked") + Observable observable = (Observable) invoker.get(); + List data = new ArrayList(); + observable.subscribe( (String s) -> data.add(s), (Throwable t) -> LOG.error(t.getMessage(), t), () -> latch.countDown()); - latch.await(); - assertArrayEquals(new String[] {"one", "two"}, data.toArray()); - } - - @Test - public void testFlowable() throws Exception { - FlowableRxInvoker invoker = client.target(generateURL("/flowable")).request().rx(FlowableRxInvoker.class); - @SuppressWarnings("unchecked") - Flowable flowable = (Flowable) invoker.get(); - List data = new ArrayList(); - flowable.subscribe( + latch.await(); + assertArrayEquals(new String[] {"one", "two"}, data.toArray()); + } + + @Test + public void testFlowable() throws Exception { + FlowableRxInvoker invoker = client.target(generateURL("/flowable")).request().rx(FlowableRxInvoker.class); + @SuppressWarnings("unchecked") + Flowable flowable = (Flowable) invoker.get(); + List data = new ArrayList(); + flowable.subscribe( (String s) -> data.add(s), (Throwable t) -> LOG.error(t.getMessage(), t), () -> latch.countDown()); - latch.await(); - assertArrayEquals(new String[] {"one", "two"}, data.toArray()); - } - - @Test - public void testFlowablecontext() throws Exception { - FlowableRxInvoker invoker = client.target(generateURL("/context/flowable")).request().rx(FlowableRxInvoker.class); - @SuppressWarnings("unchecked") - Flowable flowable = (Flowable) invoker.get(); - List data = new ArrayList(); - flowable.subscribe( + latch.await(); + assertArrayEquals(new String[] {"one", "two"}, data.toArray()); + } + + @Test + public void testFlowablecontext() throws Exception { + FlowableRxInvoker invoker = client.target(generateURL("/context/flowable")).request().rx(FlowableRxInvoker.class); + @SuppressWarnings("unchecked") + Flowable flowable = (Flowable) invoker.get(); + List data = new ArrayList(); + flowable.subscribe( (String s) -> data.add(s), (Throwable t) -> LOG.error(t.getMessage(), t), () -> {latch.countDown(); LOG.info("onComplete()");}); - latch.await(); - assertArrayEquals(new String[] {"one", "two"}, data.toArray()); - } - - // @Test - public void testChunked() throws Exception - { - Invocation.Builder request = client.target(generateURL("/chunked")).request(); - Response response = request.get(); - String entity = response.readEntity(String.class); - Assert.assertEquals(200, response.getStatus()); - Assert.assertEquals("onetwo", entity); - } + latch.await(); + assertArrayEquals(new String[] {"one", "two"}, data.toArray()); + } + + // @Test + public void testChunked() throws Exception + { + Invocation.Builder request = client.target(generateURL("/chunked")).request(); + Response response = request.get(); + String entity = response.readEntity(String.class); + Assert.assertEquals(200, response.getStatus()); + Assert.assertEquals("onetwo", entity); + } // @Test public void testInjection() @@ -170,4 +170,4 @@ public void testInjection() data = client.target(generateURL("/injection-async")).request().get(Integer.class); assertEquals((Integer)42, data); } -} \ No newline at end of file +} diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/client/spring/RestClientProxyFactoryBean.java b/resteasy-spring/src/main/java/org/jboss/resteasy/client/spring/RestClientProxyFactoryBean.java index 46d8aa1646a..9a6ac7b90eb 100755 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/client/spring/RestClientProxyFactoryBean.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/client/spring/RestClientProxyFactoryBean.java @@ -28,7 +28,7 @@ * @param The type representing the client interface. */ public class RestClientProxyFactoryBean implements FactoryBean, - InitializingBean + InitializingBean { private Class serviceInterface; private URI baseUri; @@ -38,41 +38,41 @@ public class RestClientProxyFactoryBean implements FactoryBean, private ResteasyProviderFactory resteasyProviderFactory; /* - * (non-Javadoc) - * - * @see org.springframework.beans.factory.FactoryBean#getObject() - */ + * (non-Javadoc) + * + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ public T getObject() throws Exception { return client; } /* - * (non-Javadoc) - * - * @see org.springframework.beans.factory.FactoryBean#getObjectType() - */ + * (non-Javadoc) + * + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ public Class getObjectType() { return serviceInterface; } /* - * (non-Javadoc) - * - * @see org.springframework.beans.factory.FactoryBean#isSingleton() - */ + * (non-Javadoc) + * + * @see org.springframework.beans.factory.FactoryBean#isSingleton() + */ public boolean isSingleton() { return true; } /* - * (non-Javadoc) - * - * @see - * org.springframework.beans.factory.InitializingBean#afterPropertiesSet() - */ + * (non-Javadoc) + * + * @see + * org.springframework.beans.factory.InitializingBean#afterPropertiesSet() + */ public void afterPropertiesSet() throws Exception { if (resteasyProviderFactory == null) @@ -177,7 +177,7 @@ public ResteasyProviderFactory getResteasyProviderFactory() * @param resteasyProviderFactory the instance to be used by proxy generation. */ public void setResteasyProviderFactory( - ResteasyProviderFactory resteasyProviderFactory) + ResteasyProviderFactory resteasyProviderFactory) { this.resteasyProviderFactory = resteasyProviderFactory; } diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringBeanProcessor.java b/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringBeanProcessor.java index 93503a8c7be..540dc2b45bc 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringBeanProcessor.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringBeanProcessor.java @@ -89,7 +89,7 @@ protected ResteasyBeanPostProcessor(ConfigurableListableBeanFactory beanFactory) } public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException + throws BeansException { return bean; } @@ -113,7 +113,7 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) * @see SpringBeanProcessor#postProcessBeanFactory(ConfigurableListableBeanFactory) */ public Object postProcessAfterInitialization(Object bean, String beanName) - throws BeansException + throws BeansException { if (providerNames.contains(beanName)) { @@ -255,11 +255,11 @@ public void setDispatcher(Dispatcher dispatcher) * are created by Spring before any resources by having the resources * "depends-on" the @Providers. *

- * + * * @param beanFactory bean factory */ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException + throws BeansException { beanFactory.registerResolvableDependency(Registry.class, getRegistry()); beanFactory.registerResolvableDependency(ResteasyProviderFactory.class, getProviderFactory()); @@ -275,7 +275,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) BeanDefinition beanDef = beanFactory.getBeanDefinition(name); if ( (beanDef.getBeanClassName() != null || beanDef.getFactoryBeanName() != null) && !beanDef.isAbstract()) - processBean(beanFactory, dependsOnBeans, name, beanDef); + processBean(beanFactory, dependsOnBeans, name, beanDef); } dependsOnBeans.addAll(registrations); @@ -343,11 +343,11 @@ public String getPropertyValue( } if(value.getClass() == String.class) { - return (String) value; + return (String) value; } if(value instanceof BeanReference) { - return ((BeanReference)value).getBeanName(); + return ((BeanReference)value).getBeanName(); } throw new IllegalStateException(Messages.MESSAGES.resteasyRegistrationReferences()); } @@ -382,7 +382,7 @@ private static String[] concat(String[] dependsOn, String[] dependsOnProviders) * @return bean class */ private static Class getBeanClass(String name, BeanDefinition beanDef, - ConfigurableListableBeanFactory beanFactory) + ConfigurableListableBeanFactory beanFactory) { if (beanDef instanceof RootBeanDefinition) { @@ -430,13 +430,13 @@ private static Class getBeanClass(String name, BeanDefinition beanDef, } } - final Class beanClass = getBeanClass(factoryClassName); - final Method[] methods = ReflectionUtils.getAllDeclaredMethods(beanClass); - for (Method method : methods) { - if (method.getName().equals(factoryMethodName)) { - return method.getReturnType(); - } - } + final Class beanClass = getBeanClass(factoryClassName); + final Method[] methods = ReflectionUtils.getAllDeclaredMethods(beanClass); + for (Method method : methods) { + if (method.getName().equals(factoryMethodName)) { + return method.getReturnType(); + } + } /* https://github.com/resteasy/Resteasy/issues/585 @@ -447,29 +447,29 @@ private static Class getBeanClass(String name, BeanDefinition beanDef, Case in which this tends to happen: 1. A bean (Bean A) exists which provides factoryMethods for retrieving 1 or more other beans (Bean B, Bean C, ...) - example: + example: 2. Bean B is retrieved by telling Spring that the Factory-Bean is Bean A and that there is a method X to retrieve Bean B. - example: + example: 3. When resteasy has to inject Bean B it tries to lookup method X on Bean A instead of Bean B using the above code. As a fix for this, we retrieve the return type for Bean A from the FactoryBean, which later on can be used to retrieve the other beans. - */ - if (FactoryBean.class.isAssignableFrom(beanClass)) { - String defaultFactoryMethod = "getObject"; - Class returnType = null; - for (Method method : methods) { - if (method.getName().equals(defaultFactoryMethod)) { - returnType = method.getReturnType(); - if (returnType != Object.class) { - break; - } + */ + if (FactoryBean.class.isAssignableFrom(beanClass)) { + String defaultFactoryMethod = "getObject"; + Class returnType = null; + for (Method method : methods) { + if (method.getName().equals(defaultFactoryMethod)) { + returnType = method.getReturnType(); + if (returnType != Object.class) { + break; } - } - if (returnType != null) { - return returnType; - } - } + } + } + if (returnType != null) { + return returnType; + } + } } throw new IllegalStateException(Messages.MESSAGES.couldNotFindTypeForBean(name)); diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringContextLoaderListener.java b/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringContextLoaderListener.java index 5643f3e7f4a..f911aa9c5e1 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringContextLoaderListener.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringContextLoaderListener.java @@ -63,8 +63,8 @@ protected ContextLoader createContextLoader() } @Override - protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext configurableWebApplicationContext) { - super.customizeContext(servletContext, configurableWebApplicationContext); - this.springContextLoaderSupport.customizeContext(servletContext, configurableWebApplicationContext); - } + protected void customizeContext(ServletContext servletContext, ConfigurableWebApplicationContext configurableWebApplicationContext) { + super.customizeContext(servletContext, configurableWebApplicationContext); + this.springContextLoaderSupport.customizeContext(servletContext, configurableWebApplicationContext); + } } diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringResourceFactory.java b/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringResourceFactory.java index ab58a3f3362..f150fa2cb35 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringResourceFactory.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/plugins/spring/SpringResourceFactory.java @@ -8,11 +8,11 @@ import org.springframework.beans.factory.BeanFactory; /** -* -* -* @author Solomn Duskis -* @version $Revision: 1 $ -*/ + * + * + * @author Solomn Duskis + * @version $Revision: 1 $ + */ public class SpringResourceFactory implements ResourceFactory { @@ -36,7 +36,7 @@ public PropertyInjector getPropertyInjector() } public Object createResource(HttpRequest request, HttpResponse response, - ResteasyProviderFactory factory) + ResteasyProviderFactory factory) { return beanFactory.getBean(beanName); } diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/JettyLifecycleManager.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/JettyLifecycleManager.java index 5c0534d57ed..5385c69dcfb 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/JettyLifecycleManager.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/JettyLifecycleManager.java @@ -7,10 +7,10 @@ import org.springframework.beans.factory.InitializingBean; /** -* -* @author Solomon Duskis -* @version $Revision: 1 $ -*/ + * + * @author Solomon Duskis + * @version $Revision: 1 $ + */ public class JettyLifecycleManager implements InitializingBean, DisposableBean { diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/RequestUtil.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/RequestUtil.java index 97f34ba42f9..d36b5b3c191 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/RequestUtil.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/RequestUtil.java @@ -24,7 +24,7 @@ public static HttpServletRequest getRequest() } public static ResteasyRequestWrapper getRequestWrapper(HttpServletRequest request) throws ServletException, - IOException + IOException { ResteasyRequestWrapper wrapper = (ResteasyRequestWrapper) request.getAttribute(RESPONSE_WRAPPER_KEY); if (wrapper == null) @@ -40,7 +40,7 @@ public static HttpRequest getHttpRequest(HttpServletRequest request) throws Serv } public static ResteasyRequestWrapper getRequestWrapper(HttpServletRequest request, String method, String prefix) - throws ServletException, IOException + throws ServletException, IOException { ResteasyRequestWrapper wrapper = (ResteasyRequestWrapper) request.getAttribute(RESPONSE_WRAPPER_KEY); if (wrapper == null) diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerAdapter.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerAdapter.java index 271d0f07daf..12097941600 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerAdapter.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerAdapter.java @@ -24,7 +24,7 @@ // Registry. Ideally, the Registry shouldn't be owned by the Dispatcher, and the // methods needed from SynchronousDispatcher should move into a shared class. public class ResteasyHandlerAdapter extends - ResteasyWebHandlerTemplate implements HandlerAdapter + ResteasyWebHandlerTemplate implements HandlerAdapter { protected ResteasyDeployment deployment; @@ -56,7 +56,7 @@ protected ModelAndView handle(ResteasyRequestWrapper requestWrapper, try { response.sendError(requestWrapper.getErrorCode(), requestWrapper - .getErrorMessage()); + .getErrorMessage()); } catch (Exception e) { @@ -83,7 +83,7 @@ protected ModelAndView handle(ResteasyRequestWrapper requestWrapper, } protected ModelAndView createModelAndView( - ResteasyRequestWrapper requestWrapper, HttpResponse response) + ResteasyRequestWrapper requestWrapper, HttpResponse response) { HttpRequest request = requestWrapper.getHttpRequest(); SynchronousDispatcher dispatcher = (SynchronousDispatcher)deployment.getDispatcher(); diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerMapping.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerMapping.java index 0a75da6b0bd..883b3486237 100755 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerMapping.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyHandlerMapping.java @@ -62,10 +62,10 @@ public void setInterceptors(HandlerInterceptor[] interceptors) } public HandlerExecutionChain getHandler(HttpServletRequest request) - throws Exception + throws Exception { ResteasyRequestWrapper requestWrapper = RequestUtil.getRequestWrapper( - request, request.getMethod(), prefix); + request, request.getMethod(), prefix); try { // NOTE: if invoker isn't found, RESTEasy throw NoReourceFoundFailure diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyRequestWrapper.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyRequestWrapper.java index 53e1652e335..ab7540fe53a 100755 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyRequestWrapper.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyRequestWrapper.java @@ -32,7 +32,7 @@ public ResteasyRequestWrapper(HttpServletRequest request) throws ServletExceptio } public ResteasyRequestWrapper(HttpServletRequest request, String httpMethod, String prefix) - throws ServletException, IOException + throws ServletException, IOException { this.httpServletRequest = request; ResteasyHttpHeaders headers = ServletUtil.extractHttpHeaders(request); @@ -48,7 +48,7 @@ public ResteasyRequestWrapper(HttpServletRequest request, String httpMethod, Str // invocations. Suggest Core RESTEasy refactoring to change the // async invocation httpRequest = new HttpServletInputMessage(request, null, null, null, headers, uriInfo, httpMethod - .toUpperCase(), null); + .toUpperCase(), null); } public HttpServletRequest getHttpServletRequest() diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyView.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyView.java index f8c3ed04665..8ff2f346aec 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyView.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyView.java @@ -97,8 +97,8 @@ protected Void handle(ResteasyRequestWrapper requestWrapper, if (responseInvoker != null) { ServerResponseWriter.writeNomapResponse(responseInvoker, httpRequest, response, dispatcher.getProviderFactory(), t -> { - if(t != null) - dispatcher.writeException(httpRequest, response, t, t2 -> {}); + if(t != null) + dispatcher.writeException(httpRequest, response, t, t2 -> {}); }); } } @@ -136,7 +136,7 @@ private MediaType resolveContentType(HttpRequest jaxrsRequest, MediaType mt) } private boolean isAcceptable(List acceptableMediaTypes, - MediaType potentialContentType) + MediaType potentialContentType) { boolean isAcceptable = false; for (MediaType acceptableMediaType : acceptableMediaTypes) diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebArgumentResolver.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebArgumentResolver.java index a57929d660a..6fcbe7b90ef 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebArgumentResolver.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebArgumentResolver.java @@ -49,7 +49,7 @@ public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception { HttpServletRequest servletRequest = (HttpServletRequest) webRequest - .getNativeRequest(); + .getNativeRequest(); Object[] parameterAnnotations = methodParameter.getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) { @@ -71,25 +71,25 @@ public Object resolveArgument(MethodParameter methodParameter, String contentType = servletRequest.getContentType(); MediaType mediaType = MediaType.valueOf(contentType); MessageBodyReader reader = factory.getMessageBodyReader(type, - genericType, annotations, mediaType); + genericType, annotations, mediaType); if (reader == null) throw new BadRequestException(Messages.MESSAGES.couldNotFindMessageBodyReader(genericType, mediaType)); return reader.readFrom(type, genericType, annotations, mediaType, - request.getHttpHeaders().getRequestHeaders(), request - .getInputStream()); + request.getHttpHeaders().getRequestHeaders(), request + .getInputStream()); } else if (isCookie) { CookieParam cookieParam = (CookieParam) annotation; DefaultValue defaultValue = FindAnnotation.findAnnotation( - annotations, DefaultValue.class); + annotations, DefaultValue.class); String defaultVal = null; if (defaultValue != null) defaultVal = defaultValue.value(); return new CookieParamInjector(type, genericType, method, - cookieParam.value(), defaultVal, annotations, factory).inject(request, - null); + cookieParam.value(), defaultVal, annotations, factory).inject(request, + null); } } return null; diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebHandlerTemplate.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebHandlerTemplate.java index 4d81cad6d1a..f435505b1e2 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebHandlerTemplate.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/ResteasyWebHandlerTemplate.java @@ -24,7 +24,7 @@ public T handle(ResteasyRequestWrapper requestWrapper, T result = null; HttpResponse response = new HttpServletResponseWrapper(httpServletResponse, - factory); + factory); HttpServletRequest servletRequest = requestWrapper.getHttpServletRequest(); try diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/annotation/RestfulData.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/annotation/RestfulData.java index 2303d7bff09..46e723aca8a 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/annotation/RestfulData.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/annotation/RestfulData.java @@ -22,7 +22,7 @@ /** * what content type does this support? This has the same allowed values as * javax.ws.rs.Consumes - * + * * @see javax.ws.rs.Consumes * */ String[] value = null; diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServer.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServer.java index 11c9a1229e2..47d70de8177 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServer.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServer.java @@ -5,54 +5,54 @@ import org.springframework.context.ApplicationContext; /** -* @author Solomn Duskis -* @version $Revision: 1 $ -* -*/ + * @author Solomn Duskis + * @version $Revision: 1 $ + * + */ @Deprecated public class TJWSEmbeddedSpringMVCServer extends TJWSServletServer { - protected TJWSSpringMVCDispatcher servlet = new TJWSSpringMVCDispatcher(); -// Class<>[] defaultResourceMethodInterceptors = DefaultInterceptors.defaultInterceptors; + protected TJWSSpringMVCDispatcher servlet = new TJWSSpringMVCDispatcher(); +// Class<>[] defaultResourceMethodInterceptors = DefaultInterceptors.defaultInterceptors; - protected String rootResourcePath = ""; + protected String rootResourcePath = ""; - public void setRootResourcePath(String rootResourcePath) { - this.rootResourcePath = rootResourcePath; - } + public void setRootResourcePath(String rootResourcePath) { + this.rootResourcePath = rootResourcePath; + } - public TJWSEmbeddedSpringMVCServer() { - } + public TJWSEmbeddedSpringMVCServer() { + } - public TJWSEmbeddedSpringMVCServer(String applicationContext, int port) { - this(applicationContext, port, ""); - } - public TJWSEmbeddedSpringMVCServer(String applicationContext, int port, String rootResourcePath) { - setSpringConfigLocation(applicationContext); - setPort(port); - setRootResourcePath(rootResourcePath); + public TJWSEmbeddedSpringMVCServer(String applicationContext, int port) { + this(applicationContext, port, ""); + } + public TJWSEmbeddedSpringMVCServer(String applicationContext, int port, String rootResourcePath) { + setSpringConfigLocation(applicationContext); + setPort(port); + setRootResourcePath(rootResourcePath); } -// public void setDefaultResourceMethodInterceptors(Class[] interceptorClasses) { -// defaultResourceMethodInterceptors = interceptorClasses; -// } +// public void setDefaultResourceMethodInterceptors(Class[] interceptorClasses) { +// defaultResourceMethodInterceptors = interceptorClasses; +// } - @Override - public void start() { - servlet.setContextPath(rootResourcePath); - addServlet(rootResourcePath, servlet); - super.start(); - } + @Override + public void start() { + servlet.setContextPath(rootResourcePath); + addServlet(rootResourcePath, servlet); + super.start(); + } - public void setSecurityDomain(SecurityDomain sc) { - servlet.setSecurityDomain(sc); - } + public void setSecurityDomain(SecurityDomain sc) { + servlet.setSecurityDomain(sc); + } - public void setSpringConfigLocation(String configFile) { - servlet.setContextConfigLocation(configFile); - } + public void setSpringConfigLocation(String configFile) { + servlet.setContextConfigLocation(configFile); + } - public ApplicationContext getApplicationContext() { - return servlet.getWebApplicationContext(); - } + public ApplicationContext getApplicationContext() { + return servlet.getWebApplicationContext(); + } } diff --git a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServerBean.java b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServerBean.java index 493caa2fcd5..608cb5730b1 100644 --- a/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServerBean.java +++ b/resteasy-spring/src/main/java/org/jboss/resteasy/springmvc/tjws/TJWSEmbeddedSpringMVCServerBean.java @@ -5,10 +5,10 @@ import org.springframework.beans.factory.InitializingBean; /** -* @author Solomn Duskis -* @version $Revision: 1 $ -* -*/ + * @author Solomn Duskis + * @version $Revision: 1 $ + * + */ @Deprecated public class TJWSEmbeddedSpringMVCServerBean implements InitializingBean, DisposableBean, FactoryBean diff --git a/resteasy-spring/src/test/java/org/jboss/resteasy/client/spring/test/BasicSpringTest.java b/resteasy-spring/src/test/java/org/jboss/resteasy/client/spring/test/BasicSpringTest.java index 0fbf34fb36f..bad8618db17 100755 --- a/resteasy-spring/src/test/java/org/jboss/resteasy/client/spring/test/BasicSpringTest.java +++ b/resteasy-spring/src/test/java/org/jboss/resteasy/client/spring/test/BasicSpringTest.java @@ -22,35 +22,35 @@ @DirtiesContext public class BasicSpringTest { - @Autowired - private BasicResource br; + @Autowired + private BasicResource br; - @Test - public void testBasic() throws HttpException, IOException - { -// ClientResponse result = br.getWrongContentTypeBasicObject(); -// Assert.assertEquals(-1, result.getStatus()); - Assert.assertEquals("/basic/url", br.getURL()); + @Test + public void testBasic() throws HttpException, IOException + { +// ClientResponse result = br.getWrongContentTypeBasicObject(); +// Assert.assertEquals(-1, result.getStatus()); + Assert.assertEquals("/basic/url", br.getURL()); - Assert.assertEquals("test", br.getBasicString()); - Assert.assertEquals("something", br.getBasicObject().getSomething()); + Assert.assertEquals("test", br.getBasicString()); + Assert.assertEquals("something", br.getBasicObject().getSomething()); - Assert.assertEquals("Hi, I'm custom!", br.getSpringMvcValue()); + Assert.assertEquals("Hi, I'm custom!", br.getSpringMvcValue()); - Assert.assertEquals(1, br.getSingletonCount().intValue()); - Assert.assertEquals(2, br.getSingletonCount().intValue()); + Assert.assertEquals(1, br.getSingletonCount().intValue()); + Assert.assertEquals(2, br.getSingletonCount().intValue()); - Assert.assertEquals(1, br.getPrototypeCount().intValue()); - Assert.assertEquals(1, br.getPrototypeCount().intValue()); + Assert.assertEquals(1, br.getPrototypeCount().intValue()); + Assert.assertEquals(1, br.getPrototypeCount().intValue()); - Assert.assertEquals("text/plain", br.getContentTypeHeader()); + Assert.assertEquals("text/plain", br.getContentTypeHeader()); - Integer interceptorCount = br - .getSpringInterceptorCount("afterCompletion"); - - Assert.assertEquals(new Integer(9), interceptorCount); - Assert.assertEquals("text/plain", br.getContentTypeHeader()); - Assert.assertEquals("springSomething", br.testSpringXml().getSomething()); -// br.testBogusUrl(); - } + Integer interceptorCount = br + .getSpringInterceptorCount("afterCompletion"); + + Assert.assertEquals(new Integer(9), interceptorCount); + Assert.assertEquals("text/plain", br.getContentTypeHeader()); + Assert.assertEquals("springSomething", br.testSpringXml().getSomething()); +// br.testBogusUrl(); + } } diff --git a/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/jaxb/BasicJaxbObject.java b/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/jaxb/BasicJaxbObject.java index ecd1b2b5cd0..14686d8f362 100644 --- a/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/jaxb/BasicJaxbObject.java +++ b/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/jaxb/BasicJaxbObject.java @@ -5,33 +5,33 @@ @XmlRootElement public class BasicJaxbObject { - private String something; - private Date someDate; - - - public BasicJaxbObject() { - super(); - } - - public BasicJaxbObject(String something, Date someDate) { - super(); - this.something = something; - this.someDate = someDate; - } - - public String getSomething() { - return something; - } - - public void setSomething(String something) { - this.something = something; - } - - public Date getSomeDate() { - return someDate; - } - - public void setSomeDate(Date someDate) { - this.someDate = someDate; - } + private String something; + private Date someDate; + + + public BasicJaxbObject() { + super(); + } + + public BasicJaxbObject(String something, Date someDate) { + super(); + this.something = something; + this.someDate = someDate; + } + + public String getSomething() { + return something; + } + + public void setSomething(String something) { + this.something = something; + } + + public Date getSomeDate() { + return someDate; + } + + public void setSomeDate(Date someDate) { + this.someDate = someDate; + } } diff --git a/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/resources/CounterResource.java b/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/resources/CounterResource.java index a7aca362769..29dbaebb4e1 100644 --- a/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/resources/CounterResource.java +++ b/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/resources/CounterResource.java @@ -6,11 +6,11 @@ @Path("/count") public class CounterResource { - private int count; + private int count; - @GET - @Produces("text/plain") - public Integer getCount() { - return ++count; - } + @GET + @Produces("text/plain") + public Integer getCount() { + return ++count; + } } diff --git a/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/view/MyCustomView.java b/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/view/MyCustomView.java index e0df1504d93..7308c19980c 100644 --- a/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/view/MyCustomView.java +++ b/resteasy-spring/src/test/java/org/jboss/resteasy/springmvc/test/view/MyCustomView.java @@ -10,15 +10,15 @@ @Component public class MyCustomView implements View { - public String getContentType() { - return "application/custom"; - } + public String getContentType() { + return "application/custom"; + } - @SuppressWarnings("rawtypes") - public void render(Map model, HttpServletRequest request, - HttpServletResponse response) throws Exception { - response.setContentType(getContentType()); - response.getOutputStream().print("Hi, I'm custom!"); - } + @SuppressWarnings("rawtypes") + public void render(Map model, HttpServletRequest request, + HttpServletResponse response) throws Exception { + response.setContentType(getContentType()); + response.getOutputStream().print("Hi, I'm custom!"); + } } diff --git a/resteasy-wadl-undertow-connector/src/main/java/org/jboss/resteasy/wadl/WadlUndertowConnector.java b/resteasy-wadl-undertow-connector/src/main/java/org/jboss/resteasy/wadl/WadlUndertowConnector.java index 874ae5431f5..0916ff70c59 100644 --- a/resteasy-wadl-undertow-connector/src/main/java/org/jboss/resteasy/wadl/WadlUndertowConnector.java +++ b/resteasy-wadl-undertow-connector/src/main/java/org/jboss/resteasy/wadl/WadlUndertowConnector.java @@ -14,29 +14,29 @@ * Created by weli on 7/26/16. */ public class WadlUndertowConnector { - public UndertowJaxrsServer deployToServer(UndertowJaxrsServer server, Class application) { - ApplicationPath appPath = application.getAnnotation(ApplicationPath.class); - String path = "/"; - if (appPath != null) path = appPath.value(); - - return deployToServer(server, application, path); - } - - public UndertowJaxrsServer deployToServer(UndertowJaxrsServer server, Class application, String contextPath) { - ResteasyDeployment deployment = new ResteasyDeployment(); - deployment.setApplicationClass(application.getName()); - - DeploymentInfo di = server.undertowDeployment(deployment); - - ServletInfo resteasyWadlServlet = servlet("ResteasyWadlServlet", ResteasyWadlServlet.class) - .setAsyncSupported(false) - .setLoadOnStartup(1) - .addMapping("/application.xml"); - di.addServlet(resteasyWadlServlet); - - di.setClassLoader(application.getClassLoader()); - di.setContextPath(contextPath); - di.setDeploymentName("Resteasy" + contextPath); - return server.deploy(di); - } + public UndertowJaxrsServer deployToServer(UndertowJaxrsServer server, Class application) { + ApplicationPath appPath = application.getAnnotation(ApplicationPath.class); + String path = "/"; + if (appPath != null) path = appPath.value(); + + return deployToServer(server, application, path); + } + + public UndertowJaxrsServer deployToServer(UndertowJaxrsServer server, Class application, String contextPath) { + ResteasyDeployment deployment = new ResteasyDeployment(); + deployment.setApplicationClass(application.getName()); + + DeploymentInfo di = server.undertowDeployment(deployment); + + ServletInfo resteasyWadlServlet = servlet("ResteasyWadlServlet", ResteasyWadlServlet.class) + .setAsyncSupported(false) + .setLoadOnStartup(1) + .addMapping("/application.xml"); + di.addServlet(resteasyWadlServlet); + + di.setClassLoader(application.getClassLoader()); + di.setContextPath(contextPath); + di.setDeploymentName("Resteasy" + contextPath); + return server.deploy(di); + } } diff --git a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLTestExistenceVerifier.java b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLTestExistenceVerifier.java index 32a2deaac56..ed57c504a7f 100644 --- a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLTestExistenceVerifier.java +++ b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLTestExistenceVerifier.java @@ -13,51 +13,51 @@ * Created by weli on 6/14/16. */ public class WADLTestExistenceVerifier { - private Map data = new HashMap<>(); - - public void createVerifier(String... keys) { - for (String key : keys) { - data.put(key, false); - } - } - - public void verify(List targets, Class targetClass, String fetchKeyMethod) throws InvocationTargetException, IllegalAccessException { - assertNotNull(targets); - assertTrue(targets.size() > 0); - - Method invocation = null; - - for (Object target : targets) { - for (Method method : target.getClass().getMethods()) { - if (target.getClass().equals(targetClass) && method.getName().equals(fetchKeyMethod)) { - invocation = method; - break; - } - } - } + private Map data = new HashMap<>(); + + public void createVerifier(String... keys) { + for (String key : keys) { + data.put(key, false); + } + } - if (invocation == null) throw new NoSuchMethodError(fetchKeyMethod); + public void verify(List targets, Class targetClass, String fetchKeyMethod) throws InvocationTargetException, IllegalAccessException { + assertNotNull(targets); + assertTrue(targets.size() > 0); - for (Object target : targets) { - for (String key : data.keySet()) { - if (target.getClass().equals(targetClass) && key.equals(invocation.invoke(target))) { - data.put(key, true); - } + Method invocation = null; + for (Object target : targets) { + for (Method method : target.getClass().getMethods()) { + if (target.getClass().equals(targetClass) && method.getName().equals(fetchKeyMethod)) { + invocation = method; + break; } - } + } + } - assertTrue(data.toString(), allTrue()); - } + if (invocation == null) throw new NoSuchMethodError(fetchKeyMethod); - public boolean allTrue() { - boolean flag = true; - for (Boolean value : data.values()) { - if (value.booleanValue() == false) { - flag = false; - break; + for (Object target : targets) { + for (String key : data.keySet()) { + if (target.getClass().equals(targetClass) && key.equals(invocation.invoke(target))) { + data.put(key, true); } - } - return flag; - } + + } + } + + assertTrue(data.toString(), allTrue()); + } + + public boolean allTrue() { + boolean flag = true; + for (Boolean value : data.values()) { + if (value.booleanValue() == false) { + flag = false; + break; + } + } + return flag; + } } diff --git a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLUndertowContainerTest.java b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLUndertowContainerTest.java index e93f0a6939d..3a6f671873e 100644 --- a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLUndertowContainerTest.java +++ b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/WADLUndertowContainerTest.java @@ -28,28 +28,28 @@ */ public class WADLUndertowContainerTest { - private UndertowJaxrsServer server; + private UndertowJaxrsServer server; - @Test - public void basicTest() throws Exception { - WadlUndertowConnector connector = new WadlUndertowConnector(); - connector.deployToServer(server, MyApp.class); - Client client = ClientBuilder.newClient(); + @Test + public void basicTest() throws Exception { + WadlUndertowConnector connector = new WadlUndertowConnector(); + connector.deployToServer(server, MyApp.class); + Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://127.0.0.1:${port}/base/application.xml".replaceAll("\\$\\{port\\}", - Integer.valueOf(TestPortProvider.getPort()).toString())); - Response response = target.request().get(); + WebTarget target = client.target("http://127.0.0.1:${port}/base/application.xml".replaceAll("\\$\\{port\\}", + Integer.valueOf(TestPortProvider.getPort()).toString())); + Response response = target.request().get(); - // get Application - org.jboss.resteasy.wadl.jaxb.Application application = response.readEntity(org.jboss.resteasy.wadl.jaxb.Application.class); - assertNotNull("application not null", application); - assertEquals(1, application.getResources().size()); + // get Application + org.jboss.resteasy.wadl.jaxb.Application application = response.readEntity(org.jboss.resteasy.wadl.jaxb.Application.class); + assertNotNull("application not null", application); + assertEquals(1, application.getResources().size()); - // get BasicResource - org.jboss.resteasy.wadl.jaxb.Resource basicResource = findResourceByName(application, "/basic"); - assertNotNull("basic resouce not null", basicResource); + // get BasicResource + org.jboss.resteasy.wadl.jaxb.Resource basicResource = findResourceByName(application, "/basic"); + assertNotNull("basic resouce not null", basicResource); - { + { // verify the existence of params WADLTestExistenceVerifier paramExistenceVerifier = new WADLTestExistenceVerifier(); paramExistenceVerifier.createVerifier("name", "name2"); @@ -70,9 +70,9 @@ public void basicTest() throws Exception { // verify 'get' method org.jboss.resteasy.wadl.jaxb.Method get = findMethodById(basicResource, "get"); assertEquals("GET", get.getName()); - } + } - { + { // verify existence of resources WADLTestExistenceVerifier resourceExistenceVerifier = new WADLTestExistenceVerifier(); String compositeResourceName = "composite/{pathParam}"; @@ -102,39 +102,39 @@ public void basicTest() throws Exception { WADLTestExistenceVerifier requestVerifier = new WADLTestExistenceVerifier(); requestVerifier.createVerifier("headerParam", "queryParam", "Cookie"); requestVerifier.verify(compositeMethod.getRequest().getParam(), org.jboss.resteasy.wadl.jaxb.Param.class, "getName"); - } + } - client.close(); - } - - @Test - public void test1246() throws Exception { - WadlUndertowConnector connector = new WadlUndertowConnector(); - connector.deployToServer(server, MyApp1246.class); - Client client = ClientBuilder.newClient(); - WebTarget target = client.target("http://127.0.0.1:${port}/base/application.xml".replaceAll("\\$\\{port\\}", - Integer.valueOf(TestPortProvider.getPort()).toString())); - Response response = target.request().get(); - // get Application - org.jboss.resteasy.wadl.jaxb.Application application = response.readEntity(org.jboss.resteasy.wadl.jaxb.Application.class); - org.jboss.resteasy.wadl.jaxb.Method multipleProvides1 = findMethodById(findResourceByName(findResourceByName(application, "/issues/1246"), "/provides1"), "multipleProvides1"); - assertEquals("Multiple representations should be present", 2, multipleProvides1.getResponse().get(0).getRepresentation().size()); - org.jboss.resteasy.wadl.jaxb.Method multipleProvides2 = findMethodById(findResourceByName(findResourceByName(application, "/issues/1246"), "/provides2"), "multipleProvides2"); - assertEquals("Multiple representations should be present", 2, multipleProvides2.getResponse().get(0).getRepresentation().size()); - client.close(); - } - - @Before - public void before() throws Exception { - server = new UndertowJaxrsServer().start(); - } - - @After - public void after() throws Exception { - server.stop(); - server = null; - } + client.close(); + } + + @Test + public void test1246() throws Exception { + WadlUndertowConnector connector = new WadlUndertowConnector(); + connector.deployToServer(server, MyApp1246.class); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target("http://127.0.0.1:${port}/base/application.xml".replaceAll("\\$\\{port\\}", + Integer.valueOf(TestPortProvider.getPort()).toString())); + Response response = target.request().get(); + // get Application + org.jboss.resteasy.wadl.jaxb.Application application = response.readEntity(org.jboss.resteasy.wadl.jaxb.Application.class); + org.jboss.resteasy.wadl.jaxb.Method multipleProvides1 = findMethodById(findResourceByName(findResourceByName(application, "/issues/1246"), "/provides1"), "multipleProvides1"); + assertEquals("Multiple representations should be present", 2, multipleProvides1.getResponse().get(0).getRepresentation().size()); + org.jboss.resteasy.wadl.jaxb.Method multipleProvides2 = findMethodById(findResourceByName(findResourceByName(application, "/issues/1246"), "/provides2"), "multipleProvides2"); + assertEquals("Multiple representations should be present", 2, multipleProvides2.getResponse().get(0).getRepresentation().size()); + client.close(); + } + + @Before + public void before() throws Exception { + server = new UndertowJaxrsServer().start(); + } + + @After + public void after() throws Exception { + server.stop(); + server = null; + } protected org.jboss.resteasy.wadl.jaxb.Resource findResourceByName(Object target, String resourceName) { @@ -176,22 +176,22 @@ protected org.jboss.resteasy.wadl.jaxb.Method findMethodById(org.jboss.resteasy. } - @ApplicationPath("/base") - public static class MyApp extends Application { - @Override - public Set> getClasses() { + @ApplicationPath("/base") + public static class MyApp extends Application { + @Override + public Set> getClasses() { HashSet> classes = new HashSet>(); classes.add(BasicResource.class); return classes; - } - } - @ApplicationPath("/base") - public static class MyApp1246 extends Application { - @Override - public Set> getClasses() { + } + } + @ApplicationPath("/base") + public static class MyApp1246 extends Application { + @Override + public Set> getClasses() { HashSet> classes = new HashSet>(); classes.add(RESTEASY1246.class); return classes; - } - } + } + } } diff --git a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/BasicResource.java b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/BasicResource.java index 5817331c82c..c04b69117af 100644 --- a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/BasicResource.java +++ b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/BasicResource.java @@ -16,32 +16,32 @@ @Path("/basic") public class BasicResource { - private String name; + private String name; - @GET - public String get(@PathParam("name") String name) { - return "Hello, " + name; - } + @GET + public String get(@PathParam("name") String name) { + return "Hello, " + name; + } - @POST - public void post(@PathParam("name2") String name2) { - this.name = name2; - } + @POST + public void post(@PathParam("name2") String name2) { + this.name = name2; + } - @GET - @Path("composite/{pathParam}") - @Produces("text/plain") - public String composite(@PathParam("pathParam") String pathParam, - @HeaderParam("headerParam") String headerParam, - @QueryParam("queryParam") String queryParam, - @MatrixParam("matrixParam") String matrixParam, - @CookieParam("cookieParam") String cookieParam) { - return "p:P;h:H;q:Q;m:M;c:C" - .replaceAll("P", pathParam) - .replaceAll("H", headerParam) - .replaceAll("Q", queryParam) - .replaceAll("M", matrixParam) - .replaceAll("C", cookieParam); - } + @GET + @Path("composite/{pathParam}") + @Produces("text/plain") + public String composite(@PathParam("pathParam") String pathParam, + @HeaderParam("headerParam") String headerParam, + @QueryParam("queryParam") String queryParam, + @MatrixParam("matrixParam") String matrixParam, + @CookieParam("cookieParam") String cookieParam) { + return "p:P;h:H;q:Q;m:M;c:C" + .replaceAll("P", pathParam) + .replaceAll("H", headerParam) + .replaceAll("Q", queryParam) + .replaceAll("M", matrixParam) + .replaceAll("C", cookieParam); + } } diff --git a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/issues/RESTEASY1246.java b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/issues/RESTEASY1246.java index 937d5962879..f8d0e66b939 100644 --- a/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/issues/RESTEASY1246.java +++ b/resteasy-wadl-undertow-connector/src/test/java/org/jboss/resteasy/test/nextgen/wadl/resources/issues/RESTEASY1246.java @@ -11,32 +11,31 @@ */ @Path("/issues/1246") public class RESTEASY1246 { - @Path("/provides1") - @GET - @Produces({"application/xml", "application/json"}) - public String multipleProvides1() { - return null; - } + @Path("/provides1") + @GET + @Produces({"application/xml", "application/json"}) + public String multipleProvides1() { + return null; + } - @Path("/provides2") - @GET - @Produces("application/xml,application/json") - public String multipleProvides2() { - return null; - } + @Path("/provides2") + @GET + @Produces("application/xml,application/json") + public String multipleProvides2() { + return null; + } - @Path("/consumes1") - @POST - @Consumes({"application/xml", "application/json"}) - public String multipleConsumes1() { - return null; - } + @Path("/consumes1") + @POST + @Consumes({"application/xml", "application/json"}) + public String multipleConsumes1() { + return null; + } - @Path("/consumes2") - @POST - @Consumes({"text/plain,text/html"}) - public String multipleConsumes2() { - return null; - } + @Path("/consumes2") + @POST + @Consumes({"text/plain,text/html"}) + public String multipleConsumes2() { + return null; + } } - diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlDefaultResource.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlDefaultResource.java index 35769607f1d..106070cc18e 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlDefaultResource.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlDefaultResource.java @@ -16,23 +16,23 @@ @Path("/application.xml") public class ResteasyWadlDefaultResource { - private final static ResteasyWadlWriter apiWriter = new ResteasyWadlServletWriter(); - private final static Map services = new HashMap<>(); + private final static ResteasyWadlWriter apiWriter = new ResteasyWadlServletWriter(); + private final static Map services = new HashMap<>(); - private final static Logger LOG = Logger.getLogger(ResteasyWadlDefaultResource.class); + private final static Logger LOG = Logger.getLogger(ResteasyWadlDefaultResource.class); - public static Map getServices() { - return services; - } + public static Map getServices() { + return services; + } - @GET - @Produces("application/xml") - public String output() { - try { - return this.apiWriter.getStringWriter("", services).toString(); - } catch (JAXBException e) { - LOG.error(Messages.MESSAGES.cantProcessWadl(), e); - } - return null; - } + @GET + @Produces("application/xml") + public String output() { + try { + return this.apiWriter.getStringWriter("", services).toString(); + } catch (JAXBException e) { + LOG.error(Messages.MESSAGES.cantProcessWadl(), e); + } + return null; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlGenerator.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlGenerator.java index e11331637a8..0753f373a1d 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlGenerator.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlGenerator.java @@ -9,10 +9,10 @@ */ public class ResteasyWadlGenerator { - public static ResteasyWadlServiceRegistry generateServiceRegistry(ResteasyDeployment deployment) { - ResourceMethodRegistry registry = (ResourceMethodRegistry) deployment.getRegistry(); - ResteasyProviderFactory providerFactory = deployment.getProviderFactory(); - ResteasyWadlServiceRegistry service = new ResteasyWadlServiceRegistry(null, registry, providerFactory, null); - return service; - } + public static ResteasyWadlServiceRegistry generateServiceRegistry(ResteasyDeployment deployment) { + ResourceMethodRegistry registry = (ResourceMethodRegistry) deployment.getRegistry(); + ResteasyProviderFactory providerFactory = deployment.getProviderFactory(); + ResteasyWadlServiceRegistry service = new ResteasyWadlServiceRegistry(null, registry, providerFactory, null); + return service; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodMetaData.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodMetaData.java index 33868553ad4..c5116a32b1c 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodMetaData.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodMetaData.java @@ -30,230 +30,230 @@ */ public class ResteasyWadlMethodMetaData { - private ResourceMethodInvoker resourceInvoker; - private Method method; - private Class klass; - private List produces; - private List consumesMIMETypes; - private String uri; - private String functionName; - private List parameters = new ArrayList(); - private Collection httpMethods; - private ResteasyWadlServiceRegistry registry; - private String functionPrefix; - private boolean wantsForm; - private String methodUri; - private String klassUri; + private ResourceMethodInvoker resourceInvoker; + private Method method; + private Class klass; + private List produces; + private List consumesMIMETypes; + private String uri; + private String functionName; + private List parameters = new ArrayList(); + private Collection httpMethods; + private ResteasyWadlServiceRegistry registry; + private String functionPrefix; + private boolean wantsForm; + private String methodUri; + private String klassUri; - public String getMethodUri() { - return methodUri; - } + public String getMethodUri() { + return methodUri; + } - public void setMethodUri(String methodUri) { - this.methodUri = methodUri; - } + public void setMethodUri(String methodUri) { + this.methodUri = methodUri; + } - public String getKlassUri() { - return klassUri; - } + public String getKlassUri() { + return klassUri; + } - public void setKlassUri(String klassUri) { - this.klassUri = klassUri; - } + public void setKlassUri(String klassUri) { + this.klassUri = klassUri; + } - public ResteasyWadlMethodMetaData(ResteasyWadlServiceRegistry serviceRegistry, ResourceMethodInvoker resourceInvoker) { - this.registry = serviceRegistry; - this.resourceInvoker = resourceInvoker; - this.method = resourceInvoker.getMethod(); - this.klass = resourceInvoker.getResourceClass(); - Path methodPath = method.getAnnotation(Path.class); - methodUri = methodPath == null ? null : methodPath.value(); - Path klassPath = klass.getAnnotation(Path.class); - klassUri = klassPath == null ? null : klassPath.value(); + public ResteasyWadlMethodMetaData(ResteasyWadlServiceRegistry serviceRegistry, ResourceMethodInvoker resourceInvoker) { + this.registry = serviceRegistry; + this.resourceInvoker = resourceInvoker; + this.method = resourceInvoker.getMethod(); + this.klass = resourceInvoker.getResourceClass(); + Path methodPath = method.getAnnotation(Path.class); + methodUri = methodPath == null ? null : methodPath.value(); + Path klassPath = klass.getAnnotation(Path.class); + klassUri = klassPath == null ? null : klassPath.value(); - Produces producesAnnotation = method.getAnnotation(Produces.class); - if (producesAnnotation == null) - producesAnnotation = klass.getAnnotation(Produces.class); - this.produces = getProduces(producesAnnotation); - Consumes consumes = method.getAnnotation(Consumes.class); - if (consumes == null) - consumes = klass.getAnnotation(Consumes.class); - this.uri = appendURIFragments(registry, klassPath, methodPath); - if (serviceRegistry.isRoot()) - this.functionPrefix = klass.getSimpleName(); - else - this.functionPrefix = serviceRegistry.getFunctionPrefix(); - this.functionName = this.functionPrefix + "." + method.getName(); - httpMethods = resourceInvoker.getHttpMethods(); + Produces producesAnnotation = method.getAnnotation(Produces.class); + if (producesAnnotation == null) + producesAnnotation = klass.getAnnotation(Produces.class); + this.produces = getProduces(producesAnnotation); + Consumes consumes = method.getAnnotation(Consumes.class); + if (consumes == null) + consumes = klass.getAnnotation(Consumes.class); + this.uri = appendURIFragments(registry, klassPath, methodPath); + if (serviceRegistry.isRoot()) + this.functionPrefix = klass.getSimpleName(); + else + this.functionPrefix = serviceRegistry.getFunctionPrefix(); + this.functionName = this.functionPrefix + "." + method.getName(); + httpMethods = resourceInvoker.getHttpMethods(); - // we need to add all parameters from parent resource locators until the root - List methodsUntilRoot = new ArrayList(); - methodsUntilRoot.add(method); - serviceRegistry.collectResourceMethodsUntilRoot(methodsUntilRoot); - for (Method m : methodsUntilRoot) { - Annotation[][] allAnnotations = m.getParameterAnnotations(); - Class[] parameterTypes = m.getParameterTypes(); - for (int i = 0; i < parameterTypes.length; i++) { - processMetaData(parameterTypes[i], allAnnotations[i], true); - } - } - // this must be after we scan the params in case of @Form - this.consumesMIMETypes = getConsumes(consumes); - if (wantsForm && !consumesMIMETypes.contains("application/x-www-form-urlencoded")) { - LogMessages.LOGGER.warn(Messages.MESSAGES.overridingConsumesAnnotation()); - this.consumesMIMETypes = Arrays.asList("application/x-www-form-urlencoded"); - } - } + // we need to add all parameters from parent resource locators until the root + List methodsUntilRoot = new ArrayList(); + methodsUntilRoot.add(method); + serviceRegistry.collectResourceMethodsUntilRoot(methodsUntilRoot); + for (Method m : methodsUntilRoot) { + Annotation[][] allAnnotations = m.getParameterAnnotations(); + Class[] parameterTypes = m.getParameterTypes(); + for (int i = 0; i < parameterTypes.length; i++) { + processMetaData(parameterTypes[i], allAnnotations[i], true); + } + } + // this must be after we scan the params in case of @Form + this.consumesMIMETypes = getConsumes(consumes); + if (wantsForm && !consumesMIMETypes.contains("application/x-www-form-urlencoded")) { + LogMessages.LOGGER.warn(Messages.MESSAGES.overridingConsumesAnnotation()); + this.consumesMIMETypes = Arrays.asList("application/x-www-form-urlencoded"); + } + } - protected void processMetaData(Class type, Annotation[] annotations, + protected void processMetaData(Class type, Annotation[] annotations, boolean useBody) { - QueryParam queryParam; - HeaderParam headerParam; - MatrixParam matrixParam; - PathParam pathParam; - CookieParam cookieParam; - FormParam formParam; - Form form; + QueryParam queryParam; + HeaderParam headerParam; + MatrixParam matrixParam; + PathParam pathParam; + CookieParam cookieParam; + FormParam formParam; + Form form; - // boolean isEncoded = FindAnnotation.findAnnotation(annotations, - // Encoded.class) != null; + // boolean isEncoded = FindAnnotation.findAnnotation(annotations, + // Encoded.class) != null; - if ((queryParam = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.QUERY_PARAMETER, queryParam - .value()); - } else if ((headerParam = FindAnnotation.findAnnotation(annotations, - HeaderParam.class)) != null) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.HEADER_PARAMETER, - headerParam.value()); - } else if ((cookieParam = FindAnnotation.findAnnotation(annotations, - CookieParam.class)) != null) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.COOKIE_PARAMETER, - cookieParam.value()); - } else if ((pathParam = FindAnnotation.findAnnotation(annotations, - PathParam.class)) != null) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.PATH_PARAMETER, - pathParam.value()); - } else if ((matrixParam = FindAnnotation.findAnnotation(annotations, - MatrixParam.class)) != null) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.MATRIX_PARAMETER, - matrixParam.value()); - } else if ((formParam = FindAnnotation.findAnnotation(annotations, - FormParam.class)) != null) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.FORM_PARAMETER, - formParam.value()); + if ((queryParam = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.QUERY_PARAMETER, queryParam + .value()); + } else if ((headerParam = FindAnnotation.findAnnotation(annotations, + HeaderParam.class)) != null) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.HEADER_PARAMETER, + headerParam.value()); + } else if ((cookieParam = FindAnnotation.findAnnotation(annotations, + CookieParam.class)) != null) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.COOKIE_PARAMETER, + cookieParam.value()); + } else if ((pathParam = FindAnnotation.findAnnotation(annotations, + PathParam.class)) != null) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.PATH_PARAMETER, + pathParam.value()); + } else if ((matrixParam = FindAnnotation.findAnnotation(annotations, + MatrixParam.class)) != null) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.MATRIX_PARAMETER, + matrixParam.value()); + } else if ((formParam = FindAnnotation.findAnnotation(annotations, + FormParam.class)) != null) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.FORM_PARAMETER, + formParam.value()); + this.wantsForm = true; + } else if ((form = FindAnnotation.findAnnotation(annotations, Form.class)) != null) { + if (type == List.class) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.FORM, form.prefix()); this.wantsForm = true; - } else if ((form = FindAnnotation.findAnnotation(annotations, Form.class)) != null) { - if (type == List.class) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.FORM, form.prefix()); - this.wantsForm = true; - } else if (type == Map.class) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.FORM, form.prefix()); - this.wantsForm = true; - } else - walkForm(type); - } else if ((FindAnnotation.findAnnotation(annotations, Context.class)) != null) { - // righfully ignore - } else if (useBody) { - addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.ENTITY_PARAMETER, null); - } - } + } else if (type == Map.class) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.FORM, form.prefix()); + this.wantsForm = true; + } else + walkForm(type); + } else if ((FindAnnotation.findAnnotation(annotations, Context.class)) != null) { + // righfully ignore + } else if (useBody) { + addParameter(type, annotations, ResteasyWadlMethodParamMetaData.MethodParamType.ENTITY_PARAMETER, null); + } + } - private void walkForm(Class type) { - for (Field field : type.getDeclaredFields()) { - processMetaData(field.getType(), field.getAnnotations(), false); - } - for (Method method : type.getDeclaredMethods()) { - if (method.getParameterTypes().length != 1 - || !method.getReturnType().equals(Void.class)) - continue; - processMetaData(method.getParameterTypes()[0], - method.getAnnotations(), false); - } - if (type.getSuperclass() != null) { - walkForm(type.getSuperclass()); - } - } + private void walkForm(Class type) { + for (Field field : type.getDeclaredFields()) { + processMetaData(field.getType(), field.getAnnotations(), false); + } + for (Method method : type.getDeclaredMethods()) { + if (method.getParameterTypes().length != 1 + || !method.getReturnType().equals(Void.class)) + continue; + processMetaData(method.getParameterTypes()[0], + method.getAnnotations(), false); + } + if (type.getSuperclass() != null) { + walkForm(type.getSuperclass()); + } + } - private void addParameter(Class type, Annotation[] annotations, + private void addParameter(Class type, Annotation[] annotations, ResteasyWadlMethodParamMetaData.MethodParamType paramType, String value) { - this.parameters.add(new ResteasyWadlMethodParamMetaData(type, annotations, paramType, - value)); - } + this.parameters.add(new ResteasyWadlMethodParamMetaData(type, annotations, paramType, + value)); + } - private List getProduces(Produces produces) { - if (produces == null) - return new ArrayList<>(); - String[] values = produces.value(); - return Arrays.asList(values); - } + private List getProduces(Produces produces) { + if (produces == null) + return new ArrayList<>(); + String[] values = produces.value(); + return Arrays.asList(values); + } - private List getConsumes(Consumes consumes) { - if (consumes == null) - return Arrays.asList("text/plain"); - if (consumes.value().length > 0) - return Arrays.asList(consumes.value()); - return Arrays.asList("text/plain"); - } + private List getConsumes(Consumes consumes) { + if (consumes == null) + return Arrays.asList("text/plain"); + if (consumes.value().length > 0) + return Arrays.asList(consumes.value()); + return Arrays.asList("text/plain"); + } - public static String appendURIFragments(String... fragments) { - StringBuilder str = new StringBuilder(); - for (String fragment : fragments) { - if (fragment == null || fragment.length() == 0 || fragment.equals("/")) - continue; - if (fragment.startsWith("/")) - fragment = fragment.substring(1); - if (fragment.endsWith("/")) - fragment = fragment.substring(0, fragment.length() - 1); - str.append('/').append(fragment); - } - if (str.length() == 0) - return "/"; - return str.toString(); - } + public static String appendURIFragments(String... fragments) { + StringBuilder str = new StringBuilder(); + for (String fragment : fragments) { + if (fragment == null || fragment.length() == 0 || fragment.equals("/")) + continue; + if (fragment.startsWith("/")) + fragment = fragment.substring(1); + if (fragment.endsWith("/")) + fragment = fragment.substring(0, fragment.length() - 1); + str.append('/').append(fragment); + } + if (str.length() == 0) + return "/"; + return str.toString(); + } - public ResourceMethodInvoker getResourceInvoker() { - return resourceInvoker; - } + public ResourceMethodInvoker getResourceInvoker() { + return resourceInvoker; + } - public Method getMethod() { - return method; - } + public Method getMethod() { + return method; + } - public Class getKlass() { - return klass; - } + public Class getKlass() { + return klass; + } - public List getProduces() { - return produces; - } + public List getProduces() { + return produces; + } - public List getConsumesMIMETypes() { - return consumesMIMETypes; - } + public List getConsumesMIMETypes() { + return consumesMIMETypes; + } - public String getUri() { - return uri; - } + public String getUri() { + return uri; + } - public String getFunctionName() { - return functionName; - } + public String getFunctionName() { + return functionName; + } - public List getParameters() { - return parameters; - } + public List getParameters() { + return parameters; + } - public Collection getHttpMethods() { - return httpMethods; - } + public Collection getHttpMethods() { + return httpMethods; + } - public static String appendURIFragments(ResteasyWadlServiceRegistry registry, Path classPath, Path methodPath) { - return appendURIFragments(registry == null ? null : registry.getUri(), - classPath != null ? classPath.value() : null, - methodPath != null ? methodPath.value() : null); - } + public static String appendURIFragments(ResteasyWadlServiceRegistry registry, Path classPath, Path methodPath) { + return appendURIFragments(registry == null ? null : registry.getUri(), + classPath != null ? classPath.value() : null, + methodPath != null ? methodPath.value() : null); + } - public String getFunctionPrefix() { - return functionPrefix; - } + public String getFunctionPrefix() { + return functionPrefix; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodParamMetaData.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodParamMetaData.java index 70d6a9bc2e2..63aed9f87e7 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodParamMetaData.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlMethodParamMetaData.java @@ -6,62 +6,62 @@ * @author Weinan Li */ public class ResteasyWadlMethodParamMetaData { - public enum MethodParamType { - QUERY_PARAMETER, HEADER_PARAMETER, COOKIE_PARAMETER, PATH_PARAMETER, MATRIX_PARAMETER, FORM_PARAMETER, FORM, ENTITY_PARAMETER - } + public enum MethodParamType { + QUERY_PARAMETER, HEADER_PARAMETER, COOKIE_PARAMETER, PATH_PARAMETER, MATRIX_PARAMETER, FORM_PARAMETER, FORM, ENTITY_PARAMETER + } - private Class type; - private String typeName; - private Annotation[] annotations; + private Class type; + private String typeName; + private Annotation[] annotations; - private MethodParamType paramType; - private String paramName; + private MethodParamType paramType; + private String paramName; - public ResteasyWadlMethodParamMetaData(Class type, Annotation[] annotations, + public ResteasyWadlMethodParamMetaData(Class type, Annotation[] annotations, MethodParamType paramType, String paramName) { - super(); - this.type = type; - this.annotations = annotations; - this.paramType = paramType; - this.paramName = paramName; - } - - public Class getType() { - return type; - } - - public String getTypeName() { - int i = 0; - - return ""; - } - - public void setType(Class type) { - this.type = type; - } - - public Annotation[] getAnnotations() { - return annotations; - } - - public void setAnnotations(Annotation[] annotations) { - this.annotations = annotations; - } - - public MethodParamType getParamType() { - return paramType; - } - - public void setParamType(MethodParamType paramType) { - this.paramType = paramType; - } - - public String getParamName() { - return paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } + super(); + this.type = type; + this.annotations = annotations; + this.paramType = paramType; + this.paramName = paramName; + } + + public Class getType() { + return type; + } + + public String getTypeName() { + int i = 0; + + return ""; + } + + public void setType(Class type) { + this.type = type; + } + + public Annotation[] getAnnotations() { + return annotations; + } + + public void setAnnotations(Annotation[] annotations) { + this.annotations = annotations; + } + + public MethodParamType getParamType() { + return paramType; + } + + public void setParamType(MethodParamType paramType) { + this.paramType = paramType; + } + + public String getParamName() { + return paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlResourceMetaData.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlResourceMetaData.java index 779e382e65b..41c2596029b 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlResourceMetaData.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlResourceMetaData.java @@ -7,26 +7,26 @@ * @author Weinan Li */ public class ResteasyWadlResourceMetaData { - private String uri; - private List methodsMetaData = new ArrayList(); + private String uri; + private List methodsMetaData = new ArrayList(); - public ResteasyWadlResourceMetaData(String uri) { - this.uri = uri; - } + public ResteasyWadlResourceMetaData(String uri) { + this.uri = uri; + } - public void addMethodMetaData(ResteasyWadlMethodMetaData methodMetaData) { - this.methodsMetaData.add(methodMetaData); - } + public void addMethodMetaData(ResteasyWadlMethodMetaData methodMetaData) { + this.methodsMetaData.add(methodMetaData); + } - public String getUri() { - return uri; - } + public String getUri() { + return uri; + } - public void setUri(String uri) { - this.uri = uri; - } + public void setUri(String uri) { + this.uri = uri; + } - public List getMethodsMetaData() { - return methodsMetaData; - } + public List getMethodsMetaData() { + return methodsMetaData; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServiceRegistry.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServiceRegistry.java index cc518e9988b..cb7c6fcc252 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServiceRegistry.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServiceRegistry.java @@ -21,109 +21,108 @@ */ public class ResteasyWadlServiceRegistry { - private ResourceMethodRegistry registry; + private ResourceMethodRegistry registry; - public ResteasyProviderFactory getProviderFactory() { - return providerFactory; - } + public ResteasyProviderFactory getProviderFactory() { + return providerFactory; + } - private ResteasyProviderFactory providerFactory; + private ResteasyProviderFactory providerFactory; - private ResteasyWadlServiceRegistry parent; + private ResteasyWadlServiceRegistry parent; - private Map resources; + private Map resources; - private List locators; + private List locators; - private ResourceLocator locator; + private ResourceLocator locator; - private String uri; + private String uri; - private String functionPrefix; + private String functionPrefix; - public ResteasyWadlServiceRegistry(ResteasyWadlServiceRegistry parent, ResourceMethodRegistry registry, + public ResteasyWadlServiceRegistry(ResteasyWadlServiceRegistry parent, ResourceMethodRegistry registry, ResteasyProviderFactory providerFactory, ResourceLocator locator) { - this.parent = parent; - this.registry = registry; - this.providerFactory = providerFactory; - this.locator = locator; - if (locator != null) { - Method method = locator.getMethod(); - Path methodPath = method.getAnnotation(Path.class); - Class declaringClass = method.getDeclaringClass(); - Path classPath = declaringClass.getAnnotation(Path.class); - this.uri = ResteasyWadlMethodMetaData.appendURIFragments(parent, classPath, methodPath); - if (parent.isRoot()) - this.functionPrefix = declaringClass.getSimpleName() + "." + method.getName(); - else - this.functionPrefix = parent.getFunctionPrefix() + "." + method.getName(); - } - scanRegistry(); - } - - private void scanRegistry() { - resources = new HashMap(); - - locators = new ArrayList(); - - for (Map.Entry> entry : registry.getBounded().entrySet()) { - List invokers = entry.getValue(); - for (ResourceInvoker invoker : invokers) { - if (invoker instanceof ResourceMethodInvoker) { - ResteasyWadlMethodMetaData methodMetaData = new ResteasyWadlMethodMetaData(this, (ResourceMethodInvoker) invoker); - ResteasyWadlResourceMetaData resourceMetaData = resources.get(methodMetaData.getKlassUri()); - if (resourceMetaData == null) { - resourceMetaData = new ResteasyWadlResourceMetaData(methodMetaData.getKlassUri()); - resources.put(methodMetaData.getKlassUri(), resourceMetaData); - } - resourceMetaData.addMethodMetaData(methodMetaData); - } else if (invoker instanceof ResourceLocator) { - ResourceLocator locator = (ResourceLocator) invoker; - Method method = locator.getMethod(); - Class locatorType = method.getReturnType(); - Class[] locatorResourceTypes = GetRestful.getSubResourceClasses(locatorType); - for (Class locatorResourceType : locatorResourceTypes) { - if (locatorResourceType == null) { - // FIXME: we could generate an error for the client, which would be more informative than - // just logging this - LogMessages.LOGGER.warn(Messages.MESSAGES.impossibleToGenerateWADL(method.getDeclaringClass().getName(), method.getName())); // skip this - continue; - } - ResourceMethodRegistry locatorRegistry = new ResourceMethodRegistry(providerFactory); - locatorRegistry.addResourceFactory(null, null, locatorResourceType); - locators.add(new ResteasyWadlServiceRegistry(this, locatorRegistry, providerFactory, locator)); - } - } + this.parent = parent; + this.registry = registry; + this.providerFactory = providerFactory; + this.locator = locator; + if (locator != null) { + Method method = locator.getMethod(); + Path methodPath = method.getAnnotation(Path.class); + Class declaringClass = method.getDeclaringClass(); + Path classPath = declaringClass.getAnnotation(Path.class); + this.uri = ResteasyWadlMethodMetaData.appendURIFragments(parent, classPath, methodPath); + if (parent.isRoot()) + this.functionPrefix = declaringClass.getSimpleName() + "." + method.getName(); + else + this.functionPrefix = parent.getFunctionPrefix() + "." + method.getName(); + } + scanRegistry(); + } + + private void scanRegistry() { + resources = new HashMap(); + + locators = new ArrayList(); + + for (Map.Entry> entry : registry.getBounded().entrySet()) { + List invokers = entry.getValue(); + for (ResourceInvoker invoker : invokers) { + if (invoker instanceof ResourceMethodInvoker) { + ResteasyWadlMethodMetaData methodMetaData = new ResteasyWadlMethodMetaData(this, (ResourceMethodInvoker) invoker); + ResteasyWadlResourceMetaData resourceMetaData = resources.get(methodMetaData.getKlassUri()); + if (resourceMetaData == null) { + resourceMetaData = new ResteasyWadlResourceMetaData(methodMetaData.getKlassUri()); + resources.put(methodMetaData.getKlassUri(), resourceMetaData); + } + resourceMetaData.addMethodMetaData(methodMetaData); + } else if (invoker instanceof ResourceLocator) { + ResourceLocator locator = (ResourceLocator) invoker; + Method method = locator.getMethod(); + Class locatorType = method.getReturnType(); + Class[] locatorResourceTypes = GetRestful.getSubResourceClasses(locatorType); + for (Class locatorResourceType : locatorResourceTypes) { + if (locatorResourceType == null) { + // FIXME: we could generate an error for the client, which would be more informative than + // just logging this + LogMessages.LOGGER.warn(Messages.MESSAGES.impossibleToGenerateWADL(method.getDeclaringClass().getName(), method.getName())); // skip this + continue; + } + ResourceMethodRegistry locatorRegistry = new ResourceMethodRegistry(providerFactory); + locatorRegistry.addResourceFactory(null, null, locatorResourceType); + locators.add(new ResteasyWadlServiceRegistry(this, locatorRegistry, providerFactory, locator)); + } } - } - } + } + } + } - public Map getResources() { - return resources; - } + public Map getResources() { + return resources; + } - public List getLocators() { - return locators; - } + public List getLocators() { + return locators; + } - public String getUri() { - return uri; - } + public String getUri() { + return uri; + } - public boolean isRoot() { - return parent == null; - } + public boolean isRoot() { + return parent == null; + } - public String getFunctionPrefix() { - return functionPrefix; - } + public String getFunctionPrefix() { + return functionPrefix; + } - public void collectResourceMethodsUntilRoot(List methods) { - if (isRoot()) - return; - methods.add(locator.getMethod()); - parent.collectResourceMethodsUntilRoot(methods); - } + public void collectResourceMethodsUntilRoot(List methods) { + if (isRoot()) + return; + methods.add(locator.getMethod()); + parent.collectResourceMethodsUntilRoot(methods); + } } - diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServlet.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServlet.java index 1725b9948d1..f2de01326ef 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServlet.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServlet.java @@ -21,55 +21,55 @@ */ public class ResteasyWadlServlet extends HttpServlet { - private Map services; + private Map services; - private ResteasyWadlServletWriter apiWriter = new ResteasyWadlServletWriter(); + private ResteasyWadlServletWriter apiWriter = new ResteasyWadlServletWriter(); - @Override - public void init(ServletConfig config) throws ServletException { - super.init(config); - LogMessages.LOGGER.debug(Messages.MESSAGES.loadingResteasyWadlServlet()); + @Override + public void init(ServletConfig config) throws ServletException { + super.init(config); + LogMessages.LOGGER.debug(Messages.MESSAGES.loadingResteasyWadlServlet()); - scanResources(); + scanResources(); - LogMessages.LOGGER.debug(Messages.MESSAGES.resteasyWadlServletLoaded()); + LogMessages.LOGGER.debug(Messages.MESSAGES.resteasyWadlServletLoaded()); - // make it possible to get to us for rescanning - ServletContext servletContext = config.getServletContext(); - servletContext.setAttribute(getClass().getName(), this); - } + // make it possible to get to us for rescanning + ServletContext servletContext = config.getServletContext(); + servletContext.setAttribute(getClass().getName(), this); + } - @Override - protected void service(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - String pathInfo = req.getPathInfo(); - String uri = req.getRequestURL().toString(); - uri = uri.substring(0, uri.length() - req.getServletPath().length()); - LogMessages.LOGGER.debug(Messages.MESSAGES.servingPathInfo(pathInfo)); - LogMessages.LOGGER.debug(Messages.MESSAGES.query(req.getQueryString())); - if (this.services == null) scanResources(); - if (this.services == null) { - resp.sendError(503, Messages.MESSAGES.noResteasyDeployments()); - return; - } - resp.setContentType(MediaType.APPLICATION_XML); - this.apiWriter.writeWadl(uri, req, resp, services); - } + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + String pathInfo = req.getPathInfo(); + String uri = req.getRequestURL().toString(); + uri = uri.substring(0, uri.length() - req.getServletPath().length()); + LogMessages.LOGGER.debug(Messages.MESSAGES.servingPathInfo(pathInfo)); + LogMessages.LOGGER.debug(Messages.MESSAGES.query(req.getQueryString())); + if (this.services == null) scanResources(); + if (this.services == null) { + resp.sendError(503, Messages.MESSAGES.noResteasyDeployments()); + return; + } + resp.setContentType(MediaType.APPLICATION_XML); + this.apiWriter.writeWadl(uri, req, resp, services); + } - public void scanResources() { + public void scanResources() { - ServletConfig config = getServletConfig(); - ServletContext servletContext = config.getServletContext(); + ServletConfig config = getServletConfig(); + ServletContext servletContext = config.getServletContext(); - @SuppressWarnings(value = "unchecked") - Map deployments = (Map) servletContext.getAttribute(ResteasyContextParameters.RESTEASY_DEPLOYMENTS); - if (deployments == null) return; - synchronized (this) { - services = new HashMap(); - for (Map.Entry entry : deployments.entrySet()) { - services.put(entry.getKey(), ResteasyWadlGenerator.generateServiceRegistry(entry.getValue())); - } - } - } + @SuppressWarnings(value = "unchecked") + Map deployments = (Map) servletContext.getAttribute(ResteasyContextParameters.RESTEASY_DEPLOYMENTS); + if (deployments == null) return; + synchronized (this) { + services = new HashMap(); + for (Map.Entry entry : deployments.entrySet()) { + services.put(entry.getKey(), ResteasyWadlGenerator.generateServiceRegistry(entry.getValue())); + } + } + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServletWriter.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServletWriter.java index 54071cb8822..25d3e2bb9d1 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServletWriter.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlServletWriter.java @@ -12,26 +12,26 @@ */ public class ResteasyWadlServletWriter extends ResteasyWadlWriter { - public void writeWadl(String base, HttpServletResponse resp, Map serviceRegistries) - throws IOException { - try { - ServletOutputStream output = resp.getOutputStream(); - - byte[] bytes = getBytes(base, serviceRegistries); - resp.setContentLength(bytes.length); - output.write(bytes); - output.flush(); - output.close(); - } catch (JAXBException e) { - throw new IOException(e); - } - } - - - public void writeWadl(String base, HttpServletRequest req, HttpServletResponse resp, Map serviceRegistries) - throws IOException { - writeWadl(base, resp, serviceRegistries); - } + public void writeWadl(String base, HttpServletResponse resp, Map serviceRegistries) + throws IOException { + try { + ServletOutputStream output = resp.getOutputStream(); + + byte[] bytes = getBytes(base, serviceRegistries); + resp.setContentLength(bytes.length); + output.write(bytes); + output.flush(); + output.close(); + } catch (JAXBException e) { + throw new IOException(e); + } + } + + + public void writeWadl(String base, HttpServletRequest req, HttpServletResponse resp, Map serviceRegistries) + throws IOException { + writeWadl(base, resp, serviceRegistries); + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlWriter.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlWriter.java index 41c46dd64b9..1277f0613c8 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlWriter.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/ResteasyWadlWriter.java @@ -31,205 +31,205 @@ */ public class ResteasyWadlWriter { - public byte[] getBytes(String base, Map serviceRegistries) throws JAXBException { - StringWriter stringWriter = getStringWriter(base, serviceRegistries); - return stringWriter.toString().getBytes(); - } - - public StringWriter getStringWriter(String base, Map serviceRegistries) throws JAXBException { - ObjectFactory factory = new ObjectFactory(); - Application app = factory.createApplication(); - JAXBContext context = JAXBContext.newInstance(Application.class); - Marshaller marshaller = context.createMarshaller(); - - for (Map.Entry entry : serviceRegistries.entrySet()) { - String uri = base; - if (entry.getKey() != null) uri += entry.getKey(); - Resources resources = new Resources(); - resources.setBase(uri); - app.getResources().add(resources); - processWadl(entry.getValue(), resources); - } - - StringWriter stringWriter = new StringWriter(); - PrintWriter writer = new PrintWriter(stringWriter); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.marshal(app, writer); - return stringWriter; - } - - private void processWadl(ResteasyWadlServiceRegistry serviceRegistry, Resources root) throws JAXBException { - - for (Map.Entry resourceMetaDataEntry : serviceRegistry.getResources().entrySet()) { - LogMessages.LOGGER.debug(Messages.MESSAGES.path(resourceMetaDataEntry.getKey())); - Resource resourceClass = new Resource(); - - resourceClass.setPath(resourceMetaDataEntry.getKey()); - root.getResource().add(resourceClass); - - for (ResteasyWadlMethodMetaData methodMetaData : resourceMetaDataEntry.getValue().getMethodsMetaData()) { - Method method = new Method(); - - // First we need to check whether @Path annotation exists in a method. - // If the @Path annotation exists, we need to create a resource for it. - if (methodMetaData.getMethodUri() != null) { - Resource methodResource = new Resource(); - methodResource.setPath(methodMetaData.getMethodUri()); - methodResource.getMethodOrResource().add(method); - resourceClass.getMethodOrResource().add(methodResource); - // add params into method resource - processMethodParams(methodResource, methodMetaData, method); - } else { - // register method into resource - resourceClass.getMethodOrResource().add(method); - // we need to check whether the method have parameters or not. - // params belong to the resource of the method - processMethodParams(resourceClass, methodMetaData, method); - } - - // method name = {GET, POST, DELETE, ...} - for (String name : methodMetaData.getHttpMethods()) { - method.setName(name); - } - - // method id = method name - method.setId(methodMetaData.getMethod().getName()); - - // process response of method - Response response = createResponse(serviceRegistry, methodMetaData); - method.getResponse().add(response); + public byte[] getBytes(String base, Map serviceRegistries) throws JAXBException { + StringWriter stringWriter = getStringWriter(base, serviceRegistries); + return stringWriter.toString().getBytes(); + } + + public StringWriter getStringWriter(String base, Map serviceRegistries) throws JAXBException { + ObjectFactory factory = new ObjectFactory(); + Application app = factory.createApplication(); + JAXBContext context = JAXBContext.newInstance(Application.class); + Marshaller marshaller = context.createMarshaller(); + + for (Map.Entry entry : serviceRegistries.entrySet()) { + String uri = base; + if (entry.getKey() != null) uri += entry.getKey(); + Resources resources = new Resources(); + resources.setBase(uri); + app.getResources().add(resources); + processWadl(entry.getValue(), resources); + } + + StringWriter stringWriter = new StringWriter(); + PrintWriter writer = new PrintWriter(stringWriter); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + marshaller.marshal(app, writer); + return stringWriter; + } + + private void processWadl(ResteasyWadlServiceRegistry serviceRegistry, Resources root) throws JAXBException { + + for (Map.Entry resourceMetaDataEntry : serviceRegistry.getResources().entrySet()) { + LogMessages.LOGGER.debug(Messages.MESSAGES.path(resourceMetaDataEntry.getKey())); + Resource resourceClass = new Resource(); + + resourceClass.setPath(resourceMetaDataEntry.getKey()); + root.getResource().add(resourceClass); + + for (ResteasyWadlMethodMetaData methodMetaData : resourceMetaDataEntry.getValue().getMethodsMetaData()) { + Method method = new Method(); + + // First we need to check whether @Path annotation exists in a method. + // If the @Path annotation exists, we need to create a resource for it. + if (methodMetaData.getMethodUri() != null) { + Resource methodResource = new Resource(); + methodResource.setPath(methodMetaData.getMethodUri()); + methodResource.getMethodOrResource().add(method); + resourceClass.getMethodOrResource().add(methodResource); + // add params into method resource + processMethodParams(methodResource, methodMetaData, method); + } else { + // register method into resource + resourceClass.getMethodOrResource().add(method); + // we need to check whether the method have parameters or not. + // params belong to the resource of the method + processMethodParams(resourceClass, methodMetaData, method); } - } - - for (ResteasyWadlServiceRegistry subService : serviceRegistry.getLocators()) - processWadl(subService, root); - } - - private void processMethodParams(Resource currentResourceClass, ResteasyWadlMethodMetaData methodMetaData, Method method) { - // process method parameters - Request request = new Request(); - - for (ResteasyWadlMethodParamMetaData paramMetaData : methodMetaData.getParameters()) { - Param param = createParam(currentResourceClass, method, paramMetaData, request); - } - } - - private Response createResponse(ResteasyWadlServiceRegistry serviceRegistry, ResteasyWadlMethodMetaData methodMetaData) { - Response response = new Response(); - - Class _type = methodMetaData.getMethod().getReturnType(); - Type _generic = methodMetaData.getMethod().getGenericReturnType(); - - MediaType mediaType = MediaType.WILDCARD_TYPE; - - if (methodMetaData.getProduces() != null) { - for (String produces : methodMetaData.getProduces()) { - for (String _produces : produces.split(",")) { - mediaType = MediaType.valueOf(_produces); - if (mediaType == null) { - mediaType = serviceRegistry.getProviderFactory().getConcreteMediaTypeFromMessageBodyWriters(_type, _generic, methodMetaData.getMethod().getAnnotations(), MediaType.WILDCARD_TYPE); - if (mediaType == null) - mediaType = MediaType.WILDCARD_TYPE; - } - Representation representation = createRepresentation(mediaType); - response.getRepresentation().add(representation); - } + + // method name = {GET, POST, DELETE, ...} + for (String name : methodMetaData.getHttpMethods()) { + method.setName(name); } - } - return response; - } - - private Param createParam(Resource currentResourceClass, Method method, ResteasyWadlMethodParamMetaData paramMetaData, Request request) { - Param param = new Param(); - setType(param, paramMetaData); - - // All the method's @PathParam belong to resource - if (paramMetaData.getParamType().equals(PATH_PARAMETER)) { - param.setStyle(ParamStyle.TEMPLATE); - param.setName(paramMetaData.getParamName()); - currentResourceClass.getParam().add(param); - } else if (paramMetaData.getParamType().equals(COOKIE_PARAMETER)) { - param.setStyle(ParamStyle.HEADER); - request.getParam().add(param); - param.setName("Cookie"); - param.setPath(paramMetaData.getParamName()); - method.setRequest(request); - } else if (paramMetaData.getParamType().equals(HEADER_PARAMETER)) { - param.setStyle(ParamStyle.HEADER); - request.getParam().add(param); - param.setName(paramMetaData.getParamName()); - method.setRequest(request); - } else if (paramMetaData.getParamType().equals(MATRIX_PARAMETER)) { - param.setStyle(ParamStyle.MATRIX); - param.setName(paramMetaData.getParamName()); - currentResourceClass.getParam().add(param); - } else if (paramMetaData.getParamType().equals(QUERY_PARAMETER)) { - param.setStyle(ParamStyle.QUERY); - request.getParam().add(param); - param.setName(paramMetaData.getParamName()); - method.setRequest(request); - } else if (paramMetaData.getParamType().equals(FORM_PARAMETER)) { - param.setStyle(ParamStyle.QUERY); - Representation formRepresentation = createFormRepresentation(request); - param.setName(paramMetaData.getParamName()); - formRepresentation.getParam().add(param); - method.setRequest(request); - } else if (paramMetaData.getParamType().equals(FORM)) { - param.setStyle(ParamStyle.QUERY); - Representation formRepresentation = createFormRepresentation(request); - param.setName(paramMetaData.getParamName()); - formRepresentation.getParam().add(param); - method.setRequest(request); - } - return param; - } - - private Representation createFormRepresentation(Request request) { - Representation formRepresentation = getRepresentationByMediaType(request.getRepresentation(), - MediaType.APPLICATION_FORM_URLENCODED_TYPE); - if (formRepresentation == null) { - formRepresentation = createRepresentation(MediaType.APPLICATION_FORM_URLENCODED_TYPE); - request.getRepresentation().add(formRepresentation); - } - return formRepresentation; - } - - private Representation createRepresentation(MediaType mediaType) { - Representation representation; - representation = new Representation(); - representation.setMediaType(mediaType.toString()); - return representation; - } - - private Representation getRepresentationByMediaType( - final List representations, MediaType mediaType) { - for (Representation representation : representations) { - if (mediaType.toString().equals(representation.getMediaType())) { - return representation; + + // method id = method name + method.setId(methodMetaData.getMethod().getName()); + + // process response of method + Response response = createResponse(serviceRegistry, methodMetaData); + method.getResponse().add(response); + } + } + + for (ResteasyWadlServiceRegistry subService : serviceRegistry.getLocators()) + processWadl(subService, root); + } + + private void processMethodParams(Resource currentResourceClass, ResteasyWadlMethodMetaData methodMetaData, Method method) { + // process method parameters + Request request = new Request(); + + for (ResteasyWadlMethodParamMetaData paramMetaData : methodMetaData.getParameters()) { + Param param = createParam(currentResourceClass, method, paramMetaData, request); + } + } + + private Response createResponse(ResteasyWadlServiceRegistry serviceRegistry, ResteasyWadlMethodMetaData methodMetaData) { + Response response = new Response(); + + Class _type = methodMetaData.getMethod().getReturnType(); + Type _generic = methodMetaData.getMethod().getGenericReturnType(); + + MediaType mediaType = MediaType.WILDCARD_TYPE; + + if (methodMetaData.getProduces() != null) { + for (String produces : methodMetaData.getProduces()) { + for (String _produces : produces.split(",")) { + mediaType = MediaType.valueOf(_produces); + if (mediaType == null) { + mediaType = serviceRegistry.getProviderFactory().getConcreteMediaTypeFromMessageBodyWriters(_type, _generic, methodMetaData.getMethod().getAnnotations(), MediaType.WILDCARD_TYPE); + if (mediaType == null) + mediaType = MediaType.WILDCARD_TYPE; + } + Representation representation = createRepresentation(mediaType); + response.getRepresentation().add(representation); } - } - return null; - } - - private void setType(Param param, ResteasyWadlMethodParamMetaData paramMetaData) { - if (paramMetaData.getType().equals(int.class) || paramMetaData.getType().equals(Integer.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs")); - } else if (paramMetaData.getType().equals(boolean.class) || paramMetaData.getType().equals(Boolean.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs")); - } else if (paramMetaData.getType().equals(long.class) || paramMetaData.getType().equals(Long.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs")); - } else if (paramMetaData.getType().equals(short.class) || paramMetaData.getType().equals(Short.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs")); - } else if (paramMetaData.getType().equals(byte.class) || paramMetaData.getType().equals(Byte.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs")); - } else if (paramMetaData.getType().equals(float.class) || paramMetaData.getType().equals(Float.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs")); - } else if (paramMetaData.getType().equals(double.class) || paramMetaData.getType().equals(Double.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs")); - } else if (paramMetaData.getType().equals(Map.class) || paramMetaData.getType().equals(List.class)) { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "complex", "xs")); - } else { - param.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs")); - } - } + } + } + return response; + } + + private Param createParam(Resource currentResourceClass, Method method, ResteasyWadlMethodParamMetaData paramMetaData, Request request) { + Param param = new Param(); + setType(param, paramMetaData); + + // All the method's @PathParam belong to resource + if (paramMetaData.getParamType().equals(PATH_PARAMETER)) { + param.setStyle(ParamStyle.TEMPLATE); + param.setName(paramMetaData.getParamName()); + currentResourceClass.getParam().add(param); + } else if (paramMetaData.getParamType().equals(COOKIE_PARAMETER)) { + param.setStyle(ParamStyle.HEADER); + request.getParam().add(param); + param.setName("Cookie"); + param.setPath(paramMetaData.getParamName()); + method.setRequest(request); + } else if (paramMetaData.getParamType().equals(HEADER_PARAMETER)) { + param.setStyle(ParamStyle.HEADER); + request.getParam().add(param); + param.setName(paramMetaData.getParamName()); + method.setRequest(request); + } else if (paramMetaData.getParamType().equals(MATRIX_PARAMETER)) { + param.setStyle(ParamStyle.MATRIX); + param.setName(paramMetaData.getParamName()); + currentResourceClass.getParam().add(param); + } else if (paramMetaData.getParamType().equals(QUERY_PARAMETER)) { + param.setStyle(ParamStyle.QUERY); + request.getParam().add(param); + param.setName(paramMetaData.getParamName()); + method.setRequest(request); + } else if (paramMetaData.getParamType().equals(FORM_PARAMETER)) { + param.setStyle(ParamStyle.QUERY); + Representation formRepresentation = createFormRepresentation(request); + param.setName(paramMetaData.getParamName()); + formRepresentation.getParam().add(param); + method.setRequest(request); + } else if (paramMetaData.getParamType().equals(FORM)) { + param.setStyle(ParamStyle.QUERY); + Representation formRepresentation = createFormRepresentation(request); + param.setName(paramMetaData.getParamName()); + formRepresentation.getParam().add(param); + method.setRequest(request); + } + return param; + } + + private Representation createFormRepresentation(Request request) { + Representation formRepresentation = getRepresentationByMediaType(request.getRepresentation(), + MediaType.APPLICATION_FORM_URLENCODED_TYPE); + if (formRepresentation == null) { + formRepresentation = createRepresentation(MediaType.APPLICATION_FORM_URLENCODED_TYPE); + request.getRepresentation().add(formRepresentation); + } + return formRepresentation; + } + + private Representation createRepresentation(MediaType mediaType) { + Representation representation; + representation = new Representation(); + representation.setMediaType(mediaType.toString()); + return representation; + } + + private Representation getRepresentationByMediaType( + final List representations, MediaType mediaType) { + for (Representation representation : representations) { + if (mediaType.toString().equals(representation.getMediaType())) { + return representation; + } + } + return null; + } + + private void setType(Param param, ResteasyWadlMethodParamMetaData paramMetaData) { + if (paramMetaData.getType().equals(int.class) || paramMetaData.getType().equals(Integer.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "int", "xs")); + } else if (paramMetaData.getType().equals(boolean.class) || paramMetaData.getType().equals(Boolean.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs")); + } else if (paramMetaData.getType().equals(long.class) || paramMetaData.getType().equals(Long.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs")); + } else if (paramMetaData.getType().equals(short.class) || paramMetaData.getType().equals(Short.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs")); + } else if (paramMetaData.getType().equals(byte.class) || paramMetaData.getType().equals(Byte.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs")); + } else if (paramMetaData.getType().equals(float.class) || paramMetaData.getType().equals(Float.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs")); + } else if (paramMetaData.getType().equals(double.class) || paramMetaData.getType().equals(Double.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs")); + } else if (paramMetaData.getType().equals(Map.class) || paramMetaData.getType().equals(List.class)) { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "complex", "xs")); + } else { + param.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs")); + } + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Application.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Application.java index 43dfd7e939d..fc4b2d2186e 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Application.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Application.java @@ -50,170 +50,170 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "doc", - "grammars", - "resources", - "resourceTypeOrMethodOrRepresentation", - "any" + "doc", + "grammars", + "resources", + "resourceTypeOrMethodOrRepresentation", + "any" }) @XmlRootElement(name = "application") public class Application { - protected List doc; - protected Grammars grammars; - protected List resources; - @XmlElements({ - @XmlElement(name = "resource_type", type = ResourceType.class), - @XmlElement(name = "method", type = Method.class), - @XmlElement(name = "representation", type = Representation.class), - @XmlElement(name = "param", type = Param.class) - }) - protected List resourceTypeOrMethodOrRepresentation; - @XmlAnyElement(lax = true) - protected List any; + protected List doc; + protected Grammars grammars; + protected List resources; + @XmlElements({ + @XmlElement(name = "resource_type", type = ResourceType.class), + @XmlElement(name = "method", type = Method.class), + @XmlElement(name = "representation", type = Representation.class), + @XmlElement(name = "param", type = Param.class) + }) + protected List resourceTypeOrMethodOrRepresentation; + @XmlAnyElement(lax = true) + protected List any; - /** - * Gets the value of the doc property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the doc property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getDoc().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Doc } - * - * - */ - public List getDoc() { - if (doc == null) { - doc = new ArrayList(); - } - return this.doc; - } + /** + * Gets the value of the doc property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the doc property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getDoc().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Doc } + * + * + */ + public List getDoc() { + if (doc == null) { + doc = new ArrayList(); + } + return this.doc; + } - /** - * Gets the value of the grammars property. - * - * @return - * possible object is - * {@link Grammars } - * - */ - public Grammars getGrammars() { - return grammars; - } + /** + * Gets the value of the grammars property. + * + * @return + * possible object is + * {@link Grammars } + * + */ + public Grammars getGrammars() { + return grammars; + } - /** - * Sets the value of the grammars property. - * - * @param value - * allowed object is - * {@link Grammars } - * - */ - public void setGrammars(Grammars value) { - this.grammars = value; - } + /** + * Sets the value of the grammars property. + * + * @param value + * allowed object is + * {@link Grammars } + * + */ + public void setGrammars(Grammars value) { + this.grammars = value; + } - /** - * Gets the value of the resources property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the resources property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getResources().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Resources } - * - * - */ - public List getResources() { - if (resources == null) { - resources = new ArrayList(); - } - return this.resources; - } + /** + * Gets the value of the resources property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the resources property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getResources().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Resources } + * + * + */ + public List getResources() { + if (resources == null) { + resources = new ArrayList(); + } + return this.resources; + } - /** - * Gets the value of the resourceTypeOrMethodOrRepresentation property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the resourceTypeOrMethodOrRepresentation property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getResourceTypeOrMethodOrRepresentation().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link ResourceType } - * {@link Method } - * {@link Representation } - * {@link Param } - * - * - */ - public List getResourceTypeOrMethodOrRepresentation() { - if (resourceTypeOrMethodOrRepresentation == null) { - resourceTypeOrMethodOrRepresentation = new ArrayList(); - } - return this.resourceTypeOrMethodOrRepresentation; - } + /** + * Gets the value of the resourceTypeOrMethodOrRepresentation property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the resourceTypeOrMethodOrRepresentation property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getResourceTypeOrMethodOrRepresentation().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link ResourceType } + * {@link Method } + * {@link Representation } + * {@link Param } + * + * + */ + public List getResourceTypeOrMethodOrRepresentation() { + if (resourceTypeOrMethodOrRepresentation == null) { + resourceTypeOrMethodOrRepresentation = new ArrayList(); + } + return this.resourceTypeOrMethodOrRepresentation; + } - /** - * Gets the value of the any property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the any property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAny().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Element } - * {@link Object } - * - * - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getAny().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Element } + * {@link Object } + * + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Doc.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Doc.java index 95da348a533..488eaed9448 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Doc.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Doc.java @@ -48,116 +48,116 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "content" + "content" }) @XmlRootElement(name = "doc") public class Doc { - @XmlMixed - @XmlAnyElement(lax = true) - protected List content; - @XmlAttribute(name = "title") - protected String title; - @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") - protected String lang; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); + @XmlMixed + @XmlAnyElement(lax = true) + protected List content; + @XmlAttribute(name = "title") + protected String title; + @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") + protected String lang; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); - /** - * Gets the value of the content property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the content property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getContent().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Element } - * {@link String } - * {@link Object } - * - * - */ - public List getContent() { - if (content == null) { - content = new ArrayList(); - } - return this.content; - } + /** + * Gets the value of the content property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the content property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getContent().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Element } + * {@link String } + * {@link Object } + * + * + */ + public List getContent() { + if (content == null) { + content = new ArrayList(); + } + return this.content; + } - /** - * Gets the value of the title property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTitle() { - return title; - } + /** + * Gets the value of the title property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTitle() { + return title; + } - /** - * Sets the value of the title property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTitle(String value) { - this.title = value; - } + /** + * Sets the value of the title property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTitle(String value) { + this.title = value; + } - /** - * Gets the value of the lang property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getLang() { - return lang; - } + /** + * Gets the value of the lang property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLang() { + return lang; + } - /** - * Sets the value of the lang property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setLang(String value) { - this.lang = value; - } + /** + * Sets the value of the lang property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLang(String value) { + this.lang = value; + } - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } + /** + * Gets a map that contains attributes that aren't bound to any typed property on this class. + * + *

+ * the map is keyed by the name of the attribute and + * the value is the string value of the attribute. + * + * the map returned by this method is live, and you can add new attribute + * by updating the map directly. Because of this design, there's no setter. + * + * + * @return + * always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Grammars.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Grammars.java index 84f3a39adb6..38fcd50bfdc 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Grammars.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Grammars.java @@ -41,104 +41,104 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "doc", - "include", - "any" + "doc", + "include", + "any" }) @XmlRootElement(name = "grammars") public class Grammars { - protected List doc; - protected List include; - @XmlAnyElement(lax = true) - protected List any; + protected List doc; + protected List include; + @XmlAnyElement(lax = true) + protected List any; - /** - * Gets the value of the doc property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the doc property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getDoc().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Doc } - * - * - */ - public List getDoc() { - if (doc == null) { - doc = new ArrayList(); - } - return this.doc; - } + /** + * Gets the value of the doc property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the doc property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getDoc().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Doc } + * + * + */ + public List getDoc() { + if (doc == null) { + doc = new ArrayList(); + } + return this.doc; + } - /** - * Gets the value of the include property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the include property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getInclude().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Include } - * - * - */ - public List getInclude() { - if (include == null) { - include = new ArrayList(); - } - return this.include; - } + /** + * Gets the value of the include property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the include property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getInclude().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Include } + * + * + */ + public List getInclude() { + if (include == null) { + include = new ArrayList(); + } + return this.include; + } - /** - * Gets the value of the any property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the any property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAny().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Element } - * {@link Object } - * - * - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getAny().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Element } + * {@link Object } + * + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/HTTPMethods.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/HTTPMethods.java index cc4094b7ba3..4620e1d24d3 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/HTTPMethods.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/HTTPMethods.java @@ -34,18 +34,18 @@ @XmlEnum public enum HTTPMethods { - GET, - POST, - PUT, - HEAD, - DELETE; - - public String value() { - return name(); - } - - public static HTTPMethods fromValue(String v) { - return valueOf(v); - } + GET, + POST, + PUT, + HEAD, + DELETE; + + public String value() { + return name(); + } + + public static HTTPMethods fromValue(String v) { + return valueOf(v); + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Include.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Include.java index c9579bf0509..810ec55eadb 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Include.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Include.java @@ -45,87 +45,87 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "doc" + "doc" }) @XmlRootElement(name = "include") public class Include { - protected List doc; - @XmlAttribute(name = "href") - @XmlSchemaType(name = "anyURI") - protected String href; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); + protected List doc; + @XmlAttribute(name = "href") + @XmlSchemaType(name = "anyURI") + protected String href; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); - /** - * Gets the value of the doc property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the doc property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getDoc().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Doc } - * - * - */ - public List getDoc() { - if (doc == null) { - doc = new ArrayList(); - } - return this.doc; - } + /** + * Gets the value of the doc property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the doc property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getDoc().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Doc } + * + * + */ + public List getDoc() { + if (doc == null) { + doc = new ArrayList(); + } + return this.doc; + } - /** - * Gets the value of the href property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getHref() { - return href; - } + /** + * Gets the value of the href property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getHref() { + return href; + } - /** - * Sets the value of the href property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setHref(String value) { - this.href = value; - } + /** + * Sets the value of the href property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setHref(String value) { + this.href = value; + } - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } + /** + * Gets a map that contains attributes that aren't bound to any typed property on this class. + * + *

+ * the map is keyed by the name of the attribute and + * the value is the string value of the attribute. + * + * the map returned by this method is live, and you can add new attribute + * by updating the map directly. Because of this design, there's no setter. + * + * + * @return + * always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Link.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Link.java index e0bf2f37127..5c81bb48b75 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Link.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Link.java @@ -52,176 +52,176 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "doc", - "any" + "doc", + "any" }) @XmlRootElement(name = "link") public class Link { - protected List doc; - @XmlAnyElement(lax = true) - protected List any; - @XmlAttribute(name = "resource_type") - @XmlSchemaType(name = "anyURI") - protected String resourceType; - @XmlAttribute(name = "rel") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "token") - protected String rel; - @XmlAttribute(name = "rev") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlSchemaType(name = "token") - protected String rev; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); - - /** - * Gets the value of the doc property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the doc property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getDoc().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Doc } - * - * - */ - public List getDoc() { - if (doc == null) { - doc = new ArrayList(); - } - return this.doc; - } - - /** - * Gets the value of the any property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the any property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAny().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Element } - * {@link Object } - * - * - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } - - /** - * Gets the value of the resourceType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getResourceType() { - return resourceType; - } - - /** - * Sets the value of the resourceType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setResourceType(String value) { - this.resourceType = value; - } - - /** - * Gets the value of the rel property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRel() { - return rel; - } - - /** - * Sets the value of the rel property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRel(String value) { - this.rel = value; - } - - /** - * Gets the value of the rev property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRev() { - return rev; - } - - /** - * Sets the value of the rev property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRev(String value) { - this.rev = value; - } - - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } + protected List doc; + @XmlAnyElement(lax = true) + protected List any; + @XmlAttribute(name = "resource_type") + @XmlSchemaType(name = "anyURI") + protected String resourceType; + @XmlAttribute(name = "rel") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "token") + protected String rel; + @XmlAttribute(name = "rev") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlSchemaType(name = "token") + protected String rev; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); + + /** + * Gets the value of the doc property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the doc property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getDoc().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Doc } + * + * + */ + public List getDoc() { + if (doc == null) { + doc = new ArrayList(); + } + return this.doc; + } + + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getAny().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Element } + * {@link Object } + * + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } + + /** + * Gets the value of the resourceType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResourceType() { + return resourceType; + } + + /** + * Sets the value of the resourceType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResourceType(String value) { + this.resourceType = value; + } + + /** + * Gets the value of the rel property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRel() { + return rel; + } + + /** + * Sets the value of the rel property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRel(String value) { + this.rel = value; + } + + /** + * Gets the value of the rev property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRev() { + return rev; + } + + /** + * Sets the value of the rev property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRev(String value) { + this.rev = value; + } + + /** + * Gets a map that contains attributes that aren't bound to any typed property on this class. + * + *

+ * the map is keyed by the name of the attribute and + * the value is the string value of the attribute. + * + * the map returned by this method is live, and you can add new attribute + * by updating the map directly. Because of this design, there's no setter. + * + * + * @return + * always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Method.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Method.java index 1b9c6b0e1ae..49d7988fd87 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Method.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Method.java @@ -55,232 +55,232 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "doc", - "request", - "response", - "any" + "doc", + "request", + "response", + "any" }) @XmlRootElement(name = "method") public class Method { - protected List doc; - protected Request request; - protected List response; - @XmlAnyElement(lax = true) - protected List any; - @XmlAttribute(name = "id") - @XmlJavaTypeAdapter(CollapsedStringAdapter.class) - @XmlID - @XmlSchemaType(name = "ID") - protected String id; - @XmlAttribute(name = "name") - protected String name; - @XmlAttribute(name = "href") - @XmlSchemaType(name = "anyURI") - protected String href; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); + protected List doc; + protected Request request; + protected List response; + @XmlAnyElement(lax = true) + protected List any; + @XmlAttribute(name = "id") + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + protected String id; + @XmlAttribute(name = "name") + protected String name; + @XmlAttribute(name = "href") + @XmlSchemaType(name = "anyURI") + protected String href; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); - /** - * Gets the value of the doc property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the doc property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getDoc().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Doc } - * - * - */ - public List getDoc() { - if (doc == null) { - doc = new ArrayList(); - } - return this.doc; - } + /** + * Gets the value of the doc property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the doc property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getDoc().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Doc } + * + * + */ + public List getDoc() { + if (doc == null) { + doc = new ArrayList(); + } + return this.doc; + } - /** - * Gets the value of the request property. - * - * @return - * possible object is - * {@link Request } - * - */ - public Request getRequest() { - return request; - } + /** + * Gets the value of the request property. + * + * @return + * possible object is + * {@link Request } + * + */ + public Request getRequest() { + return request; + } - /** - * Sets the value of the request property. - * - * @param value - * allowed object is - * {@link Request } - * - */ - public void setRequest(Request value) { - this.request = value; - } + /** + * Sets the value of the request property. + * + * @param value + * allowed object is + * {@link Request } + * + */ + public void setRequest(Request value) { + this.request = value; + } - /** - * Gets the value of the response property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the response property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getResponse().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Response } - * - * - */ - public List getResponse() { - if (response == null) { - response = new ArrayList(); - } - return this.response; - } + /** + * Gets the value of the response property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the response property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getResponse().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Response } + * + * + */ + public List getResponse() { + if (response == null) { + response = new ArrayList(); + } + return this.response; + } - /** - * Gets the value of the any property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the any property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAny().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Element } - * {@link Object } - * - * - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getAny().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Element } + * {@link Object } + * + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } - /** - * Gets the value of the id property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getId() { - return id; - } + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } - /** - * Sets the value of the id property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setId(String value) { - this.id = value; - } + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } - /** - * Gets the value of the name property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getName() { - return name; - } + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } - /** - * Sets the value of the name property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setName(String value) { - this.name = value; - } + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } - /** - * Gets the value of the href property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getHref() { - return href; - } + /** + * Gets the value of the href property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getHref() { + return href; + } - /** - * Sets the value of the href property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setHref(String value) { - this.href = value; - } + /** + * Sets the value of the href property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setHref(String value) { + this.href = value; + } - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } + /** + * Gets a map that contains attributes that aren't bound to any typed property on this class. + * + *

+ * the map is keyed by the name of the attribute and + * the value is the string value of the attribute. + * + * the map returned by this method is live, and you can add new attribute + * by updating the map directly. Because of this design, there's no setter. + * + * + * @return + * always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/ObjectFactory.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/ObjectFactory.java index 9708b0d6e13..841cc352c60 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/ObjectFactory.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/ObjectFactory.java @@ -29,123 +29,123 @@ public class ObjectFactory { - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: net.java.dev.wadl._2009._02 - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Include } - * - */ - public Include createInclude() { - return new Include(); - } - - /** - * Create an instance of {@link Doc } - * - */ - public Doc createDoc() { - return new Doc(); - } - - /** - * Create an instance of {@link Request } - * - */ - public Request createRequest() { - return new Request(); - } - - /** - * Create an instance of {@link Param } - * - */ - public Param createParam() { - return new Param(); - } - - /** - * Create an instance of {@link Option } - * - */ - public Option createOption() { - return new Option(); - } - - /** - * Create an instance of {@link Link } - * - */ - public Link createLink() { - return new Link(); - } - - /** - * Create an instance of {@link Representation } - * - */ - public Representation createRepresentation() { - return new Representation(); - } - - /** - * Create an instance of {@link Method } - * - */ - public Method createMethod() { - return new Method(); - } - - /** - * Create an instance of {@link Response } - * - */ - public Response createResponse() { - return new Response(); - } - - /** - * Create an instance of {@link Resource } - * - */ - public Resource createResource() { - return new Resource(); - } - - /** - * Create an instance of {@link ResourceType } - * - */ - public ResourceType createResourceType() { - return new ResourceType(); - } - - /** - * Create an instance of {@link Resources } - * - */ - public Resources createResources() { - return new Resources(); - } - - /** - * Create an instance of {@link Application } - * - */ - public Application createApplication() { - return new Application(); - } - - /** - * Create an instance of {@link Grammars } - * - */ - public Grammars createGrammars() { - return new Grammars(); - } + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: net.java.dev.wadl._2009._02 + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link Include } + * + */ + public Include createInclude() { + return new Include(); + } + + /** + * Create an instance of {@link Doc } + * + */ + public Doc createDoc() { + return new Doc(); + } + + /** + * Create an instance of {@link Request } + * + */ + public Request createRequest() { + return new Request(); + } + + /** + * Create an instance of {@link Param } + * + */ + public Param createParam() { + return new Param(); + } + + /** + * Create an instance of {@link Option } + * + */ + public Option createOption() { + return new Option(); + } + + /** + * Create an instance of {@link Link } + * + */ + public Link createLink() { + return new Link(); + } + + /** + * Create an instance of {@link Representation } + * + */ + public Representation createRepresentation() { + return new Representation(); + } + + /** + * Create an instance of {@link Method } + * + */ + public Method createMethod() { + return new Method(); + } + + /** + * Create an instance of {@link Response } + * + */ + public Response createResponse() { + return new Response(); + } + + /** + * Create an instance of {@link Resource } + * + */ + public Resource createResource() { + return new Resource(); + } + + /** + * Create an instance of {@link ResourceType } + * + */ + public ResourceType createResourceType() { + return new ResourceType(); + } + + /** + * Create an instance of {@link Resources } + * + */ + public Resources createResources() { + return new Resources(); + } + + /** + * Create an instance of {@link Application } + * + */ + public Application createApplication() { + return new Application(); + } + + /** + * Create an instance of {@link Grammars } + * + */ + public Grammars createGrammars() { + return new Grammars(); + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Option.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Option.java index 31e4f2ed2a5..87a3a176b0d 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Option.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Option.java @@ -48,145 +48,145 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "doc", - "any" + "doc", + "any" }) @XmlRootElement(name = "option") public class Option { - protected List doc; - @XmlAnyElement(lax = true) - protected List any; - @XmlAttribute(name = "value", required = true) - protected String value; - @XmlAttribute(name = "mediaType") - protected String mediaType; - @XmlAnyAttribute - private Map otherAttributes = new HashMap(); + protected List doc; + @XmlAnyElement(lax = true) + protected List any; + @XmlAttribute(name = "value", required = true) + protected String value; + @XmlAttribute(name = "mediaType") + protected String mediaType; + @XmlAnyAttribute + private Map otherAttributes = new HashMap(); - /** - * Gets the value of the doc property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the doc property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getDoc().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Doc } - * - * - */ - public List getDoc() { - if (doc == null) { - doc = new ArrayList(); - } - return this.doc; - } + /** + * Gets the value of the doc property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the doc property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getDoc().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Doc } + * + * + */ + public List getDoc() { + if (doc == null) { + doc = new ArrayList(); + } + return this.doc; + } - /** - * Gets the value of the any property. - * - *

- * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a set method for the any property. - * - *

- * For example, to add a new item, do as follows: - *

-     *    getAny().add(newItem);
-     * 
- * - * - *

- * Objects of the following type(s) are allowed in the list - * {@link Element } - * {@link Object } - * - * - */ - public List getAny() { - if (any == null) { - any = new ArrayList(); - } - return this.any; - } + /** + * Gets the value of the any property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the any property. + * + *

+ * For example, to add a new item, do as follows: + *

+    *    getAny().add(newItem);
+    * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Element } + * {@link Object } + * + * + */ + public List getAny() { + if (any == null) { + any = new ArrayList(); + } + return this.any; + } - /** - * Gets the value of the value property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getValue() { - return value; - } + /** + * Gets the value of the value property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getValue() { + return value; + } - /** - * Sets the value of the value property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setValue(String value) { - this.value = value; - } + /** + * Sets the value of the value property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setValue(String value) { + this.value = value; + } - /** - * Gets the value of the mediaType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMediaType() { - return mediaType; - } + /** + * Gets the value of the mediaType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMediaType() { + return mediaType; + } - /** - * Sets the value of the mediaType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMediaType(String value) { - this.mediaType = value; - } + /** + * Sets the value of the mediaType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMediaType(String value) { + this.mediaType = value; + } - /** - * Gets a map that contains attributes that aren't bound to any typed property on this class. - * - *

- * the map is keyed by the name of the attribute and - * the value is the string value of the attribute. - * - * the map returned by this method is live, and you can add new attribute - * by updating the map directly. Because of this design, there's no setter. - * - * - * @return - * always non-null - */ - public Map getOtherAttributes() { - return otherAttributes; - } + /** + * Gets a map that contains attributes that aren't bound to any typed property on this class. + * + *

+ * the map is keyed by the name of the attribute and + * the value is the string value of the attribute. + * + * the map returned by this method is live, and you can add new attribute + * by updating the map directly. Because of this design, there's no setter. + * + * + * @return + * always non-null + */ + public Map getOtherAttributes() { + return otherAttributes; + } } diff --git a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Param.java b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Param.java index 49a40904c17..10462832afa 100644 --- a/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Param.java +++ b/resteasy-wadl/src/main/java/org/jboss/resteasy/wadl/jaxb/Param.java @@ -62,428 +62,428 @@ */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { - "doc", - "option", - "link", - "any" + "doc", + "option", + "link", + "any" }) @XmlRootElement(name = "param") public class Param { - protected List doc; - protected List