target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testExtendedClassCompatible() { Configuration configuration = new DynamicConfiguration(); configuration.setProperty(BootStrapProperties.CONFIG_SERVICE_EXTENDED_CLASS, "invalidClass"); AbstractPropertiesLoader loader = MicroservicePropertiesLoader.INSTANCE; try { loader.loadProperties(configuration); Assert.fail("Must throw exception"); } catch (Error e) { Assert.assertEquals(ClassNotFoundException.class, e.getCause().getClass()); Assert.assertEquals("invalidClass", e.getCause().getMessage()); } }
public Map<String, String> loadProperties(Configuration configuration) { Map<String, String> propertiesMap = new HashMap<>(); loadPropertiesFromConfigMap(configuration, propertiesMap); loadPropertiesFromExtendedClass(configuration, propertiesMap); return propertiesMap; }
AbstractPropertiesLoader { public Map<String, String> loadProperties(Configuration configuration) { Map<String, String> propertiesMap = new HashMap<>(); loadPropertiesFromConfigMap(configuration, propertiesMap); loadPropertiesFromExtendedClass(configuration, propertiesMap); return propertiesMap; } }
AbstractPropertiesLoader { public Map<String, String> loadProperties(Configuration configuration) { Map<String, String> propertiesMap = new HashMap<>(); loadPropertiesFromConfigMap(configuration, propertiesMap); loadPropertiesFromExtendedClass(configuration, propertiesMap); return propertiesMap; } }
AbstractPropertiesLoader { public Map<String, String> loadProperties(Configuration configuration) { Map<String, String> propertiesMap = new HashMap<>(); loadPropertiesFromConfigMap(configuration, propertiesMap); loadPropertiesFromExtendedClass(configuration, propertiesMap); return propertiesMap; } Map<String, String> loadProperties(Configuration configuration); }
AbstractPropertiesLoader { public Map<String, String> loadProperties(Configuration configuration) { Map<String, String> propertiesMap = new HashMap<>(); loadPropertiesFromConfigMap(configuration, propertiesMap); loadPropertiesFromExtendedClass(configuration, propertiesMap); return propertiesMap; } Map<String, String> loadProperties(Configuration configuration); }
@Test public void parseInvalid() { Assert.assertNull(parser.parse("")); Assert.assertNull(parser.parse("-")); Assert.assertNull(parser.parse("1-")); }
@Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('-'); if (pos <= 0 || pos == strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); Version to = new Version(strVersionRule.substring(pos + 1)); return new RangeVersionRule(from.getVersion() + "-" + to.getVersion(), from, to); }
VersionRuleRangeParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('-'); if (pos <= 0 || pos == strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); Version to = new Version(strVersionRule.substring(pos + 1)); return new RangeVersionRule(from.getVersion() + "-" + to.getVersion(), from, to); } }
VersionRuleRangeParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('-'); if (pos <= 0 || pos == strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); Version to = new Version(strVersionRule.substring(pos + 1)); return new RangeVersionRule(from.getVersion() + "-" + to.getVersion(), from, to); } }
VersionRuleRangeParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('-'); if (pos <= 0 || pos == strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); Version to = new Version(strVersionRule.substring(pos + 1)); return new RangeVersionRule(from.getVersion() + "-" + to.getVersion(), from, to); } @Override VersionRule parse(String strVersionRule); }
VersionRuleRangeParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('-'); if (pos <= 0 || pos == strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); Version to = new Version(strVersionRule.substring(pos + 1)); return new RangeVersionRule(from.getVersion() + "-" + to.getVersion(), from, to); } @Override VersionRule parse(String strVersionRule); }
@Test public void isAccept() { Assert.assertTrue(versionRule.isAccept(null)); }
public boolean isAccept(Version version) { return isMatch(version, null); }
VersionRule { public boolean isAccept(Version version) { return isMatch(version, null); } }
VersionRule { public boolean isAccept(Version version) { return isMatch(version, null); } VersionRule(String versionRule); }
VersionRule { public boolean isAccept(Version version) { return isMatch(version, null); } VersionRule(String versionRule); String getVersionRule(); boolean isAccept(Version version); abstract boolean isMatch(Version version, Version latestVersion); @Override String toString(); }
VersionRule { public boolean isAccept(Version version) { return isMatch(version, null); } VersionRule(String versionRule); String getVersionRule(); boolean isAccept(Version version); abstract boolean isMatch(Version version, Version latestVersion); @Override String toString(); }
@Test public void getVersionRule() { Assert.assertEquals("abc", versionRule.getVersionRule()); }
public String getVersionRule() { return versionRule; }
VersionRule { public String getVersionRule() { return versionRule; } }
VersionRule { public String getVersionRule() { return versionRule; } VersionRule(String versionRule); }
VersionRule { public String getVersionRule() { return versionRule; } VersionRule(String versionRule); String getVersionRule(); boolean isAccept(Version version); abstract boolean isMatch(Version version, Version latestVersion); @Override String toString(); }
VersionRule { public String getVersionRule() { return versionRule; } VersionRule(String versionRule); String getVersionRule(); boolean isAccept(Version version); abstract boolean isMatch(Version version, Version latestVersion); @Override String toString(); }
@Test public void parseNormal() { versionRule = parser.parse("1"); Assert.assertEquals("1.0.0.0", versionRule.getVersionRule()); }
@Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } @Override VersionRule parse(String strVersionRule); }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } @Override VersionRule parse(String strVersionRule); }
@Test public void isMatch() { versionRule = parser.parse("1"); Assert.assertTrue(versionRule.isMatch(VersionConst.v1, null)); Assert.assertFalse(versionRule.isMatch(VersionConst.v2, null)); }
@Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } @Override VersionRule parse(String strVersionRule); }
VersionRuleFixedParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { Version version = new Version(strVersionRule); return new FixedVersionRule(version.getVersion(), version); } @Override VersionRule parse(String strVersionRule); }
@Test public void getOrCreate() { Version v = VersionUtils.getOrCreate("1.0.0"); Assert.assertEquals("1.0.0.0", v.getVersion()); Assert.assertSame(v, VersionUtils.getOrCreate("1.0.0")); }
public static Version getOrCreate(String strVersion) { Objects.requireNonNull(strVersion); return versionCache.computeIfAbsent(strVersion, Version::new); }
VersionUtils { public static Version getOrCreate(String strVersion) { Objects.requireNonNull(strVersion); return versionCache.computeIfAbsent(strVersion, Version::new); } }
VersionUtils { public static Version getOrCreate(String strVersion) { Objects.requireNonNull(strVersion); return versionCache.computeIfAbsent(strVersion, Version::new); } }
VersionUtils { public static Version getOrCreate(String strVersion) { Objects.requireNonNull(strVersion); return versionCache.computeIfAbsent(strVersion, Version::new); } static Version getOrCreate(String strVersion); }
VersionUtils { public static Version getOrCreate(String strVersion) { Objects.requireNonNull(strVersion); return versionCache.computeIfAbsent(strVersion, Version::new); } static Version getOrCreate(String strVersion); }
@Test public void fixed() { VersionRule versionRule = VersionRuleUtils.getOrCreate("1"); Assert.assertThat(versionRule, Matchers.instanceOf(FixedVersionRule.class)); Assert.assertSame(versionRule, VersionRuleUtils.getOrCreate("1")); }
public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
@Test public void latest() { VersionRule versionRule = VersionRuleUtils.getOrCreate(DefinitionConst.VERSION_RULE_LATEST); Assert.assertThat(versionRule, Matchers.instanceOf(LatestVersionRule.class)); Assert.assertSame(versionRule, VersionRuleUtils.getOrCreate(DefinitionConst.VERSION_RULE_LATEST)); }
public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
@Test public void getSchemasFailed() { String microserviceId = "msId"; new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Holder<GetSchemasResponse> holder = Deencapsulation.getField(responseHandler, "arg$4"); holder.setStatusCode(Status.NOT_FOUND.getStatusCode()); } }; Holder<List<GetSchemaResponse>> schemasHolder = oClient.getSchemas(microserviceId); List<GetSchemaResponse> schemaResponses = schemasHolder.getValue(); Assert.assertEquals(404, schemasHolder.getStatusCode()); Assert.assertNull(schemaResponses); }
@Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public Holder<List<GetSchemaResponse>> getSchemas(String microserviceId) { return getSchemas(microserviceId, false, false); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
@Test public void range() { VersionRule versionRule = VersionRuleUtils.getOrCreate("1-2"); Assert.assertThat(versionRule, Matchers.instanceOf(RangeVersionRule.class)); Assert.assertSame(versionRule, VersionRuleUtils.getOrCreate("1-2")); }
public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
@Test public void startFrom() { VersionRule versionRule = VersionRuleUtils.getOrCreate("1+"); Assert.assertThat(versionRule, Matchers.instanceOf(StartFromVersionRule.class)); Assert.assertSame(versionRule, VersionRuleUtils.getOrCreate("1+")); }
public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
@Test public void invalid() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage(Matchers.is("Invalid major \"\", version \"\".")); VersionRuleUtils.getOrCreate(""); }
public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
VersionRuleUtils { public static VersionRule getOrCreate(String strVersionRule) { Objects.requireNonNull(strVersionRule); return versionRuleCache.computeIfAbsent(strVersionRule, VersionRuleUtils::create); } static VersionRule getOrCreate(String strVersionRule); static VersionRule create(String strVersionRule); }
@Test public void testToString() { version = new Version(s1, s1, s1, s1); Assert.assertEquals("1.1.1.1", version.toString()); }
@Override public String toString() { return version; }
Version implements Comparable<Version> { @Override public String toString() { return version; } }
Version implements Comparable<Version> { @Override public String toString() { return version; } Version(String version); Version(short major, short minor, short patch, short build); }
Version implements Comparable<Version> { @Override public String toString() { return version; } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
Version implements Comparable<Version> { @Override public String toString() { return version; } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
@Test public void testHashCode() { version = new Version(s1, s1, s1, s1); Assert.assertEquals(version.getVersion().hashCode(), version.hashCode()); }
@Override public int hashCode() { return version.hashCode(); }
Version implements Comparable<Version> { @Override public int hashCode() { return version.hashCode(); } }
Version implements Comparable<Version> { @Override public int hashCode() { return version.hashCode(); } Version(String version); Version(short major, short minor, short patch, short build); }
Version implements Comparable<Version> { @Override public int hashCode() { return version.hashCode(); } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
Version implements Comparable<Version> { @Override public int hashCode() { return version.hashCode(); } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
@Test public void testEquals() { version = new Version(s1, s1, s1, s1); Assert.assertTrue(version.equals(version)); Assert.assertTrue(version.equals(new Version(s1, s1, s1, s1))); Assert.assertFalse(version.equals(null)); }
@Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Version)) { return false; } return numberVersion == ((Version) other).numberVersion; }
Version implements Comparable<Version> { @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Version)) { return false; } return numberVersion == ((Version) other).numberVersion; } }
Version implements Comparable<Version> { @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Version)) { return false; } return numberVersion == ((Version) other).numberVersion; } Version(String version); Version(short major, short minor, short patch, short build); }
Version implements Comparable<Version> { @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Version)) { return false; } return numberVersion == ((Version) other).numberVersion; } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
Version implements Comparable<Version> { @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Version)) { return false; } return numberVersion == ((Version) other).numberVersion; } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
@Test public void compareTo() { version = new Version(s1, s1, s1, s1); Assert.assertEquals(0, version.compareTo(version)); Assert.assertEquals(0, version.compareTo(new Version(s1, s1, s1, s1))); Assert.assertEquals(-1, version.compareTo(new Version(s1, s1, s2, s1))); Assert.assertEquals(-1, version.compareTo(new Version(s1, s2, s1, s1))); Assert.assertEquals(-1, version.compareTo(new Version(s2, s1, s1, s1))); Assert.assertEquals(1, version.compareTo(new Version((short) 0, Short.MAX_VALUE, Short.MAX_VALUE, Short.MAX_VALUE))); }
@Override public int compareTo(Version other) { return Long.compare(numberVersion, other.numberVersion); }
Version implements Comparable<Version> { @Override public int compareTo(Version other) { return Long.compare(numberVersion, other.numberVersion); } }
Version implements Comparable<Version> { @Override public int compareTo(Version other) { return Long.compare(numberVersion, other.numberVersion); } Version(String version); Version(short major, short minor, short patch, short build); }
Version implements Comparable<Version> { @Override public int compareTo(Version other) { return Long.compare(numberVersion, other.numberVersion); } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
Version implements Comparable<Version> { @Override public int compareTo(Version other) { return Long.compare(numberVersion, other.numberVersion); } Version(String version); Version(short major, short minor, short patch, short build); short getMajor(); short getMinor(); short getPatch(); short getBuild(); String getVersion(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object other); @Override int compareTo(Version other); }
@Test public void parseInvalid() { Assert.assertNull(parser.parse("")); Assert.assertNull(parser.parse("+")); Assert.assertNull(parser.parse("1+1")); }
@Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('+'); if (pos <= 0 || pos != strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); return new StartFromVersionRule(from.getVersion() + "+", from); }
VersionRuleStartFromParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('+'); if (pos <= 0 || pos != strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); return new StartFromVersionRule(from.getVersion() + "+", from); } }
VersionRuleStartFromParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('+'); if (pos <= 0 || pos != strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); return new StartFromVersionRule(from.getVersion() + "+", from); } }
VersionRuleStartFromParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('+'); if (pos <= 0 || pos != strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); return new StartFromVersionRule(from.getVersion() + "+", from); } @Override VersionRule parse(String strVersionRule); }
VersionRuleStartFromParser implements VersionRuleParser { @Override public VersionRule parse(String strVersionRule) { int pos = strVersionRule.indexOf('+'); if (pos <= 0 || pos != strVersionRule.length() - 1) { return null; } Version from = new Version(strVersionRule.substring(0, pos)); return new StartFromVersionRule(from.getVersion() + "+", from); } @Override VersionRule parse(String strVersionRule); }
@Test public void testParsePatternFullTest() { List<AccessLogItem<RoutingContext>> result = logPatternParser.parsePattern(ROW_PATTERN); assertEquals(29, result.size()); StringBuilder builder = new StringBuilder(); result.get(0).appendServerFormattedItem(accessLogEvent, builder); assertEquals("[", builder.toString()); assertEquals(HttpMethodAccessItem.class, result.get(1).getClass()); builder = new StringBuilder(); result.get(2).appendServerFormattedItem(accessLogEvent, builder); assertEquals("] ", builder.toString()); assertEquals(HttpMethodAccessItem.class, result.get(3).getClass()); builder = new StringBuilder(); result.get(4).appendServerFormattedItem(accessLogEvent, builder); assertEquals(" ", builder.toString()); assertEquals(HttpStatusAccessItem.class, result.get(5).getClass()); assertEquals(DurationSecondAccessItem.class, result.get(6).getClass()); assertEquals(DurationMillisecondAccessItem.class, result.get(7).getClass()); assertEquals(RemoteHostAccessItem.class, result.get(8).getClass()); assertEquals(LocalHostAccessItem.class, result.get(9).getClass()); assertEquals(LocalPortAccessItem.class, result.get(10).getClass()); assertEquals(ResponseSizeAccessItem.class, result.get(11).getClass()); assertEquals("0", ((ResponseSizeAccessItem) result.get(11)).getZeroBytes()); assertEquals(ResponseSizeAccessItem.class, result.get(12).getClass()); assertEquals("-", ((ResponseSizeAccessItem) result.get(12)).getZeroBytes()); assertEquals(FirstLineOfRequestAccessItem.class, result.get(13).getClass()); assertEquals(UrlPathAccessItem.class, result.get(14).getClass()); assertEquals(QueryStringAccessItem.class, result.get(15).getClass()); assertEquals(UrlPathAccessItem.class, result.get(16).getClass()); assertEquals(QueryStringAccessItem.class, result.get(17).getClass()); assertEquals(UrlPathWithQueryAccessItem.class, result.get(18).getClass()); assertEquals(RequestProtocolAccessItem.class, result.get(19).getClass()); assertEquals(ConfigurableDatetimeAccessItem.class, result.get(20).getClass()); assertEquals(ConfigurableDatetimeAccessItem.DEFAULT_DATETIME_PATTERN, ((ConfigurableDatetimeAccessItem) result.get(20)).getPattern()); assertEquals(ConfigurableDatetimeAccessItem.DEFAULT_LOCALE, ((ConfigurableDatetimeAccessItem) result.get(20)).getLocale()); assertEquals(TimeZone.getDefault(), ((ConfigurableDatetimeAccessItem) result.get(20)).getTimezone()); assertEquals("yyyy MM dd HH:mm:ss zzz", ((ConfigurableDatetimeAccessItem) result.get(21)).getPattern()); assertEquals(ConfigurableDatetimeAccessItem.DEFAULT_LOCALE, ((ConfigurableDatetimeAccessItem) result.get(21)).getLocale()); assertEquals(TimeZone.getDefault(), ((ConfigurableDatetimeAccessItem) result.get(21)).getTimezone()); assertEquals("yyyy MM dd HH:mm:ss", ((ConfigurableDatetimeAccessItem) result.get(22)).getPattern()); assertEquals(Locale.forLanguageTag("en-US"), ((ConfigurableDatetimeAccessItem) result.get(22)).getLocale()); assertEquals(TimeZone.getTimeZone("GMT+0"), ((ConfigurableDatetimeAccessItem) result.get(22)).getTimezone()); assertEquals(RequestHeaderAccessItem.class, result.get(23).getClass()); assertEquals("incoming-header", ((RequestHeaderAccessItem) result.get(23)).getVarName()); assertEquals(ResponseHeaderAccessItem.class, result.get(24).getClass()); assertEquals("outgoing-header", ((ResponseHeaderAccessItem) result.get(24)).getVarName()); assertEquals(CookieAccessItem.class, result.get(25).getClass()); assertEquals("cookie", ((CookieAccessItem) result.get(25)).getVarName()); assertEquals(TraceIdAccessItem.class, result.get(26).getClass()); assertEquals(InvocationContextAccessItem.class, result.get(27).getClass()); assertEquals("ctx", ((InvocationContextAccessItem) result.get(27)).getVarName()); assertEquals(TransportAccessItem.class, result.get(28).getClass()); }
@Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); static final Comparator<VertxRestAccessLogItemMeta> accessLogItemMetaComparator; }
@Test public void testParsePattern() { String pattern = " %m cs-uri-stem %{response-header}o "; List<AccessLogItem<RoutingContext>> result = logPatternParser.parsePattern(pattern); assertEquals(7, result.size()); StringBuilder stringBuilder = new StringBuilder(); result.get(0).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" ", stringBuilder.toString()); assertEquals(HttpMethodAccessItem.class, result.get(1).getClass()); stringBuilder = new StringBuilder(); result.get(2).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" ", stringBuilder.toString()); assertEquals(UrlPathAccessItem.class, result.get(3).getClass()); stringBuilder = new StringBuilder(); result.get(4).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" ", stringBuilder.toString()); assertEquals(ResponseHeaderAccessItem.class, result.get(5).getClass()); assertEquals("response-header", ((ResponseHeaderAccessItem) result.get(5)).getVarName()); stringBuilder = new StringBuilder(); result.get(6).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" ", stringBuilder.toString()); }
@Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); static final Comparator<VertxRestAccessLogItemMeta> accessLogItemMetaComparator; }
@Test public void testFindServiceInstance() { new MockUp<RestClientUtil>() { @Mock void get(IpPort ipPort, String uri, RequestParam requestParam, Handler<RestResponse> responseHandler) { Assert.assertEquals("global=true", requestParam.getQueryParams()); } }; Assert.assertNull(oClient.findServiceInstance("aaa", "bbb")); }
@Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
@Test public void testParsePatternWithNoBlank() { String pattern = "%mcs-uri-stem%{response-header}o"; List<AccessLogItem<RoutingContext>> result = logPatternParser.parsePattern(pattern); assertEquals(3, result.size()); assertEquals(HttpMethodAccessItem.class, result.get(0).getClass()); assertEquals(UrlPathAccessItem.class, result.get(1).getClass()); assertEquals(ResponseHeaderAccessItem.class, result.get(2).getClass()); assertEquals("response-header", ((ResponseHeaderAccessItem) result.get(2)).getVarName()); }
@Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); static final Comparator<VertxRestAccessLogItemMeta> accessLogItemMetaComparator; }
@Test public void testParsePatternComplex() { String pattern = "%m cs-uri-stem %{response-header}o abc cs-uri-query %s%{request} header}i plain cs-uri"; List<AccessLogItem<RoutingContext>> result = logPatternParser.parsePattern(pattern); assertEquals(12, result.size()); assertEquals(HttpMethodAccessItem.class, result.get(0).getClass()); StringBuilder stringBuilder = new StringBuilder(); result.get(1).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" ", stringBuilder.toString()); assertEquals(UrlPathAccessItem.class, result.get(2).getClass()); stringBuilder = new StringBuilder(); result.get(3).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" ", stringBuilder.toString()); assertEquals(ResponseHeaderAccessItem.class, result.get(4).getClass()); assertEquals("response-header", ((ResponseHeaderAccessItem) result.get(4)).getVarName()); stringBuilder = new StringBuilder(); result.get(5).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" abc ", stringBuilder.toString()); assertEquals(QueryStringAccessItem.class, result.get(6).getClass()); stringBuilder = new StringBuilder(); result.get(7).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" ", stringBuilder.toString()); assertEquals(HttpStatusAccessItem.class, result.get(8).getClass()); assertEquals(RequestHeaderAccessItem.class, result.get(9).getClass()); assertEquals("request} header", ((RequestHeaderAccessItem) result.get(9)).getVarName()); stringBuilder = new StringBuilder(); result.get(10).appendServerFormattedItem(accessLogEvent, stringBuilder); assertEquals(" plain ", stringBuilder.toString()); assertEquals(UrlPathWithQueryAccessItem.class, result.get(11).getClass()); }
@Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { @Override public List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern) { LOGGER.info("parse the pattern of access log: [{}]", rawPattern); List<AccessLogItemLocation> locationList = matchAccessLogItem(rawPattern); locationList = fillInPlainTextLocation(rawPattern, locationList); return convertToItemList(rawPattern, locationList); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); static final Comparator<VertxRestAccessLogItemMeta> accessLogItemMetaComparator; }
@Test public void testComparePlaceholderString() { Assert.assertTrue( VertxRestAccessLogPatternParser.comparePlaceholderString("abc", "bbc") < 0 ); Assert.assertTrue( VertxRestAccessLogPatternParser.comparePlaceholderString("abc", "ab") < 0 ); Assert.assertEquals(0, VertxRestAccessLogPatternParser.comparePlaceholderString("abc", "abc")); Assert.assertTrue( VertxRestAccessLogPatternParser.comparePlaceholderString("bbc", "abc") > 0 ); Assert.assertTrue( VertxRestAccessLogPatternParser.comparePlaceholderString("ab", "abc") > 0 ); }
public static int comparePlaceholderString(String s1, String s2) { int result = s1.compareTo(s2); if (0 == result) { return result; } return result < 0 ? (s2.startsWith(s1) ? -result : result) : (s1.startsWith(s2) ? -result : result); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { public static int comparePlaceholderString(String s1, String s2) { int result = s1.compareTo(s2); if (0 == result) { return result; } return result < 0 ? (s2.startsWith(s1) ? -result : result) : (s1.startsWith(s2) ? -result : result); } }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { public static int comparePlaceholderString(String s1, String s2) { int result = s1.compareTo(s2); if (0 == result) { return result; } return result < 0 ? (s2.startsWith(s1) ? -result : result) : (s1.startsWith(s2) ? -result : result); } VertxRestAccessLogPatternParser(); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { public static int comparePlaceholderString(String s1, String s2) { int result = s1.compareTo(s2); if (0 == result) { return result; } return result < 0 ? (s2.startsWith(s1) ? -result : result) : (s1.startsWith(s2) ? -result : result); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); }
VertxRestAccessLogPatternParser implements AccessLogPatternParser<RoutingContext> { public static int comparePlaceholderString(String s1, String s2) { int result = s1.compareTo(s2); if (0 == result) { return result; } return result < 0 ? (s2.startsWith(s1) ? -result : result) : (s1.startsWith(s2) ? -result : result); } VertxRestAccessLogPatternParser(); static int comparePlaceholderString(String s1, String s2); static void sortAccessLogItemMeta(List<VertxRestAccessLogItemMeta> accessLogItemMetaList); @Override List<AccessLogItem<RoutingContext>> parsePattern(String rawPattern); static final Comparator<VertxRestAccessLogItemMeta> accessLogItemMetaComparator; }
@Test public void testServerLog() { RoutingContext context = Mockito.mock(RoutingContext.class); HttpServerRequest request = Mockito.mock(HttpServerRequest.class); long startMillisecond = 1416863450581L; ServerAccessLogEvent serverAccessLogEvent = new ServerAccessLogEvent(); serverAccessLogEvent.setMilliStartTime(startMillisecond).setRoutingContext(context); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ConfigurableDatetimeAccessItem.DEFAULT_DATETIME_PATTERN, ConfigurableDatetimeAccessItem.DEFAULT_LOCALE); simpleDateFormat.setTimeZone(TimeZone.getDefault()); when(context.request()).thenReturn(request); when(request.method()).thenReturn(HttpMethod.DELETE); String log = LOG_GENERATOR.generateServerLog(serverAccessLogEvent); Assert.assertEquals("DELETE" + " - " + simpleDateFormat.format(startMillisecond), log); }
public String generateServerLog(ServerAccessLogEvent accessLogEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendServerFormattedItem(accessLogEvent, log); } return log.toString(); }
AccessLogGenerator { public String generateServerLog(ServerAccessLogEvent accessLogEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendServerFormattedItem(accessLogEvent, log); } return log.toString(); } }
AccessLogGenerator { public String generateServerLog(ServerAccessLogEvent accessLogEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendServerFormattedItem(accessLogEvent, log); } return log.toString(); } @SuppressWarnings("unchecked") AccessLogGenerator(String rawPattern); }
AccessLogGenerator { public String generateServerLog(ServerAccessLogEvent accessLogEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendServerFormattedItem(accessLogEvent, log); } return log.toString(); } @SuppressWarnings("unchecked") AccessLogGenerator(String rawPattern); String generateServerLog(ServerAccessLogEvent accessLogEvent); String generateClientLog(InvocationFinishEvent finishEvent); }
AccessLogGenerator { public String generateServerLog(ServerAccessLogEvent accessLogEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendServerFormattedItem(accessLogEvent, log); } return log.toString(); } @SuppressWarnings("unchecked") AccessLogGenerator(String rawPattern); String generateServerLog(ServerAccessLogEvent accessLogEvent); String generateClientLog(InvocationFinishEvent finishEvent); }
@Test public void testClientLog() { Invocation invocation = Mockito.mock(Invocation.class); InvocationStageTrace stageTrace = Mockito.mock(InvocationStageTrace.class); OperationMeta operationMeta = Mockito.mock(OperationMeta.class); long startMillisecond = 1416863450581L; when(stageTrace.getStartSend()).thenReturn(0L); when(stageTrace.getStart()).thenReturn(0L); when(stageTrace.getFinish()).thenReturn(0L); when(stageTrace.getStartCurrentTime()).thenReturn(startMillisecond); when(invocation.getOperationMeta()).thenReturn(operationMeta); when(invocation.getInvocationStageTrace()).thenReturn(stageTrace); InvocationFinishEvent finishEvent = new InvocationFinishEvent(invocation, null); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ConfigurableDatetimeAccessItem.DEFAULT_DATETIME_PATTERN, ConfigurableDatetimeAccessItem.DEFAULT_LOCALE); simpleDateFormat.setTimeZone(TimeZone.getDefault()); when(operationMeta.getHttpMethod()).thenReturn(HttpMethod.DELETE.toString()); String log = LOG_GENERATOR.generateClientLog(finishEvent); Assert.assertEquals("DELETE" + " - " + simpleDateFormat.format(startMillisecond), log); }
public String generateClientLog(InvocationFinishEvent finishEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendClientFormattedItem(finishEvent, log); } return log.toString(); }
AccessLogGenerator { public String generateClientLog(InvocationFinishEvent finishEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendClientFormattedItem(finishEvent, log); } return log.toString(); } }
AccessLogGenerator { public String generateClientLog(InvocationFinishEvent finishEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendClientFormattedItem(finishEvent, log); } return log.toString(); } @SuppressWarnings("unchecked") AccessLogGenerator(String rawPattern); }
AccessLogGenerator { public String generateClientLog(InvocationFinishEvent finishEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendClientFormattedItem(finishEvent, log); } return log.toString(); } @SuppressWarnings("unchecked") AccessLogGenerator(String rawPattern); String generateServerLog(ServerAccessLogEvent accessLogEvent); String generateClientLog(InvocationFinishEvent finishEvent); }
AccessLogGenerator { public String generateClientLog(InvocationFinishEvent finishEvent) { StringBuilder log = new StringBuilder(128); for (AccessLogItem<RoutingContext> accessLogItem : getAccessLogItems()) { accessLogItem.appendClientFormattedItem(finishEvent, log); } return log.toString(); } @SuppressWarnings("unchecked") AccessLogGenerator(String rawPattern); String generateServerLog(ServerAccessLogEvent accessLogEvent); String generateClientLog(InvocationFinishEvent finishEvent); }
@Test public void convert() throws IOException { URL url = TestSwaggerToProtoGenerator.class.getClassLoader().getResource("ProtoSchema.proto"); String protoContent = IOUtils.toString(url, "UTF-8"); int idx = protoContent.indexOf("syntax = "); protoContent = protoContent.substring(idx); SpringmvcSwaggerGenerator swaggerGenerator = new SpringmvcSwaggerGenerator(ProtoSchema.class); Swagger swagger = swaggerGenerator.generate(); SwaggerToProtoGenerator generator = new SwaggerToProtoGenerator("a.b", swagger); Proto proto = generator.convert(); Assert.assertEquals(protoContent.replaceAll("\r\n", "\n"), new ProtoToStringGenerator(proto).protoToString().replaceAll("\r\n", "\n")); }
public Proto convert() { convertDefinitions(); convertOperations(); for (; ; ) { List<Runnable> oldPending = pending; pending = new ArrayList<>(); for (Runnable runnable : oldPending) { runnable.run(); } if (pending.isEmpty()) { break; } } return createProto(); }
SwaggerToProtoGenerator { public Proto convert() { convertDefinitions(); convertOperations(); for (; ; ) { List<Runnable> oldPending = pending; pending = new ArrayList<>(); for (Runnable runnable : oldPending) { runnable.run(); } if (pending.isEmpty()) { break; } } return createProto(); } }
SwaggerToProtoGenerator { public Proto convert() { convertDefinitions(); convertOperations(); for (; ; ) { List<Runnable> oldPending = pending; pending = new ArrayList<>(); for (Runnable runnable : oldPending) { runnable.run(); } if (pending.isEmpty()) { break; } } return createProto(); } SwaggerToProtoGenerator(String protoPackage, Swagger swagger); }
SwaggerToProtoGenerator { public Proto convert() { convertDefinitions(); convertOperations(); for (; ; ) { List<Runnable> oldPending = pending; pending = new ArrayList<>(); for (Runnable runnable : oldPending) { runnable.run(); } if (pending.isEmpty()) { break; } } return createProto(); } SwaggerToProtoGenerator(String protoPackage, Swagger swagger); Proto convert(); static String escapePackageName(String name); static String escapeMessageName(String name); static boolean isValidEnum(String name); }
SwaggerToProtoGenerator { public Proto convert() { convertDefinitions(); convertOperations(); for (; ; ) { List<Runnable> oldPending = pending; pending = new ArrayList<>(); for (Runnable runnable : oldPending) { runnable.run(); } if (pending.isEmpty()) { break; } } return createProto(); } SwaggerToProtoGenerator(String protoPackage, Swagger swagger); Proto convert(); static String escapePackageName(String name); static String escapeMessageName(String name); static boolean isValidEnum(String name); }
@Test public void protoToString() { ProtoParser protoParser = new ProtoParser(); Proto proto = protoParser.parseFromContent(content); String newContent = new ProtoToStringGenerator(proto).protoToString(); Assert.assertEquals(content, newContent); }
public String protoToString() { StringBuilder sb = new StringBuilder(); appendLine(sb, "syntax = \"%s\";", proto.getSyntax()); for (Import importValue : proto.getImports()) { appendLine(sb, "import \"%s\";", importValue.getValue()); } appendLine(sb, "package %s;\n", proto.getPackage().getValue()); for (Message message : proto.getMessages()) { messageToString(message, sb); } for (Enum enumValue : proto.getEnums()) { enumToString(enumValue, sb); } for (Service service : proto.getServices()) { serviceToString(service, sb); } return sb.toString(); }
ProtoToStringGenerator { public String protoToString() { StringBuilder sb = new StringBuilder(); appendLine(sb, "syntax = \"%s\";", proto.getSyntax()); for (Import importValue : proto.getImports()) { appendLine(sb, "import \"%s\";", importValue.getValue()); } appendLine(sb, "package %s;\n", proto.getPackage().getValue()); for (Message message : proto.getMessages()) { messageToString(message, sb); } for (Enum enumValue : proto.getEnums()) { enumToString(enumValue, sb); } for (Service service : proto.getServices()) { serviceToString(service, sb); } return sb.toString(); } }
ProtoToStringGenerator { public String protoToString() { StringBuilder sb = new StringBuilder(); appendLine(sb, "syntax = \"%s\";", proto.getSyntax()); for (Import importValue : proto.getImports()) { appendLine(sb, "import \"%s\";", importValue.getValue()); } appendLine(sb, "package %s;\n", proto.getPackage().getValue()); for (Message message : proto.getMessages()) { messageToString(message, sb); } for (Enum enumValue : proto.getEnums()) { enumToString(enumValue, sb); } for (Service service : proto.getServices()) { serviceToString(service, sb); } return sb.toString(); } ProtoToStringGenerator(Proto proto); }
ProtoToStringGenerator { public String protoToString() { StringBuilder sb = new StringBuilder(); appendLine(sb, "syntax = \"%s\";", proto.getSyntax()); for (Import importValue : proto.getImports()) { appendLine(sb, "import \"%s\";", importValue.getValue()); } appendLine(sb, "package %s;\n", proto.getPackage().getValue()); for (Message message : proto.getMessages()) { messageToString(message, sb); } for (Enum enumValue : proto.getEnums()) { enumToString(enumValue, sb); } for (Service service : proto.getServices()) { serviceToString(service, sb); } return sb.toString(); } ProtoToStringGenerator(Proto proto); String protoToString(); }
ProtoToStringGenerator { public String protoToString() { StringBuilder sb = new StringBuilder(); appendLine(sb, "syntax = \"%s\";", proto.getSyntax()); for (Import importValue : proto.getImports()) { appendLine(sb, "import \"%s\";", importValue.getValue()); } appendLine(sb, "package %s;\n", proto.getPackage().getValue()); for (Message message : proto.getMessages()) { messageToString(message, sb); } for (Enum enumValue : proto.getEnums()) { enumToString(enumValue, sb); } for (Service service : proto.getServices()) { serviceToString(service, sb); } return sb.toString(); } ProtoToStringGenerator(Proto proto); String protoToString(); }
@Test public void testNeedConvert() { Assert.assertEquals(SimpleType.constructUnsafe(Object.class), ProtoConst.OBJECT_TYPE); Assert.assertEquals(false, ResponseRootDeserializer.needConvert(1, TypeFactory.defaultInstance().constructType(int.class))); Assert.assertEquals(false, ResponseRootDeserializer.needConvert(1, TypeFactory.defaultInstance().constructType(Integer.class))); Assert.assertEquals(false, ResponseRootDeserializer .needConvert(Integer.valueOf(1), TypeFactory.defaultInstance().constructType(int.class))); Assert.assertEquals(false, ResponseRootDeserializer .needConvert(Integer.valueOf(1), TypeFactory.defaultInstance().constructType(Integer.class))); Assert.assertEquals(true, ResponseRootDeserializer .needConvert(new HashMap<>(), TypeFactory.defaultInstance().constructType(Model.class))); Assert.assertEquals(false, ResponseRootDeserializer .needConvert(new Model(), TypeFactory.defaultInstance().constructType(Model.class))); Assert.assertEquals(false, ResponseRootDeserializer .needConvert(new Model(), TypeFactory.defaultInstance().constructType(Object.class))); List<Model> modelList = new ArrayList<>(); List<Map> modemaplList = new ArrayList<>(); Assert.assertEquals(true, ResponseRootDeserializer .needConvert(modemaplList, TypeFactory.defaultInstance().constructType(new TypeReference<List<Model>>() { }))); Assert.assertEquals(true, ResponseRootDeserializer .needConvert(modelList, TypeFactory.defaultInstance().constructType(new TypeReference<List<Model>>() { }))); }
public static boolean needConvert(Object obj, JavaType invocationTimeType) { if (obj == null || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || invocationTimeType.isPrimitive() || ProtoConst.OBJECT_TYPE.equals(invocationTimeType)) { return false; } if (obj.getClass() == invocationTimeType.getRawClass()) { return false; } if (invocationTimeType.getRawClass().isAssignableFrom(obj.getClass())) { if (invocationTimeType.getContentType() == null) { return false; } } return true; }
ResponseRootDeserializer { public static boolean needConvert(Object obj, JavaType invocationTimeType) { if (obj == null || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || invocationTimeType.isPrimitive() || ProtoConst.OBJECT_TYPE.equals(invocationTimeType)) { return false; } if (obj.getClass() == invocationTimeType.getRawClass()) { return false; } if (invocationTimeType.getRawClass().isAssignableFrom(obj.getClass())) { if (invocationTimeType.getContentType() == null) { return false; } } return true; } }
ResponseRootDeserializer { public static boolean needConvert(Object obj, JavaType invocationTimeType) { if (obj == null || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || invocationTimeType.isPrimitive() || ProtoConst.OBJECT_TYPE.equals(invocationTimeType)) { return false; } if (obj.getClass() == invocationTimeType.getRawClass()) { return false; } if (invocationTimeType.getRawClass().isAssignableFrom(obj.getClass())) { if (invocationTimeType.getContentType() == null) { return false; } } return true; } ResponseRootDeserializer(RootDeserializer<T> rootDeserializer, boolean empty); }
ResponseRootDeserializer { public static boolean needConvert(Object obj, JavaType invocationTimeType) { if (obj == null || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || invocationTimeType.isPrimitive() || ProtoConst.OBJECT_TYPE.equals(invocationTimeType)) { return false; } if (obj.getClass() == invocationTimeType.getRawClass()) { return false; } if (invocationTimeType.getRawClass().isAssignableFrom(obj.getClass())) { if (invocationTimeType.getContentType() == null) { return false; } } return true; } ResponseRootDeserializer(RootDeserializer<T> rootDeserializer, boolean empty); @SuppressWarnings("unchecked") T deserialize(byte[] bytes, JavaType invocationTimeType); static boolean needConvert(Object obj, JavaType invocationTimeType); }
ResponseRootDeserializer { public static boolean needConvert(Object obj, JavaType invocationTimeType) { if (obj == null || ClassUtils.isPrimitiveOrWrapper(obj.getClass()) || invocationTimeType.isPrimitive() || ProtoConst.OBJECT_TYPE.equals(invocationTimeType)) { return false; } if (obj.getClass() == invocationTimeType.getRawClass()) { return false; } if (invocationTimeType.getRawClass().isAssignableFrom(obj.getClass())) { if (invocationTimeType.getContentType() == null) { return false; } } return true; } ResponseRootDeserializer(RootDeserializer<T> rootDeserializer, boolean empty); @SuppressWarnings("unchecked") T deserialize(byte[] bytes, JavaType invocationTimeType); static boolean needConvert(Object obj, JavaType invocationTimeType); }
@Test public void testArgsToRest() { try { Map<String, Object> args = new HashMap<>(); args.put("header", "abc"); RestCodec.argsToRest(args, restOperation, clientRequest); Assert.assertEquals("abc", header.get("header")); } catch (Exception e) { e.printStackTrace(); Assert.assertTrue(false); } }
public static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest) throws Exception { int paramSize = restOperation.getParamList().size(); if (paramSize == 0) { return; } for (int idx = 0; idx < paramSize; idx++) { RestParam param = restOperation.getParamList().get(idx); param.getParamProcessor().setValue(clientRequest, args.get(param.getParamName())); } }
RestCodec { public static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest) throws Exception { int paramSize = restOperation.getParamList().size(); if (paramSize == 0) { return; } for (int idx = 0; idx < paramSize; idx++) { RestParam param = restOperation.getParamList().get(idx); param.getParamProcessor().setValue(clientRequest, args.get(param.getParamName())); } } }
RestCodec { public static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest) throws Exception { int paramSize = restOperation.getParamList().size(); if (paramSize == 0) { return; } for (int idx = 0; idx < paramSize; idx++) { RestParam param = restOperation.getParamList().get(idx); param.getParamProcessor().setValue(clientRequest, args.get(param.getParamName())); } } private RestCodec(); }
RestCodec { public static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest) throws Exception { int paramSize = restOperation.getParamList().size(); if (paramSize == 0) { return; } for (int idx = 0; idx < paramSize; idx++) { RestParam param = restOperation.getParamList().get(idx); param.getParamProcessor().setValue(clientRequest, args.get(param.getParamName())); } } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
RestCodec { public static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest) throws Exception { int paramSize = restOperation.getParamList().size(); if (paramSize == 0) { return; } for (int idx = 0; idx < paramSize; idx++) { RestParam param = restOperation.getParamList().get(idx); param.getParamProcessor().setValue(clientRequest, args.get(param.getParamName())); } } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
@Test public void testRestToArgs(@Mocked HttpServletRequest request, @Mocked RestOperationMeta restOperation, @Mocked RestParam restParam, @Mocked ParamValueProcessor processer) throws Exception { List<RestParam> params = new ArrayList<>(); params.add(restParam); String s = "my"; new Expectations() { { restOperation.getParamList(); result = params; restParam.getParamProcessor(); result = processer; processer.getValue(request); result = s; restParam.getParamName(); result = "test"; } }; Map<String, Object> xx = RestCodec.restToArgs(request, restOperation); Assert.assertEquals(xx.get("test"), s); }
public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
@Test public void findServiceInstance_consumerId_null() { new MockUp<RestClientUtil>() { @Mock void get(IpPort ipPort, String uri, RequestParam requestParam, Handler<RestResponse> responseHandler) { Assert.assertEquals("appId=appId&global=true&serviceName=serviceName&version=1.0.0%2B", requestParam.getQueryParams()); } }; Assert.assertNull(oClient.findServiceInstance(null, "appId", "serviceName", "1.0.0+")); }
@Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule) { MicroserviceInstances instances = findServiceInstances(consumerId, appId, serviceName, versionRule, null); if (instances == null) { return null; } return instances.getInstancesResponse().getInstances(); } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
@Test public void testRestToArgsExcetpion(@Mocked HttpServletRequest request, @Mocked RestOperationMeta restOperation, @Mocked RestParam restParam, @Mocked ParamValueProcessor processer) throws Exception { List<RestParam> params = new ArrayList<>(); params.add(restParam); new Expectations() { { restOperation.getParamList(); result = params; restParam.getParamProcessor(); result = processer; processer.getValue(request); result = new Exception("bad request parame"); } }; boolean success = false; try { RestCodec.restToArgs(request, restOperation); success = true; } catch (InvocationException e) { Assert.assertEquals(400, e.getStatusCode()); Assert.assertTrue(((CommonExceptionData) e.getErrorData()).getMessage().contains("Parameter is not valid")); } Assert.assertEquals(success, false); }
public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
@Test public void testRestToArgsInstanceExcetpion(@Mocked HttpServletRequest request, @Mocked RestOperationMeta restOperation, @Mocked RestParam restParam, @Mocked ParamValueProcessor processer) throws Exception { List<RestParam> params = new ArrayList<>(); params.add(restParam); InvocationException exception = new InvocationException(Status.BAD_REQUEST, "Parameter is not valid."); new Expectations() { { restOperation.getParamList(); result = params; restParam.getParamProcessor(); result = processer; processer.getValue(request); result = exception; } }; boolean success = false; try { RestCodec.restToArgs(request, restOperation); success = true; } catch (InvocationException e) { Assert.assertEquals(e.getStatusCode(), Status.BAD_REQUEST.getStatusCode()); } Assert.assertEquals(success, false); }
public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
RestCodec { public static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation) throws InvocationException { List<RestParam> paramList = restOperation.getParamList(); Map<String, Object> paramValues = new HashMap<>(); for (int idx = 0; idx < paramList.size(); idx++) { RestParam param = paramList.get(idx); try { paramValues.put(param.getParamName(), param.getParamProcessor().getValue(request)); } catch (Exception e) { String message = String .format("Parameter is not valid for operation [%s]. Parameter is [%s]. Processor is [%s].", restOperation.getOperationMeta().getMicroserviceQualifiedName(), param.getParamName(), param.getParamProcessor().getProcessorType()); if (DynamicPropertyFactory.getInstance().getBooleanProperty( RestConst.PRINT_CODEC_ERROR_MESSGAGE, false).get()) { LOG.error(message, e); } else { LOG.error("{} Add {}=true to print the details.", message, RestConst.PRINT_CODEC_ERROR_MESSGAGE); } throw new InvocationException(Status.BAD_REQUEST, message); } } return paramValues; } private RestCodec(); static void argsToRest(Map<String, Object> args, RestOperationMeta restOperation, RestClientRequest clientRequest); static Map<String, Object> restToArgs(HttpServletRequest request, RestOperationMeta restOperation); }
@Test public void testSetSerializationView() { Assert.assertEquals(DEFAULT_SERIAL_CLASS, pp.getSerializationView()); pp.setSerializationView(null); Assert.assertEquals(DEFAULT_SERIAL_CLASS, pp.getSerializationView()); pp.setSerializationView(Object.class); Assert.assertEquals(Object.class.getCanonicalName(), pp.getSerializationView()); }
@Override public void setSerializationView(Class<?> serializationView) { if (serializationView == null) { return; } this.serializationView = serializationView; }
ProduceJsonProcessor implements ProduceProcessor { @Override public void setSerializationView(Class<?> serializationView) { if (serializationView == null) { return; } this.serializationView = serializationView; } }
ProduceJsonProcessor implements ProduceProcessor { @Override public void setSerializationView(Class<?> serializationView) { if (serializationView == null) { return; } this.serializationView = serializationView; } }
ProduceJsonProcessor implements ProduceProcessor { @Override public void setSerializationView(Class<?> serializationView) { if (serializationView == null) { return; } this.serializationView = serializationView; } @Override String getSerializationView(); @Override void setSerializationView(Class<?> serializationView); @Override String getName(); @Override void doEncodeResponse(OutputStream output, Object result); @Override Object doDecodeResponse(InputStream input, JavaType type); @Override int getOrder(); }
ProduceJsonProcessor implements ProduceProcessor { @Override public void setSerializationView(Class<?> serializationView) { if (serializationView == null) { return; } this.serializationView = serializationView; } @Override String getSerializationView(); @Override void setSerializationView(Class<?> serializationView); @Override String getName(); @Override void doEncodeResponse(OutputStream output, Object result); @Override Object doDecodeResponse(InputStream input, JavaType type); @Override int getOrder(); }
@Test public void testCreate() { ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(PathProcessorCreator.PARAMTYPE); Parameter parameter = new PathParameter(); parameter.setName("path"); ParamValueProcessor processor = creator.create(parameter, String.class); Assert.assertEquals(PathProcessor.class, processor.getClass()); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new PathProcessor(parameter.getName(), targetType, ((PathParameter) parameter).getDefaultValue(), true); }
PathProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new PathProcessor(parameter.getName(), targetType, ((PathParameter) parameter).getDefaultValue(), true); } }
PathProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new PathProcessor(parameter.getName(), targetType, ((PathParameter) parameter).getDefaultValue(), true); } PathProcessorCreator(); }
PathProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new PathProcessor(parameter.getName(), targetType, ((PathParameter) parameter).getDefaultValue(), true); } PathProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
PathProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new PathProcessor(parameter.getName(), targetType, ((PathParameter) parameter).getDefaultValue(), true); } PathProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@Test public void testCreate() { ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(FormProcessorCreator.PARAMTYPE); FormParameter p = new FormParameter(); p.setName("p1"); ParamValueProcessor processor = creator.create(p, String.class); Assert.assertEquals(FormProcessor.class, processor.getClass()); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); if (isPart(parameter)) { return new PartProcessor((FormParameter) parameter, genericParamType); } return new FormProcessor((FormParameter) parameter, targetType); }
FormProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); if (isPart(parameter)) { return new PartProcessor((FormParameter) parameter, genericParamType); } return new FormProcessor((FormParameter) parameter, targetType); } }
FormProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); if (isPart(parameter)) { return new PartProcessor((FormParameter) parameter, genericParamType); } return new FormProcessor((FormParameter) parameter, targetType); } FormProcessorCreator(); }
FormProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); if (isPart(parameter)) { return new PartProcessor((FormParameter) parameter, genericParamType); } return new FormProcessor((FormParameter) parameter, targetType); } FormProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
FormProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); if (isPart(parameter)) { return new PartProcessor((FormParameter) parameter, genericParamType); } return new FormProcessor((FormParameter) parameter, targetType); } FormProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@Test public void testCreate() { ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(QueryProcessorCreator.PARAMTYPE); Parameter parameter = new QueryParameter(); parameter.setName("query"); ParamValueProcessor processor = creator.create(parameter, String.class); Assert.assertEquals(QueryProcessor.class, processor.getClass()); String result = (String) processor.convertValue("Hello", TypeFactory.defaultInstance().constructType(String.class)); Assert.assertEquals("Hello", result); result = (String) processor.convertValue("", TypeFactory.defaultInstance().constructType(String.class)); Assert.assertEquals("", result); result = (String) processor.convertValue(null, TypeFactory.defaultInstance().constructType(String.class)); Assert.assertEquals(null, result); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } QueryProcessorCreator(); }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } QueryProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } QueryProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@SuppressWarnings("UnusedAssignment") @Test public void testCreateNullAsEmpty() throws Exception { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); ArchaiusUtils.setProperty("servicecomb.rest.parameter.query.emptyAsNull", "true"); ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(QueryProcessorCreator.PARAMTYPE); Parameter parameter = new QueryParameter(); parameter.setName("query"); ParamValueProcessor processor = creator.create(parameter, String.class); Assert.assertEquals(QueryProcessor.class, processor.getClass()); Mockito.when(request.getParameter("query")).thenReturn("Hello"); String result = (String) processor.getValue(request); Assert.assertEquals("Hello", result); Mockito.when(request.getParameter("query")).thenReturn(""); result = (String) processor.getValue(request); Assert.assertEquals(null, result); Mockito.when(request.getParameter("query")).thenReturn(null); result = (String) processor.convertValue(null, TypeFactory.defaultInstance().constructType(String.class)); result = (String) processor.getValue(request); Assert.assertEquals(null, result); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } QueryProcessorCreator(); }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } QueryProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
QueryProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new QueryProcessor((QueryParameter) parameter, targetType); } QueryProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@Test public void fileBoundaryInfo_nullSubmittedFileName(@Mocked Part part) { new Expectations() { { part.getSubmittedFileName(); result = null; part.getContentType(); result = "abc"; } }; RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part); Assert.assertEquals("\r\n" + "--boundary\r\n" + "Content-Disposition: form-data; name=\"name\"; filename=\"null\"\r\n" + "Content-Type: abc\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n", buffer.toString()); }
protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
@Test public void fileBoundaryInfo_validSubmittedFileName(@Mocked Part part) { new Expectations() { { part.getSubmittedFileName(); result = "a.txt"; part.getContentType(); result = MediaType.TEXT_PLAIN; } }; RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part); Assert.assertEquals("\r\n" + "--boundary\r\n" + "Content-Disposition: form-data; name=\"name\"; filename=\"a.txt\"\r\n" + "Content-Type: text/plain\r\n" + "Content-Transfer-Encoding: binary\r\n" + "\r\n", buffer.toString()); }
protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
RestClientRequestImpl implements RestClientRequest { protected Buffer fileBoundaryInfo(String boundary, String name, Part part) { Buffer buffer = Buffer.buffer(); buffer.appendString("\r\n"); buffer.appendString("--" + boundary + "\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"") .appendString(name) .appendString("\"; filename=\"") .appendString(part.getSubmittedFileName() != null ? part.getSubmittedFileName() : "null") .appendString("\"\r\n"); buffer.appendString("Content-Type: ").appendString(part.getContentType()).appendString("\r\n"); buffer.appendString("Content-Transfer-Encoding: binary\r\n"); buffer.appendString("\r\n"); return buffer; } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
@Test public void testAttach() { RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); Part part = Mockito.mock(Part.class); String fileName = "fileName"; restClientRequest.attach(fileName, part); Multimap<String, Part> uploads = Deencapsulation.getField(restClientRequest, "uploads"); Assert.assertEquals(1, uploads.size()); Assert.assertThat(uploads.asMap(), Matchers.hasEntry(fileName, Arrays.asList(part))); }
@Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
@Test public void findServiceInstances_microserviceNotExist() { HttpClientResponse response = new MockUp<HttpClientResponse>() { @Mock int statusCode() { return 400; } @Mock HttpClientResponse bodyHandler(Handler<Buffer> bodyHandler) { Buffer bodyBuffer = Buffer.buffer("{\"errorCode\":\"400012\"}"); bodyHandler.handle(bodyBuffer); return null; } }.getMockInstance(); RestResponse restResponse = new RestResponse(null, response); new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Assert.assertEquals("appId=appId&global=true&serviceName=serviceName&version=0.0.0.0%2B", requestContext.getParams().getQueryParams()); restResponse.setRequestContext(requestContext); responseHandler.handle(restResponse); } }; MicroserviceInstances microserviceInstances = oClient .findServiceInstances("consumerId", "appId", "serviceName", DefinitionConst.VERSION_RULE_ALL, null); Assert.assertTrue(microserviceInstances.isMicroserviceNotExist()); Assert.assertFalse(microserviceInstances.isNeedRefresh()); }
@Override public MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision) { MicroserviceInstances microserviceInstances = new MicroserviceInstances(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); RequestParam requestParam = new RequestParam().addQueryParam("appId", appId) .addQueryParam("serviceName", serviceName) .addQueryParam("global", "true") .addQueryParam("version", versionRule); if (RegistryUtils.getMicroservice().getEnvironment() != null) { requestParam.addQueryParam("env", RegistryUtils.getMicroservice().getEnvironment()); } if (consumerId != null) { requestParam.addHeader("X-ConsumerId", consumerId); } if (revision != null) { requestParam.addQueryParam("rev", revision); } restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_INSTANCES, requestParam, syncHandlerForInstances(countDownLatch, microserviceInstances)); try { countDownLatch.await(); if (!microserviceInstances.isNeedRefresh()) { return microserviceInstances; } if (microserviceInstances.getInstancesResponse() == null) { return null; } List<MicroserviceInstance> list = microserviceInstances.getInstancesResponse().getInstances(); if (list == null) { microserviceInstances.getInstancesResponse().setInstances(new ArrayList<>()); } return microserviceInstances; } catch (Exception e) { LOGGER.error("find microservice instance {}/{}/{} failed", appId, serviceName, versionRule, e); } return null; }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision) { MicroserviceInstances microserviceInstances = new MicroserviceInstances(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); RequestParam requestParam = new RequestParam().addQueryParam("appId", appId) .addQueryParam("serviceName", serviceName) .addQueryParam("global", "true") .addQueryParam("version", versionRule); if (RegistryUtils.getMicroservice().getEnvironment() != null) { requestParam.addQueryParam("env", RegistryUtils.getMicroservice().getEnvironment()); } if (consumerId != null) { requestParam.addHeader("X-ConsumerId", consumerId); } if (revision != null) { requestParam.addQueryParam("rev", revision); } restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_INSTANCES, requestParam, syncHandlerForInstances(countDownLatch, microserviceInstances)); try { countDownLatch.await(); if (!microserviceInstances.isNeedRefresh()) { return microserviceInstances; } if (microserviceInstances.getInstancesResponse() == null) { return null; } List<MicroserviceInstance> list = microserviceInstances.getInstancesResponse().getInstances(); if (list == null) { microserviceInstances.getInstancesResponse().setInstances(new ArrayList<>()); } return microserviceInstances; } catch (Exception e) { LOGGER.error("find microservice instance {}/{}/{} failed", appId, serviceName, versionRule, e); } return null; } }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision) { MicroserviceInstances microserviceInstances = new MicroserviceInstances(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); RequestParam requestParam = new RequestParam().addQueryParam("appId", appId) .addQueryParam("serviceName", serviceName) .addQueryParam("global", "true") .addQueryParam("version", versionRule); if (RegistryUtils.getMicroservice().getEnvironment() != null) { requestParam.addQueryParam("env", RegistryUtils.getMicroservice().getEnvironment()); } if (consumerId != null) { requestParam.addHeader("X-ConsumerId", consumerId); } if (revision != null) { requestParam.addQueryParam("rev", revision); } restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_INSTANCES, requestParam, syncHandlerForInstances(countDownLatch, microserviceInstances)); try { countDownLatch.await(); if (!microserviceInstances.isNeedRefresh()) { return microserviceInstances; } if (microserviceInstances.getInstancesResponse() == null) { return null; } List<MicroserviceInstance> list = microserviceInstances.getInstancesResponse().getInstances(); if (list == null) { microserviceInstances.getInstancesResponse().setInstances(new ArrayList<>()); } return microserviceInstances; } catch (Exception e) { LOGGER.error("find microservice instance {}/{}/{} failed", appId, serviceName, versionRule, e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision) { MicroserviceInstances microserviceInstances = new MicroserviceInstances(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); RequestParam requestParam = new RequestParam().addQueryParam("appId", appId) .addQueryParam("serviceName", serviceName) .addQueryParam("global", "true") .addQueryParam("version", versionRule); if (RegistryUtils.getMicroservice().getEnvironment() != null) { requestParam.addQueryParam("env", RegistryUtils.getMicroservice().getEnvironment()); } if (consumerId != null) { requestParam.addHeader("X-ConsumerId", consumerId); } if (revision != null) { requestParam.addQueryParam("rev", revision); } restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_INSTANCES, requestParam, syncHandlerForInstances(countDownLatch, microserviceInstances)); try { countDownLatch.await(); if (!microserviceInstances.isNeedRefresh()) { return microserviceInstances; } if (microserviceInstances.getInstancesResponse() == null) { return null; } List<MicroserviceInstance> list = microserviceInstances.getInstancesResponse().getInstances(); if (list == null) { microserviceInstances.getInstancesResponse().setInstances(new ArrayList<>()); } return microserviceInstances; } catch (Exception e) { LOGGER.error("find microservice instance {}/{}/{} failed", appId, serviceName, versionRule, e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision) { MicroserviceInstances microserviceInstances = new MicroserviceInstances(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); RequestParam requestParam = new RequestParam().addQueryParam("appId", appId) .addQueryParam("serviceName", serviceName) .addQueryParam("global", "true") .addQueryParam("version", versionRule); if (RegistryUtils.getMicroservice().getEnvironment() != null) { requestParam.addQueryParam("env", RegistryUtils.getMicroservice().getEnvironment()); } if (consumerId != null) { requestParam.addHeader("X-ConsumerId", consumerId); } if (revision != null) { requestParam.addQueryParam("rev", revision); } restClientUtil.get(ipPort, Const.REGISTRY_API.MICROSERVICE_INSTANCES, requestParam, syncHandlerForInstances(countDownLatch, microserviceInstances)); try { countDownLatch.await(); if (!microserviceInstances.isNeedRefresh()) { return microserviceInstances; } if (microserviceInstances.getInstancesResponse() == null) { return null; } List<MicroserviceInstance> list = microserviceInstances.getInstancesResponse().getInstances(); if (list == null) { microserviceInstances.getInstancesResponse().setInstances(new ArrayList<>()); } return microserviceInstances; } catch (Exception e) { LOGGER.error("find microservice instance {}/{}/{} failed", appId, serviceName, versionRule, e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
@Test public void testAttachOnPartIsNull() { RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); restClientRequest.attach("fileName", null); Multimap<String, Part> uploads = Deencapsulation.getField(restClientRequest, "uploads"); Assert.assertTrue(uploads.isEmpty()); }
@Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
RestClientRequestImpl implements RestClientRequest { @Override @SuppressWarnings("unchecked") public void attach(String name, Object partOrList) { if (null == partOrList) { LOGGER.debug("null file is ignored, file name = [{}]", name); return; } if (partOrList.getClass().isArray()) { for (Object part : (Object[]) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } } if (List.class.isAssignableFrom(partOrList.getClass())) { for (Object part : (List<Object>) partOrList) { uploads.put(name, PartUtils.getSinglePart(name, part)); } return; } uploads.put(name, PartUtils.getSinglePart(name, partOrList)); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
@Test public void doEndWithUpload() { Map<String, String> headers = new HashMap<>(); new MockUp<HttpClientRequest>(request) { @Mock HttpClientRequest putHeader(String name, String value) { headers.put(name, value); return request; } }; UUID uuid = new UUID(0, 0); new Expectations(UUID.class) { { UUID.randomUUID(); result = uuid; } }; RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null); restClientRequest.doEndWithUpload(); Assert.assertEquals("multipart/form-data; charset=UTF-8; boundary=boundary00000000-0000-0000-0000-000000000000", headers.get(HttpHeaders.CONTENT_TYPE.toString())); }
protected void doEndWithUpload() { request.setChunked(true); String boundary = "boundary" + UUID.randomUUID().toString(); putHeader(CONTENT_TYPE, MULTIPART_FORM_DATA + "; charset=UTF-8; boundary=" + boundary); genBodyForm(boundary); attachFiles(boundary); }
RestClientRequestImpl implements RestClientRequest { protected void doEndWithUpload() { request.setChunked(true); String boundary = "boundary" + UUID.randomUUID().toString(); putHeader(CONTENT_TYPE, MULTIPART_FORM_DATA + "; charset=UTF-8; boundary=" + boundary); genBodyForm(boundary); attachFiles(boundary); } }
RestClientRequestImpl implements RestClientRequest { protected void doEndWithUpload() { request.setChunked(true); String boundary = "boundary" + UUID.randomUUID().toString(); putHeader(CONTENT_TYPE, MULTIPART_FORM_DATA + "; charset=UTF-8; boundary=" + boundary); genBodyForm(boundary); attachFiles(boundary); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); }
RestClientRequestImpl implements RestClientRequest { protected void doEndWithUpload() { request.setChunked(true); String boundary = "boundary" + UUID.randomUUID().toString(); putHeader(CONTENT_TYPE, MULTIPART_FORM_DATA + "; charset=UTF-8; boundary=" + boundary); genBodyForm(boundary); attachFiles(boundary); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
RestClientRequestImpl implements RestClientRequest { protected void doEndWithUpload() { request.setChunked(true); String boundary = "boundary" + UUID.randomUUID().toString(); putHeader(CONTENT_TYPE, MULTIPART_FORM_DATA + "; charset=UTF-8; boundary=" + boundary); genBodyForm(boundary); attachFiles(boundary); } RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp); RestClientRequestImpl(HttpClientRequest request, Context context, AsyncResponse asyncResp, Handler<Throwable> throwableHandler); @Override void write(Buffer bodyBuffer); @Override Buffer getBodyBuffer(); @Override @SuppressWarnings("unchecked") void attach(String name, Object partOrList); @Override void end(); Context getContext(); HttpClientRequest getRequest(); Map<String, String> getCookieMap(); Map<String, Object> getFormMap(); @Override void addCookie(String name, String value); @Override void addForm(String name, Object value); @Override void putHeader(String name, String value); @Override MultiMap getHeaders(); }
@Test public void testCreateNormal() { ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(BodyProcessorCreator.PARAMTYPE); BodyParameter param = new BodyParameter(); ParamValueProcessor processor = creator.create(param, String.class); Assert.assertEquals(BodyProcessor.class, processor.getClass()); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } BodyProcessorCreator(); }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } BodyProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } BodyProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@Test public void testCreateRawJson() { ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(BodyProcessorCreator.PARAMTYPE); BodyParameter param = new BodyParameter(); param.setVendorExtension(SwaggerConst.EXT_RAW_JSON_TYPE, true); ParamValueProcessor processor = creator.create(param, String.class); Assert.assertEquals(RawJsonBodyProcessor.class, processor.getClass()); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } BodyProcessorCreator(); }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } BodyProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
BodyProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { Model model = ((BodyParameter) parameter).getSchema(); JavaType swaggerType = null; if (model instanceof ModelImpl) { swaggerType = ConverterMgr.findJavaType(((ModelImpl) model).getType(), ((ModelImpl) model).getFormat()); } boolean isString = swaggerType != null && swaggerType.getRawClass().equals(String.class); JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = SwaggerUtils.isRawJsonType(parameter); if (rawJson) { return new RawJsonBodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } return new BodyProcessor(targetType, (String) parameter.getVendorExtensions() .get(SwaggerConst.EXT_JSON_VIEW), isString, parameter.getRequired()); } BodyProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@Test public void testCreate() { ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(HeaderProcessorCreator.PARAMTYPE); HeaderParameter hp = new HeaderParameter(); hp.setName("h1"); ParamValueProcessor processor = creator.create(hp, String.class); Assert.assertEquals(HeaderProcessor.class, processor.getClass()); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new HeaderProcessor((HeaderParameter) parameter, targetType); }
HeaderProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new HeaderProcessor((HeaderParameter) parameter, targetType); } }
HeaderProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new HeaderProcessor((HeaderParameter) parameter, targetType); } HeaderProcessorCreator(); }
HeaderProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new HeaderProcessor((HeaderParameter) parameter, targetType); } HeaderProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
HeaderProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new HeaderProcessor((HeaderParameter) parameter, targetType); } HeaderProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@Test public void testCreate() { ParamValueProcessorCreator creator = ParamValueProcessorCreatorManager.INSTANCE.findValue(CookieProcessorCreator.PARAMTYPE); CookieParameter p = new CookieParameter(); p.setName("p1"); ParamValueProcessor processor = creator.create(p, String.class); Assert.assertEquals(CookieProcessor.class, processor.getClass()); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new CookieProcessor(parameter.getName(), targetType, ((CookieParameter) parameter).getDefaultValue(), parameter.getRequired()); }
CookieProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new CookieProcessor(parameter.getName(), targetType, ((CookieParameter) parameter).getDefaultValue(), parameter.getRequired()); } }
CookieProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new CookieProcessor(parameter.getName(), targetType, ((CookieParameter) parameter).getDefaultValue(), parameter.getRequired()); } CookieProcessorCreator(); }
CookieProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new CookieProcessor(parameter.getName(), targetType, ((CookieParameter) parameter).getDefaultValue(), parameter.getRequired()); } CookieProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); }
CookieProcessorCreator implements ParamValueProcessorCreator { @Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = genericParamType == null ? null : TypeFactory.defaultInstance().constructType(genericParamType); return new CookieProcessor(parameter.getName(), targetType, ((CookieParameter) parameter).getDefaultValue(), parameter.getRequired()); } CookieProcessorCreator(); @Override ParamValueProcessor create(Parameter parameter, Type genericParamType); static final String PARAMTYPE; }
@Test public void should_failed_when_not_defined_any_schema() { mockGetServicePathManager(null); InvocationException throwable = (InvocationException) catchThrowable(() -> creator.create()); CommonExceptionData data = (CommonExceptionData) throwable.getErrorData(); assertThat(throwable.getStatusCode()).isEqualTo(NOT_FOUND.getStatusCode()); assertThat(Json.encode(data)).isEqualTo("{\"code\":\"SCB.00000002\",\"message\":\"Not Found\"}"); }
@Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
@Test public void should_failed_when_accept_is_not_support() { mockGetServicePathManager(); new Expectations() { { requestEx.getHeader(HttpHeaders.ACCEPT); result = "test-type"; restOperationMeta.ensureFindProduceProcessor(requestEx); result = null; } }; InvocationException throwable = (InvocationException) catchThrowable(() -> creator.create()); CommonExceptionData data = (CommonExceptionData) throwable.getErrorData(); assertThat(throwable.getStatusCode()).isEqualTo(NOT_ACCEPTABLE.getStatusCode()); assertThat(Json.encode(data)) .isEqualTo("{\"code\":\"SCB.00000000\",\"message\":\"Accept test-type is not supported\"}"); }
@Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
@Test public void should_save_requestEx_in_invocation_context() { mockGetServicePathManager(); Invocation invocation = creator.create(); Object request = invocation.getLocalContext(RestConst.REST_REQUEST); assertThat(request).isSameAs(requestEx); }
@Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
@Test public void should_save_path_var_map_in_requestEx() { mockGetServicePathManager(); creator.create(); new Verifications() { { requestEx.setAttribute(RestConst.PATH_PARAMETERS, any); times = 1; } }; }
@Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
@Test public void testGetServiceCenterInfoSuccess() { ServiceCenterInfo serviceCenterInfo = new ServiceCenterInfo(); serviceCenterInfo.setVersion("x.x.x"); serviceCenterInfo.setBuildTag("xxx"); serviceCenterInfo.setRunMode("dev"); serviceCenterInfo.setApiVersion("x.x.x"); serviceCenterInfo.setConfig(new ServiceCenterConfig()); new MockUp<RestClientUtil>() { @Mock void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) { Holder<ServiceCenterInfo> holder = Deencapsulation.getField(responseHandler, "arg$4"); holder.value = serviceCenterInfo; } }; ServiceCenterInfo info = oClient.getServiceCenterInfo(); Assert.assertEquals("x.x.x", info.getVersion()); Assert.assertEquals("xxx", info.getBuildTag()); Assert.assertEquals("dev", info.getRunMode()); Assert.assertNotNull(info.getConfig()); }
@Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
@Test public void should_merge_invocation_context_from_request() { mockGetServicePathManager(); new Expectations() { { requestEx.getHeader(Const.CSE_CONTEXT); result = "{\"k\":\"v\"}"; } }; Invocation invocation = creator.create(); assertThat(invocation.getContext("k")).isEqualTo("v"); }
@Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
RestProducerInvocationCreator implements InvocationCreator { @Override public Invocation create() { initRestOperation(); Invocation invocation = InvocationFactory.forProvider(endpoint, restOperationMeta.getOperationMeta(), null); initInvocationContext(invocation); initProduceProcessor(); initTransportContext(invocation); invocation.addLocalContext(RestConst.REST_REQUEST, requestEx); return invocation; } RestProducerInvocationCreator(@Nonnull MicroserviceMeta microserviceMeta, @Nonnull Endpoint endpoint, @Nonnull HttpServletRequestEx requestEx, @Nonnull HttpServletResponseEx responseEx); @Override Invocation create(); }
@Test public void runSucc() throws InterruptedException, ExecutionException { CompletableFuture<Void> result = executor.run(); Assert.assertNull(result.get()); }
public CompletableFuture<Void> run() { doRun(); return future; }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } HttpServerFilterBeforeSendResponseExecutor(List<HttpServerFilter> httpServerFilters, Invocation invocation, HttpServletResponseEx responseEx); }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } HttpServerFilterBeforeSendResponseExecutor(List<HttpServerFilter> httpServerFilters, Invocation invocation, HttpServletResponseEx responseEx); CompletableFuture<Void> run(); }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } HttpServerFilterBeforeSendResponseExecutor(List<HttpServerFilter> httpServerFilters, Invocation invocation, HttpServletResponseEx responseEx); CompletableFuture<Void> run(); }
@Test public void runFail() throws InterruptedException, ExecutionException { httpServerFilters.add(new HttpServerFilterBaseForTest() { @Override public CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx) { throw new RuntimeExceptionWithoutStackTrace(); } }); CompletableFuture<Void> result = executor.run(); expectedException.expect(ExecutionException.class); expectedException.expectCause(Matchers.instanceOf(RuntimeExceptionWithoutStackTrace.class)); result.get(); }
public CompletableFuture<Void> run() { doRun(); return future; }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } HttpServerFilterBeforeSendResponseExecutor(List<HttpServerFilter> httpServerFilters, Invocation invocation, HttpServletResponseEx responseEx); }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } HttpServerFilterBeforeSendResponseExecutor(List<HttpServerFilter> httpServerFilters, Invocation invocation, HttpServletResponseEx responseEx); CompletableFuture<Void> run(); }
HttpServerFilterBeforeSendResponseExecutor { public CompletableFuture<Void> run() { doRun(); return future; } HttpServerFilterBeforeSendResponseExecutor(List<HttpServerFilter> httpServerFilters, Invocation invocation, HttpServletResponseEx responseEx); CompletableFuture<Void> run(); }
@Test public void asyncBeforeSendResponse_part(@Mocked RestOperationMeta restOperationMeta) { ResponsesMeta responsesMeta = new ResponsesMeta(); responsesMeta.getResponseMap().put(202, RestObjectMapperFactory.getRestObjectMapper().constructType(Part.class)); new Expectations(RestMetaUtils.class) { { responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE); result = response; response.getResult(); result = part; response.getStatusCode(); result = 202; invocation.findResponseType(202); result = TypeFactory.defaultInstance().constructType(Part.class); } }; new MockUp<HttpServletResponseEx>(responseEx) { @Mock CompletableFuture<Void> sendPart(Part body) { invokedSendPart = true; return null; } }; Assert.assertNull(filter.beforeSendResponseAsync(invocation, responseEx)); Assert.assertTrue(invokedSendPart); }
@Override public CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx) { Response response = (Response) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE); ProduceProcessor produceProcessor = (ProduceProcessor) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR); Object body = response.getResult(); if (response.isFailed()) { body = ((InvocationException) body).getErrorData(); } if (null != invocation && isDownloadFileResponseType(invocation, response)) { return responseEx.sendPart(PartUtils.getSinglePart(null, body)); } responseEx.setContentType(produceProcessor.getName() + "; charset=utf-8"); CompletableFuture<Void> future = new CompletableFuture<>(); try (BufferOutputStream output = new BufferOutputStream(Unpooled.compositeBuffer())) { produceProcessor.encodeResponse(output, body); responseEx.setBodyBuffer(output.getBuffer()); future.complete(null); } catch (Throwable e) { future.completeExceptionally(ExceptionFactory.convertProducerException(e)); } return future; }
ServerRestArgsFilter implements HttpServerFilter { @Override public CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx) { Response response = (Response) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE); ProduceProcessor produceProcessor = (ProduceProcessor) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR); Object body = response.getResult(); if (response.isFailed()) { body = ((InvocationException) body).getErrorData(); } if (null != invocation && isDownloadFileResponseType(invocation, response)) { return responseEx.sendPart(PartUtils.getSinglePart(null, body)); } responseEx.setContentType(produceProcessor.getName() + "; charset=utf-8"); CompletableFuture<Void> future = new CompletableFuture<>(); try (BufferOutputStream output = new BufferOutputStream(Unpooled.compositeBuffer())) { produceProcessor.encodeResponse(output, body); responseEx.setBodyBuffer(output.getBuffer()); future.complete(null); } catch (Throwable e) { future.completeExceptionally(ExceptionFactory.convertProducerException(e)); } return future; } }
ServerRestArgsFilter implements HttpServerFilter { @Override public CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx) { Response response = (Response) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE); ProduceProcessor produceProcessor = (ProduceProcessor) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR); Object body = response.getResult(); if (response.isFailed()) { body = ((InvocationException) body).getErrorData(); } if (null != invocation && isDownloadFileResponseType(invocation, response)) { return responseEx.sendPart(PartUtils.getSinglePart(null, body)); } responseEx.setContentType(produceProcessor.getName() + "; charset=utf-8"); CompletableFuture<Void> future = new CompletableFuture<>(); try (BufferOutputStream output = new BufferOutputStream(Unpooled.compositeBuffer())) { produceProcessor.encodeResponse(output, body); responseEx.setBodyBuffer(output.getBuffer()); future.complete(null); } catch (Throwable e) { future.completeExceptionally(ExceptionFactory.convertProducerException(e)); } return future; } }
ServerRestArgsFilter implements HttpServerFilter { @Override public CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx) { Response response = (Response) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE); ProduceProcessor produceProcessor = (ProduceProcessor) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR); Object body = response.getResult(); if (response.isFailed()) { body = ((InvocationException) body).getErrorData(); } if (null != invocation && isDownloadFileResponseType(invocation, response)) { return responseEx.sendPart(PartUtils.getSinglePart(null, body)); } responseEx.setContentType(produceProcessor.getName() + "; charset=utf-8"); CompletableFuture<Void> future = new CompletableFuture<>(); try (BufferOutputStream output = new BufferOutputStream(Unpooled.compositeBuffer())) { produceProcessor.encodeResponse(output, body); responseEx.setBodyBuffer(output.getBuffer()); future.complete(null); } catch (Throwable e) { future.completeExceptionally(ExceptionFactory.convertProducerException(e)); } return future; } @Override int getOrder(); @Override boolean enabled(); @Override Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx); @Override CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx); }
ServerRestArgsFilter implements HttpServerFilter { @Override public CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx) { Response response = (Response) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_RESPONSE); ProduceProcessor produceProcessor = (ProduceProcessor) responseEx.getAttribute(RestConst.INVOCATION_HANDLER_PROCESSOR); Object body = response.getResult(); if (response.isFailed()) { body = ((InvocationException) body).getErrorData(); } if (null != invocation && isDownloadFileResponseType(invocation, response)) { return responseEx.sendPart(PartUtils.getSinglePart(null, body)); } responseEx.setContentType(produceProcessor.getName() + "; charset=utf-8"); CompletableFuture<Void> future = new CompletableFuture<>(); try (BufferOutputStream output = new BufferOutputStream(Unpooled.compositeBuffer())) { produceProcessor.encodeResponse(output, body); responseEx.setBodyBuffer(output.getBuffer()); future.complete(null); } catch (Throwable e) { future.completeExceptionally(ExceptionFactory.convertProducerException(e)); } return future; } @Override int getOrder(); @Override boolean enabled(); @Override Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx); @Override CompletableFuture<Void> beforeSendResponseAsync(Invocation invocation, HttpServletResponseEx responseEx); }
@Test public void should_not_invoke_filter_when_decode_request_failed(@Mocked FilterNode nextNode) { mockDecodeRequestFail(); codecFilter.onFilter(invocation, nextNode); new Verifications() { { nextNode.onFilter(invocation); times = 0; } }; }
@Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } @Override CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode); @SuppressWarnings("deprecation") static CompletableFuture<Response> encodeResponse(Response response, boolean download, ProduceProcessor produceProcessor, HttpServletResponseEx responseEx); static boolean isDownloadFileResponseType(Invocation invocation, Response response); static void copyHeadersToHttpResponse(Map<String, List<Object>> headerMap, HttpServletResponseEx responseEx); }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } @Override CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode); @SuppressWarnings("deprecation") static CompletableFuture<Response> encodeResponse(Response response, boolean download, ProduceProcessor produceProcessor, HttpServletResponseEx responseEx); static boolean isDownloadFileResponseType(Invocation invocation, Response response); static void copyHeadersToHttpResponse(Map<String, List<Object>> headerMap, HttpServletResponseEx responseEx); }
@Test public void should_convert_exception_to_response_when_decode_request_failed() throws ExecutionException, InterruptedException { mockDecodeRequestFail(); new Expectations(invocation) { { invocation.findResponseType(anyInt); result = TypeFactory.defaultInstance().constructType(String.class); } }; Response response = codecFilter.onFilter(invocation, nextNode).get(); assertThat(response.getStatus()).isEqualTo(INTERNAL_SERVER_ERROR); assertThat(Json.encode(response.getResult())) .isEqualTo("{\"code\":\"SCB.50000000\",\"message\":\"encode request failed\"}"); }
@Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } @Override CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode); @SuppressWarnings("deprecation") static CompletableFuture<Response> encodeResponse(Response response, boolean download, ProduceProcessor produceProcessor, HttpServletResponseEx responseEx); static boolean isDownloadFileResponseType(Invocation invocation, Response response); static void copyHeadersToHttpResponse(Map<String, List<Object>> headerMap, HttpServletResponseEx responseEx); }
RestServerCodecFilter implements Filter { @Override public CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode) { return CompletableFuture.completedFuture(invocation) .thenCompose(this::decodeRequest) .thenCompose(nextNode::onFilter) .exceptionally(exception -> exceptionToResponse(invocation, exception, INTERNAL_SERVER_ERROR)) .thenCompose(response -> encodeResponse(invocation, response)); } @Override CompletableFuture<Response> onFilter(Invocation invocation, FilterNode nextNode); @SuppressWarnings("deprecation") static CompletableFuture<Response> encodeResponse(Response response, boolean download, ProduceProcessor produceProcessor, HttpServletResponseEx responseEx); static boolean isDownloadFileResponseType(Invocation invocation, Response response); static void copyHeadersToHttpResponse(Map<String, List<Object>> headerMap, HttpServletResponseEx responseEx); }
@Test public void setHttpServerFilters(@Mocked List<HttpServerFilter> httpServerFilters) { restInvocation.setHttpServerFilters(httpServerFilters); Assert.assertSame(httpServerFilters, restInvocation.httpServerFilters); }
public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) { this.httpServerFilters = httpServerFilters; }
AbstractRestInvocation { public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) { this.httpServerFilters = httpServerFilters; } }
AbstractRestInvocation { public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) { this.httpServerFilters = httpServerFilters; } AbstractRestInvocation(); }
AbstractRestInvocation { public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) { this.httpServerFilters = httpServerFilters; } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) { this.httpServerFilters = httpServerFilters; } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void initProduceProcessorNull() { new Expectations() { { requestEx.getHeader(HttpHeaders.ACCEPT); result = "notExistType"; } }; restInvocation = new AbstractRestInvocationForTest() { @Override public void sendFailResponse(Throwable throwable) { } }; initRestInvocation(); expectedException.expect(InvocationException.class); expectedException .expectMessage( "InvocationException: code=406;msg=CommonExceptionData [message=Accept notExistType is not supported]"); restInvocation.initProduceProcessor(); }
protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } AbstractRestInvocation(); }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void initProduceProcessorNormal() { new Expectations() { { requestEx.getHeader(HttpHeaders.ACCEPT); result = MediaType.APPLICATION_JSON; } }; restInvocation.initProduceProcessor(); }
protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } AbstractRestInvocation(); }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { LOGGER.error("Accept {} is not supported, operation={}.", requestEx.getHeader(HttpHeaders.ACCEPT), restOperationMeta.getOperationMeta().getMicroserviceQualifiedName()); String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void getContext() { invocation.addContext("key", "test"); assertEquals("test", restInvocation.getContext("key")); }
public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } AbstractRestInvocation(); }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void testGetServiceCenterInfoException() { InterruptedException e = new InterruptedException(); new MockUp<CountDownLatch>() { @Mock public void await() throws InterruptedException { throw e; } }; new RegisterSchemaTester() { void doRun(java.util.List<LoggingEvent> events) { oClient.getServiceCenterInfo(); Assert.assertEquals( "query servicecenter version info failed.", events.get(0).getMessage()); Assert.assertEquals(e, events.get(0).getThrowableInformation().getThrowable()); } }.run(); }
@Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
ServiceRegistryClientImpl implements ServiceRegistryClient { @Override public ServiceCenterInfo getServiceCenterInfo() { Holder<ServiceCenterInfo> holder = new Holder<>(); IpPort ipPort = ipPortManager.getAvailableAddress(); CountDownLatch countDownLatch = new CountDownLatch(1); restClientUtil.get(ipPort, Const.REGISTRY_API.SERVICECENTER_VERSION, new RequestParam(), syncHandler(countDownLatch, ServiceCenterInfo.class, holder)); try { countDownLatch.await(); if (holder.value != null) { return holder.value; } } catch (Exception e) { LOGGER.error("query servicecenter version info failed.", e); } return null; } ServiceRegistryClientImpl(ServiceRegistryConfig serviceRegistryConfig); @Override void init(); @Override List<Microservice> getAllMicroservices(); @Override String getMicroserviceId(String appId, String microserviceName, String versionRule, String environment); @Override boolean isSchemaExist(String microserviceId, String schemaId); @Override boolean registerSchema(String microserviceId, String schemaId, String schemaContent); @Override String getSchema(String microserviceId, String schemaId); @Override String getAggregatedSchema(String microserviceId, String schemaId); @Override Holder<List<GetSchemaResponse>> getSchemas(String microserviceId); @Override String registerMicroservice(Microservice microservice); @Override Microservice getMicroservice(String microserviceId); @Override Microservice getAggregatedMicroservice(String microserviceId); @Override String registerMicroserviceInstance(MicroserviceInstance instance); @Override List<MicroserviceInstance> getMicroserviceInstance(String consumerId, String providerId); @Override boolean unregisterMicroserviceInstance(String microserviceId, String microserviceInstanceId); @Override HeartbeatResponse heartbeat(String microserviceId, String microserviceInstanceId); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback); void watch(String selfMicroserviceId, AsyncResultCallback<MicroserviceInstanceChangedEvent> callback, AsyncResultCallback<Void> onOpen, AsyncResultCallback<Void> onClose); @Override List<MicroserviceInstance> findServiceInstance(String consumerId, String appId, String serviceName, String versionRule); @Override MicroserviceInstances findServiceInstances(String consumerId, String appId, String serviceName, String versionRule, String revision); @Override boolean updateMicroserviceProperties(String microserviceId, Map<String, String> serviceProperties); @Override boolean updateInstanceProperties(String microserviceId, String microserviceInstanceId, Map<String, String> instanceProperties); @Override MicroserviceInstance findServiceInstance(String serviceId, String instanceId); @Override ServiceCenterInfo getServiceCenterInfo(); @Override boolean updateMicroserviceInstanceStatus(String microserviceId, String instanceId, MicroserviceInstanceStatus status); @Subscribe void onMicroserviceHeartbeatTask(MicroserviceInstanceHeartbeatTask event); }
@Test public void getContextNull() { Assert.assertNull(restInvocation.getContext("key")); }
public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } AbstractRestInvocation(); }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public String getContext(String key) { if (null == invocation || null == invocation.getContext()) { return null; } return invocation.getContext(key); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void invokeFilterHaveResponse(@Mocked HttpServerFilter filter) { Response response = Response.ok(""); new Expectations() { { filter.enabled(); result = true; filter.afterReceiveRequest(invocation, requestEx); result = response; } }; Holder<Response> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override protected void doInvoke() { result.value = Response.ok("not run to here"); } @Override protected void sendResponseQuietly(Response response) { result.value = response; } }; initRestInvocation(); restInvocation.httpServerFilters = Arrays.asList(filter); restInvocation.invoke(); Assert.assertSame(response, result.value); }
public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void invokeFilterNoResponse(@Mocked HttpServerFilter filter) { new Expectations() { { filter.enabled(); result = true; filter.afterReceiveRequest(invocation, requestEx); result = null; } }; Holder<Boolean> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override protected void doInvoke() { result.value = true; } }; initRestInvocation(); restInvocation.httpServerFilters = Arrays.asList(filter); restInvocation.invoke(); Assert.assertTrue(result.value); }
public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void invokeFilterNoResponseDisableFilter(@Mocked HttpServerFilter filter) { new Expectations() { { filter.enabled(); result = false; } }; Holder<Boolean> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override protected void doInvoke() { result.value = true; } }; initRestInvocation(); restInvocation.httpServerFilters = Arrays.asList(filter); restInvocation.invoke(); Assert.assertTrue(result.value); }
public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void invokeFilterException(@Mocked HttpServerFilter filter) { Exception error = new RuntimeExceptionWithoutStackTrace(); new Expectations() { { filter.enabled(); result = true; filter.afterReceiveRequest(invocation, requestEx); result = error; } }; Holder<Throwable> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override public void sendFailResponse(Throwable throwable) { result.value = throwable; } @Override protected void doInvoke() { } }; initRestInvocation(); restInvocation.httpServerFilters = Arrays.asList(filter); restInvocation.invoke(); Assert.assertSame(error, result.value); }
public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void invokeNormal(@Mocked HttpServerFilter filter) { new Expectations() { { filter.enabled(); result = true; filter.afterReceiveRequest(invocation, requestEx); result = null; } }; restInvocation = new AbstractRestInvocationForTest() { @Override protected void doInvoke() { } @Override public void sendFailResponse(Throwable throwable) { Assert.fail("must not fail"); } }; initRestInvocation(); restInvocation.httpServerFilters = Arrays.asList(filter); restInvocation.invoke(); assertEquals(nanoTime, invocation.getInvocationStageTrace().getStartServerFiltersRequest()); }
public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void sendFailResponseNoProduceProcessor() { invocation.onStart(0); restInvocation.produceProcessor = null; restInvocation.sendFailResponse(new RuntimeExceptionWithoutStackTrace()); Assert.assertSame(ProduceProcessorManager.INSTANCE.findDefaultJsonProcessor(), restInvocation.produceProcessor); }
public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } AbstractRestInvocation(); }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void sendFailResponseHaveProduceProcessor() { Holder<Response> result = new Holder<>(); restInvocation = new AbstractRestInvocationForTest() { @Override protected void doInvoke() { } @Override protected void sendResponseQuietly(Response response) { result.value = response; } }; initRestInvocation(); restInvocation.produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(); Throwable e = new InvocationException(Status.BAD_GATEWAY, ""); restInvocation.sendFailResponse(e); Assert.assertSame(e, result.value.getResult()); Assert.assertSame( ProduceProcessorManager.INSTANCE.findDefaultPlainProcessor(), restInvocation.produceProcessor); }
public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } AbstractRestInvocation(); }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.INSTANCE.findDefaultProcessor(); } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void sendResponseQuietlyException(@Mocked Response response) { restInvocation = new AbstractRestInvocationForTest() { @Override protected void doInvoke() { } @Override protected void sendResponse(Response response) { throw new RuntimeExceptionWithoutStackTrace(); } }; initRestInvocation(); restInvocation.sendResponseQuietly(response); }
protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } AbstractRestInvocation(); }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void sendResponseQuietlyExceptionOnNullInvocation(@Mocked Response response) { restInvocation = new AbstractRestInvocationForTest() { @Override protected void doInvoke() { } @Override protected void sendResponse(Response response) { throw new RuntimeExceptionWithoutStackTrace(""); } }; initRestInvocation(); restInvocation.invocation = null; restInvocation.sendResponseQuietly(response); }
protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } AbstractRestInvocation(); }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); }
AbstractRestInvocation { protected void sendResponseQuietly(Response response) { if (invocation != null) { invocation.getInvocationStageTrace().finishHandlersResponse(); } try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}, request uri:{}", getMicroserviceQualifiedName(), requestEx.getRequestURI(), e); } } AbstractRestInvocation(); void setHttpServerFilters(List<HttpServerFilter> httpServerFilters); String getContext(String key); void invoke(); void sendFailResponse(Throwable throwable); static final String UNKNOWN_OPERATION_ID; }
@Test public void testGetAvailableAddress(@Injectable ServiceRegistryConfig config, @Injectable InstanceCacheManager cacheManager, @Injectable InstanceCache cache) { ArrayList<IpPort> ipPortList = new ArrayList<>(); ipPortList.add(new IpPort("127.0.0.1", 9980)); ipPortList.add(new IpPort("127.0.0.1", 9981)); new Expectations() { { config.getIpPort(); result = ipPortList; config.getTransport(); result = "rest"; config.isRegistryAutoDiscovery(); result = true; } }; IpPortManager manager = new IpPortManager(config); manager.instanceCacheManager = cacheManager; IpPort address1 = manager.getAvailableAddress(); if (address1.getPort() == 9980) { Assert.assertEquals("127.0.0.1", address1.getHostOrIp()); Assert.assertEquals(9980, address1.getPort()); } else { Assert.assertEquals("127.0.0.1", address1.getHostOrIp()); Assert.assertEquals(9981, address1.getPort()); } IpPort address2 = manager.getNextAvailableAddress(address1); if (address1.getPort() == 9980) { Assert.assertEquals("127.0.0.1", address2.getHostOrIp()); Assert.assertEquals(9981, address2.getPort()); } else { Assert.assertEquals("127.0.0.1", address2.getHostOrIp()); Assert.assertEquals(9980, address2.getPort()); } IpPort address3 = manager.getAvailableAddress(); if (address1.getPort() == 9980) { Assert.assertEquals("127.0.0.1", address3.getHostOrIp()); Assert.assertEquals(9981, address3.getPort()); } else { Assert.assertEquals("127.0.0.1", address3.getHostOrIp()); Assert.assertEquals(9980, address3.getPort()); } Map<String, List<CacheEndpoint>> addresses = new HashMap<>(); List<CacheEndpoint> instances = new ArrayList<>(); instances.add(new CacheEndpoint("http: addresses.put("rest", instances); new Expectations() { { cacheManager.getOrCreate("default", "SERVICECENTER", "latest"); result = cache; cache.getOrCreateTransportMap(); result = addresses; } }; manager.initAutoDiscovery(); IpPort address4 = manager.getNextAvailableAddress(address3); if (address1.getPort() == 9980) { Assert.assertEquals("127.0.0.1", address4.getHostOrIp()); Assert.assertEquals(9980, address4.getPort()); } else { address4 = manager.getNextAvailableAddress(address1); Assert.assertEquals("127.0.0.1", address4.getHostOrIp()); Assert.assertEquals(9980, address4.getPort()); } IpPort address5 = manager.getNextAvailableAddress(address4); Assert.assertEquals("127.0.0.1", address5.getHostOrIp()); Assert.assertEquals(9981, address5.getPort()); manager.setAutoDiscoveryInited(true); IpPort address6 = manager.getNextAvailableAddress(address3); if (address1.getPort() == 9980) { Assert.assertEquals("127.0.0.1", address6.getHostOrIp()); Assert.assertEquals(9982, address6.getPort()); } else { address6 = manager.getNextAvailableAddress(address1); Assert.assertEquals("127.0.0.1", address6.getHostOrIp()); Assert.assertEquals(9982, address6.getPort()); } }
public IpPort getAvailableAddress() { return getAvailableAddress(currentAvailableIndex.get()); }
IpPortManager { public IpPort getAvailableAddress() { return getAvailableAddress(currentAvailableIndex.get()); } }
IpPortManager { public IpPort getAvailableAddress() { return getAvailableAddress(currentAvailableIndex.get()); } IpPortManager(ServiceRegistryConfig serviceRegistryConfig); }
IpPortManager { public IpPort getAvailableAddress() { return getAvailableAddress(currentAvailableIndex.get()); } IpPortManager(ServiceRegistryConfig serviceRegistryConfig); void setAutoDiscoveryInited(boolean autoDiscoveryInited); int getMaxRetryTimes(); void initAutoDiscovery(); IpPort getNextAvailableAddress(IpPort failedIpPort); IpPort getAvailableAddress(); }
IpPortManager { public IpPort getAvailableAddress() { return getAvailableAddress(currentAvailableIndex.get()); } IpPortManager(ServiceRegistryConfig serviceRegistryConfig); void setAutoDiscoveryInited(boolean autoDiscoveryInited); int getMaxRetryTimes(); void initAutoDiscovery(); IpPort getNextAvailableAddress(IpPort failedIpPort); IpPort getAvailableAddress(); }
@Test public void onBeforeProducerProvider_metrics_endpoint_disabled() { ArchaiusUtils.setProperty("servicecomb.metrics.endpoint.enabled", false); final MetricsBootListener listener = new MetricsBootListener(); final List<ProducerMeta> producerMetas = new ArrayList<>(); final BootEvent event = new BootEvent(); final SCBEngine scbEngine = new SCBEngine() { final public ProducerProviderManager producerProviderManager = new ProducerProviderManager(this) { @Override public void addProducerMeta(String schemaId, Object instance) { producerMetas.add(new ProducerMeta(schemaId, instance)); } }; @Override public ProducerProviderManager getProducerProviderManager() { return producerProviderManager; } }; event.setScbEngine(scbEngine); listener.onBeforeProducerProvider(event); Assert.assertThat(producerMetas, Matchers.empty()); }
@Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); }
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } }
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } }
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } MetricsBootstrap getMetricsBootstrap(); SlowInvocationLogger getSlowInvocationLogger(); @Override void onBeforeProducerProvider(BootEvent event); @Override void onAfterRegistry(BootEvent event); @Override void onBeforeClose(BootEvent event); }
MetricsBootListener implements BootListener { @Override public void onBeforeProducerProvider(BootEvent event) { if (!DynamicPropertyFactory.getInstance().getBooleanProperty("servicecomb.metrics.endpoint.enabled", true).get()) { return; } MetricsRestPublisher metricsRestPublisher = SPIServiceUtils.getTargetService(MetricsInitializer.class, MetricsRestPublisher.class); event.getScbEngine().getProducerProviderManager() .addProducerMeta("metricsEndpoint", metricsRestPublisher); } MetricsBootstrap getMetricsBootstrap(); SlowInvocationLogger getSlowInvocationLogger(); @Override void onBeforeProducerProvider(BootEvent event); @Override void onAfterRegistry(BootEvent event); @Override void onBeforeClose(BootEvent event); }
@Test public void testModuleName() { Assert.assertEquals("security", securityModule.getModuleName()); }
@Override public String getModuleName() { return "security"; }
SecurityModule implements Module { @Override public String getModuleName() { return "security"; } }
SecurityModule implements Module { @Override public String getModuleName() { return "security"; } protected SecurityModule(); protected SecurityModule(SecurityConfig config); }
SecurityModule implements Module { @Override public String getModuleName() { return "security"; } protected SecurityModule(); protected SecurityModule(SecurityConfig config); DataRoomMatcher getDataRoomMatcher(); static SecurityModule newServerModule(SecurityConfig config); static SecurityModule newClientModule(); void setEnabled(final boolean enabled); boolean isEnabled(); void setEnabled(Supplier<Boolean> enabled); @Override String getModuleName(); void reconfigure(SecurityConfig config); SecurityConfig getConfig(); @Override void setupModule(ModuleContext context); boolean isAllowed(QueryContext queryContext, Class<?> resourceClass, ResourcePermission permission); boolean isAllowed(QueryContext queryContext, String resourceType, ResourcePermission permission); ResourcePermission getCallerPermissions(QueryContext queryContext, String resourceType); ResourcePermission getRolePermissions(QueryContext queryContext, String resourceType, String checkedRole); ResourcePermission getResourcePermission(QueryContext queryContext, Class<?> resourceClass); ResourcePermission getResourcePermission(QueryContext queryContext, String resourceType); boolean isUserInRole(QueryContext queryContext, String role); SecurityProvider getCallerSecurityProvider(); }
SecurityModule implements Module { @Override public String getModuleName() { return "security"; } protected SecurityModule(); protected SecurityModule(SecurityConfig config); DataRoomMatcher getDataRoomMatcher(); static SecurityModule newServerModule(SecurityConfig config); static SecurityModule newClientModule(); void setEnabled(final boolean enabled); boolean isEnabled(); void setEnabled(Supplier<Boolean> enabled); @Override String getModuleName(); void reconfigure(SecurityConfig config); SecurityConfig getConfig(); @Override void setupModule(ModuleContext context); boolean isAllowed(QueryContext queryContext, Class<?> resourceClass, ResourcePermission permission); boolean isAllowed(QueryContext queryContext, String resourceType, ResourcePermission permission); ResourcePermission getCallerPermissions(QueryContext queryContext, String resourceType); ResourcePermission getRolePermissions(QueryContext queryContext, String resourceType, String checkedRole); ResourcePermission getResourcePermission(QueryContext queryContext, Class<?> resourceClass); ResourcePermission getResourcePermission(QueryContext queryContext, String resourceType); boolean isUserInRole(QueryContext queryContext, String role); SecurityProvider getCallerSecurityProvider(); }
@Test public void testFindOne() { QuerySpec querySpec = new QuerySpec(TestEntity.class); TestEntity entity = repo.findOne(1L, querySpec); Assert.assertEquals("test1", entity.getStringValue()); }
@Override public T findOne(I id, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, id)); List<T> results = findAll(idQuerySpec); return getUnique(results, id); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public T findOne(I id, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, id)); List<T> results = findAll(idQuerySpec); return getUnique(results, id); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public T findOne(I id, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, id)); List<T> results = findAll(idQuerySpec); return getUnique(results, id); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public T findOne(I id, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, id)); List<T> results = findAll(idQuerySpec); return getUnique(results, id); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public T findOne(I id, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, id)); List<T> results = findAll(idQuerySpec); return getUnique(results, id); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFindAllById() { QuerySpec querySpec = new QuerySpec(TestEntity.class); ResourceList<TestEntity> entities = repo.findAll(Arrays.asList(1L, 2L), querySpec); Assert.assertEquals(2, entities.size()); Assert.assertEquals("test1", entities.get(0).getStringValue()); Assert.assertEquals("test2", entities.get(1).getStringValue()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test(expected = IllegalArgumentException.class) public void testInvalidLimit() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.setLimit(Long.MAX_VALUE); repo.findAll(querySpec); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test(expected = IllegalArgumentException.class) public void testInvalidOffset() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.setOffset(Long.MAX_VALUE); repo.findAll(querySpec); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterString() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("stringValue"), FilterOperator.EQ, "test1")); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(1, list.size()); TestEntity entity = list.get(0); Assert.assertEquals("test1", entity.getStringValue()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterLong() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("longValue"), FilterOperator.EQ, 2L)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(1, list.size()); TestEntity entity = list.get(0); Assert.assertEquals(2, entity.getId().longValue()); Assert.assertEquals(2L, entity.getLongValue()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterInt() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("embValue", "embIntValue"), FilterOperator.EQ, 2)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(1, list.size()); TestEntity entity = list.get(0); Assert.assertEquals(2L, entity.getId().longValue()); Assert.assertEquals(2, entity.getEmbValue().getEmbIntValue().intValue()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterBooleanTrue() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter( new FilterSpec(Arrays.asList("embValue", "nestedValue", "embBoolValue"), FilterOperator.EQ, true)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(1, list.size()); TestEntity entity = list.get(0); Assert.assertTrue(entity.getEmbValue().getNestedValue().getEmbBoolValue()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testOptimization() { QuerySpec querySpec = new QuerySpec(RelationIdEntity.class); querySpec.addFilter(PathSpec.of("oneRelatedValue", "id").filter(FilterOperator.EQ, 1L)); QuerySpec optimized = repo.optimizeQuerySpec(querySpec); Assert.assertEquals(1, optimized.getFilters().size()); FilterSpec filterSpec = optimized.getFilters().get(0); Assert.assertEquals(PathSpec.of("oneRelatedValueId"), filterSpec.getPath()); }
protected QuerySpec optimizeQuerySpec(QuerySpec filteredQuerySpec) { QuerySpec clone = filteredQuerySpec.clone(); String resourceType = filteredQuerySpec.getResourceType(); RegistryEntry entry = resourceType != null ? resourceRegistry.getEntry(resourceType) : resourceRegistry.getEntry(filteredQuerySpec.getResourceClass()); ResourceInformation resourceInformation = entry.getResourceInformation(); List<FilterSpec> filters = clone.getFilters(); for (FilterSpec filter : filters) { PathSpec path = filter.getPath(); if (path == null || path.getElements().size() < 2) { continue; } List<String> elements = path.getElements(); String attr1 = elements.get(elements.size() - 2); String attr2 = elements.get(elements.size() - 1); ResourceField firstField = resourceInformation.findFieldByUnderlyingName(attr1); if (firstField != null && firstField.getResourceFieldType() == ResourceFieldType.RELATIONSHIP && firstField.hasIdField() && isRequestingOppositeId(firstField, attr2)) { PathSpec optimizedPath = PathSpec.of(elements.subList(0, elements.size() - 2)).append(firstField.getIdName()); filter.setPath(optimizedPath); } } return clone; }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { protected QuerySpec optimizeQuerySpec(QuerySpec filteredQuerySpec) { QuerySpec clone = filteredQuerySpec.clone(); String resourceType = filteredQuerySpec.getResourceType(); RegistryEntry entry = resourceType != null ? resourceRegistry.getEntry(resourceType) : resourceRegistry.getEntry(filteredQuerySpec.getResourceClass()); ResourceInformation resourceInformation = entry.getResourceInformation(); List<FilterSpec> filters = clone.getFilters(); for (FilterSpec filter : filters) { PathSpec path = filter.getPath(); if (path == null || path.getElements().size() < 2) { continue; } List<String> elements = path.getElements(); String attr1 = elements.get(elements.size() - 2); String attr2 = elements.get(elements.size() - 1); ResourceField firstField = resourceInformation.findFieldByUnderlyingName(attr1); if (firstField != null && firstField.getResourceFieldType() == ResourceFieldType.RELATIONSHIP && firstField.hasIdField() && isRequestingOppositeId(firstField, attr2)) { PathSpec optimizedPath = PathSpec.of(elements.subList(0, elements.size() - 2)).append(firstField.getIdName()); filter.setPath(optimizedPath); } } return clone; } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { protected QuerySpec optimizeQuerySpec(QuerySpec filteredQuerySpec) { QuerySpec clone = filteredQuerySpec.clone(); String resourceType = filteredQuerySpec.getResourceType(); RegistryEntry entry = resourceType != null ? resourceRegistry.getEntry(resourceType) : resourceRegistry.getEntry(filteredQuerySpec.getResourceClass()); ResourceInformation resourceInformation = entry.getResourceInformation(); List<FilterSpec> filters = clone.getFilters(); for (FilterSpec filter : filters) { PathSpec path = filter.getPath(); if (path == null || path.getElements().size() < 2) { continue; } List<String> elements = path.getElements(); String attr1 = elements.get(elements.size() - 2); String attr2 = elements.get(elements.size() - 1); ResourceField firstField = resourceInformation.findFieldByUnderlyingName(attr1); if (firstField != null && firstField.getResourceFieldType() == ResourceFieldType.RELATIONSHIP && firstField.hasIdField() && isRequestingOppositeId(firstField, attr2)) { PathSpec optimizedPath = PathSpec.of(elements.subList(0, elements.size() - 2)).append(firstField.getIdName()); filter.setPath(optimizedPath); } } return clone; } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { protected QuerySpec optimizeQuerySpec(QuerySpec filteredQuerySpec) { QuerySpec clone = filteredQuerySpec.clone(); String resourceType = filteredQuerySpec.getResourceType(); RegistryEntry entry = resourceType != null ? resourceRegistry.getEntry(resourceType) : resourceRegistry.getEntry(filteredQuerySpec.getResourceClass()); ResourceInformation resourceInformation = entry.getResourceInformation(); List<FilterSpec> filters = clone.getFilters(); for (FilterSpec filter : filters) { PathSpec path = filter.getPath(); if (path == null || path.getElements().size() < 2) { continue; } List<String> elements = path.getElements(); String attr1 = elements.get(elements.size() - 2); String attr2 = elements.get(elements.size() - 1); ResourceField firstField = resourceInformation.findFieldByUnderlyingName(attr1); if (firstField != null && firstField.getResourceFieldType() == ResourceFieldType.RELATIONSHIP && firstField.hasIdField() && isRequestingOppositeId(firstField, attr2)) { PathSpec optimizedPath = PathSpec.of(elements.subList(0, elements.size() - 2)).append(firstField.getIdName()); filter.setPath(optimizedPath); } } return clone; } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { protected QuerySpec optimizeQuerySpec(QuerySpec filteredQuerySpec) { QuerySpec clone = filteredQuerySpec.clone(); String resourceType = filteredQuerySpec.getResourceType(); RegistryEntry entry = resourceType != null ? resourceRegistry.getEntry(resourceType) : resourceRegistry.getEntry(filteredQuerySpec.getResourceClass()); ResourceInformation resourceInformation = entry.getResourceInformation(); List<FilterSpec> filters = clone.getFilters(); for (FilterSpec filter : filters) { PathSpec path = filter.getPath(); if (path == null || path.getElements().size() < 2) { continue; } List<String> elements = path.getElements(); String attr1 = elements.get(elements.size() - 2); String attr2 = elements.get(elements.size() - 1); ResourceField firstField = resourceInformation.findFieldByUnderlyingName(attr1); if (firstField != null && firstField.getResourceFieldType() == ResourceFieldType.RELATIONSHIP && firstField.hasIdField() && isRequestingOppositeId(firstField, attr2)) { PathSpec optimizedPath = PathSpec.of(elements.subList(0, elements.size() - 2)).append(firstField.getIdName()); filter.setPath(optimizedPath); } } return clone; } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterBooleanFalse() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter( new FilterSpec(Arrays.asList("embValue", "nestedValue", "embBoolValue"), FilterOperator.EQ, false)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(numTestEntities - 1, list.size()); for (TestEntity entity : list) { Assert.assertFalse(entity.getEmbValue().getNestedValue().getEmbBoolValue()); } }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void fromMethod() { Assert.assertEquals(ResourcePermission.GET, ResourcePermission.fromMethod(HttpMethod.GET)); Assert.assertEquals(ResourcePermission.POST, ResourcePermission.fromMethod(HttpMethod.POST)); Assert.assertEquals(ResourcePermission.DELETE, ResourcePermission.fromMethod(HttpMethod.DELETE)); Assert.assertEquals(ResourcePermission.PATCH, ResourcePermission.fromMethod(HttpMethod.PATCH)); }
public static ResourcePermission fromMethod(HttpMethod method) { ResourcePermission permission = METHODS.get(method); PreconditionUtil.verify(permission != null, "unknown method %s, expected=%s", method, METHODS); return permission; }
ResourcePermission { public static ResourcePermission fromMethod(HttpMethod method) { ResourcePermission permission = METHODS.get(method); PreconditionUtil.verify(permission != null, "unknown method %s, expected=%s", method, METHODS); return permission; } }
ResourcePermission { public static ResourcePermission fromMethod(HttpMethod method) { ResourcePermission permission = METHODS.get(method); PreconditionUtil.verify(permission != null, "unknown method %s, expected=%s", method, METHODS); return permission; } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); }
ResourcePermission { public static ResourcePermission fromMethod(HttpMethod method) { ResourcePermission permission = METHODS.get(method); PreconditionUtil.verify(permission != null, "unknown method %s, expected=%s", method, METHODS); return permission; } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
ResourcePermission { public static ResourcePermission fromMethod(HttpMethod method) { ResourcePermission permission = METHODS.get(method); PreconditionUtil.verify(permission != null, "unknown method %s, expected=%s", method, METHODS); return permission; } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }
@Test public void testFilterEquals() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("longValue"), FilterOperator.EQ, 2L)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(1, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterNotEquals() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("longValue"), FilterOperator.NEQ, 2L)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(4, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterLess() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("longValue"), FilterOperator.LT, 2)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(2, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterLessEqual() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("longValue"), FilterOperator.LE, 2)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(3, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterGreater() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("longValue"), FilterOperator.GT, 1)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(3, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterGreaterEqual() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("longValue"), FilterOperator.GE, 1)); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(4, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterLike() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("stringValue"), FilterOperator.LIKE, "test2")); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(1, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testFilterLikeWildcards() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.addFilter(new FilterSpec(Arrays.asList("stringValue"), FilterOperator.LIKE, "test%")); List<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(5, list.size()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testPaging() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.setOffset(2L); querySpec.setLimit(2L); ResourceList<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(2, list.size()); Assert.assertEquals(2, list.get(0).getId().intValue()); Assert.assertEquals(3, list.get(1).getId().intValue()); PagedMetaInformation metaInformation = list.getMeta(PagedMetaInformation.class); Assert.assertEquals(5, metaInformation.getTotalResourceCount().longValue()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void testPagingFirst() { QuerySpec querySpec = new QuerySpec(TestEntity.class); querySpec.setOffset(0L); querySpec.setLimit(3L); ResourceList<TestEntity> list = repo.findAll(querySpec); Assert.assertEquals(3, list.size()); Assert.assertEquals(0, list.get(0).getId().intValue()); Assert.assertEquals(1, list.get(1).getId().intValue()); Assert.assertEquals(2, list.get(2).getId().intValue()); PagedMetaInformation metaInformation = list.getMeta(PagedMetaInformation.class); Assert.assertEquals(5, metaInformation.getTotalResourceCount().longValue()); }
@Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
JpaEntityRepositoryBase extends JpaRepositoryBase<T> implements ResourceRepository<T, I>, ResourceRegistryAware { @Override public ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec) { String idField = getIdField().getUnderlyingName(); QuerySpec idQuerySpec = querySpec.clone(); idQuerySpec.addFilter(new FilterSpec(Arrays.asList(idField), FilterOperator.EQ, ids)); return findAll(idQuerySpec); } JpaEntityRepositoryBase(Class<T> entityClass); JpaEntityRepositoryBase(JpaRepositoryConfig<T> config); JpaQueryFactory getQueryFactory(); @Override T findOne(I id, QuerySpec querySpec); @Override ResourceList<T> findAll(Collection<I> ids, QuerySpec querySpec); @Override ResourceList<T> findAll(QuerySpec querySpec); @Override S create(S resource); @Override S save(S resource); @Override void delete(I id); @Override Class<T> getResourceClass(); Class<?> getEntityClass(); @Override void setResourceRegistry(ResourceRegistry resourceRegistry); ResourceField getIdField(); }
@Test public void string() { Assert.assertEquals("ResourcePermission[post=false, get=true, patch=false, delete=false]", ResourcePermission.GET.toString()); }
@Override public String toString() { return "ResourcePermission[post=" + postAllowed + ", get=" + getAllowed + ", patch=" + patchAllowed + ", delete=" + deleteAllowed + "]"; }
ResourcePermission { @Override public String toString() { return "ResourcePermission[post=" + postAllowed + ", get=" + getAllowed + ", patch=" + patchAllowed + ", delete=" + deleteAllowed + "]"; } }
ResourcePermission { @Override public String toString() { return "ResourcePermission[post=" + postAllowed + ", get=" + getAllowed + ", patch=" + patchAllowed + ", delete=" + deleteAllowed + "]"; } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); }
ResourcePermission { @Override public String toString() { return "ResourcePermission[post=" + postAllowed + ", get=" + getAllowed + ", patch=" + patchAllowed + ", delete=" + deleteAllowed + "]"; } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
ResourcePermission { @Override public String toString() { return "ResourcePermission[post=" + postAllowed + ", get=" + getAllowed + ", patch=" + patchAllowed + ", delete=" + deleteAllowed + "]"; } protected ResourcePermission(); private ResourcePermission(boolean post, boolean get, boolean patch, boolean delete); static final ResourcePermission create(boolean push, boolean get, boolean patch, boolean delete); static ResourcePermission fromMethod(HttpMethod method); boolean isPostAllowed(); boolean isGetAllowed(); boolean isPatchAllowed(); boolean isDeleteAllowed(); @JsonIgnore boolean isEmpty(); ResourcePermission or(ResourcePermission other); ResourcePermission and(ResourcePermission other); ResourcePermission xor(ResourcePermission other); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static final ResourcePermission EMPTY; static final ResourcePermission ALL; static final ResourcePermission GET; static final ResourcePermission POST; static final ResourcePermission PATCH; static final ResourcePermission DELETE; }