src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
SecretsGroupInfo { public SecretsGroupInfo(SecretsGroupSRN srn, Optional<String> encryptorArn, Optional<String> storageArn, Optional<String> adminPolicyArn, Optional<String> readOnlyPolicyArn, List<Principal> admin, List<Principal> readOnly) { this.srn = srn; this.encryptorArn = encryptorArn; this.storageArn = storageArn; this.adminPolicyArn = adminPolicyArn; this.readOnlyPolicyArn = readOnlyPolicyArn; this.admin = admin; this.readOnly = readOnly; } SecretsGroupInfo(SecretsGroupSRN srn, Optional<String> encryptorArn, Optional<String> storageArn, Optional<String> adminPolicyArn, Optional<String> readOnlyPolicyArn, List<Principal> admin, List<Principal> readOnly); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); public SecretsGroupSRN srn; public Optional<String> encryptorArn; public Optional<String> storageArn; public Optional<String> adminPolicyArn; public Optional<String> readOnlyPolicyArn; public List<Principal> admin; public List<Principal> readOnly; } | @Test public void testSecretsGroupInfo() { List<Principal> readonlyPrincipals = getReadOnlyPrincipals(); List<Principal> adminPrincipals = getAdminPrincipals(); SecretsGroupInfo info = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, storageArn, adminArn, readonlyArn, adminPrincipals, readonlyPrincipals); assertEquals(info.srn.account, account); assertEquals(info.srn.groupIdentifier.name, groupName); assertEquals(info.srn.groupIdentifier.region, groupRegion); assertEquals(info.encryptorArn, encryptorArn); assertEquals(info.storageArn, storageArn); assertEquals(info.adminPolicyArn, adminArn); assertEquals(info.readOnlyPolicyArn, readonlyArn); assertEquals(info.admin, adminPrincipals); assertEquals(info.readOnly, readonlyPrincipals); assertEquals( info.toString(), "SecretsGroupInfo{srn=srn:aws:strongbox:us-west-1:1234:group/project/group1, " + "storageArn=Optional[arn:aws:dynamodb:eu-west-1:1234:table/strongbox_eu-west-1_project-group1], " + "encryptorArn=Optional[arn:aws:kms:eu-west-1:1234:key/d413a4de-5eb5-4eb4-b4af-373bcba5efdf], " + "adminPolicyArn=Optional[arn:aws:iam::1234:policy/strongbox/strongbox_eu-west-1_project-group1_admin], " + "readOnlyPolicyArn=Optional[arn:aws:iam::1234:policy/strongbox/strongbox_eu-west-1_project-group1_readonly], " + "admin=[alice [user], awesometeam [group]], readOnly=[bob [user], awesomeservice [role]]}" ); } |
SecretsGroupInfo { @Override public boolean equals(final Object obj) { if(obj instanceof SecretsGroupInfo){ final SecretsGroupInfo other = (SecretsGroupInfo) obj; return Objects.equal(srn, other.srn) && Objects.equal(encryptorArn, other.encryptorArn) && Objects.equal(storageArn, other.storageArn) && Objects.equal(adminPolicyArn, other.adminPolicyArn) && Objects.equal(readOnlyPolicyArn, other.readOnlyPolicyArn) && Objects.equal(admin, other.admin) && Objects.equal(readOnly, other.readOnly); } else{ return false; } } SecretsGroupInfo(SecretsGroupSRN srn, Optional<String> encryptorArn, Optional<String> storageArn, Optional<String> adminPolicyArn, Optional<String> readOnlyPolicyArn, List<Principal> admin, List<Principal> readOnly); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); public SecretsGroupSRN srn; public Optional<String> encryptorArn; public Optional<String> storageArn; public Optional<String> adminPolicyArn; public Optional<String> readOnlyPolicyArn; public List<Principal> admin; public List<Principal> readOnly; } | @Test public void testEquals() { SecretsGroupInfo info = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, storageArn, adminArn, readonlyArn, new ArrayList<>(), new ArrayList<>()); SecretsGroupInfo infoCopy = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, storageArn, adminArn, readonlyArn, new ArrayList<>(), new ArrayList<>()); assertTrue(info.equals(infoCopy)); SecretsGroupInfo differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(Region.EU_WEST_1, groupName)), encryptorArn, storageArn, adminArn, readonlyArn, new ArrayList<>(), new ArrayList<>()); assertFalse(info.equals(differentInfo)); differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, "other.name")), encryptorArn, storageArn, adminArn, readonlyArn, new ArrayList<>(), new ArrayList<>()); assertFalse(info.equals(differentInfo)); differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), Optional.of("other encryptor ARN"), storageArn, adminArn, readonlyArn, new ArrayList<>(), new ArrayList<>()); assertFalse(info.equals(differentInfo)); differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, Optional.of("other storage ARN"), adminArn, readonlyArn, new ArrayList<>(), new ArrayList<>()); assertFalse(info.equals(differentInfo)); differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, storageArn, Optional.of("other admin ARN"), readonlyArn, new ArrayList<>(), new ArrayList<>()); assertFalse(info.equals(differentInfo)); differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, storageArn, adminArn, Optional.of("other readonly ARN"), new ArrayList<>(), new ArrayList<>()); assertFalse(info.equals(differentInfo)); differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, storageArn, adminArn, readonlyArn, getAdminPrincipals(), new ArrayList<>()); assertFalse(info.equals(differentInfo)); differentInfo = new SecretsGroupInfo( new SecretsGroupSRN(account, new SecretsGroupIdentifier(groupRegion, groupName)), encryptorArn, storageArn, adminArn, readonlyArn, new ArrayList<>(), getReadOnlyPrincipals()); assertFalse(info.equals(differentInfo)); assertFalse(info.equals("some string value")); } |
RoleARN extends ARN { public String getRoleName() { return this.resource; } RoleARN(final String arn); String getRoleName(); } | @Test public void role() { RoleARN arn = new RoleARN("arn:aws:iam::12345:role/role-name"); assertThat(arn.getRoleName(), is("role-name")); } |
SecretValue implements BestEffortShred { @Override public boolean equals(final Object obj) { if (obj instanceof SecretValue) { final SecretValue other = (SecretValue) obj; return Arrays.equals(secretValue, other.asByteArray()) && Objects.equal(type, other.type) && Objects.equal(encoding, other.encoding); } else { return false; } } SecretValue(byte[] secretValue, Encoding encoding, SecretType type); SecretValue(byte[] secretValue, SecretType type); SecretValue(String secretValue, SecretType type); byte[] asByteArray(); String asString(); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override void bestEffortShred(); final SecretType type; final Encoding encoding; } | @Test public void testEquals() { byte[] value1 = {1, 2, 3, 4}; byte[] value2 = {1, 2, 3, 4}; byte[] value3 = {1, 2, 3, 5}; SecretValue secretValue1 = new SecretValue(value1, SecretType.OPAQUE); SecretValue secretValue2 = new SecretValue(value2, SecretType.OPAQUE); SecretValue secretValue3 = new SecretValue(value3, SecretType.OPAQUE); assertTrue(secretValue1.equals(secretValue2)); assertFalse(secretValue1.equals(secretValue3)); } |
Principal { public static Principal fromArn(String arn, String account) { String[] parts = arn.split(":"); if (parts.length != 6 || !parts[0].equals("arn") || !parts[1].equals("aws") || !parts[2].equals("iam")) { throw new InvalidResourceName(arn, "A principal ARN should start with 'arn:aws:iam' and have 6 parts"); } if (!account.equals(parts[4])) { throw new IllegalArgumentException("The account in the ARN does not match account of the Principal trying to " + "perform the action."); } String last = parts[5]; String[] elements = last.split("/"); if (elements.length != 2) { throw new InvalidResourceName( arn, "Resource name part of principal ARN should contain exactly one '/'. Only principal ARNs for" + "groups, users or roles can be used."); } String type = elements[0]; String name = elements[1]; return new Principal(PrincipalType.fromString(type), name); } Principal(PrincipalType type, String principalName); static Principal fromArn(String arn, String account); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final PrincipalType type; final String name; } | @Test public void testFromArn() { Principal principal; principal = Principal.fromArn("arn:aws:iam::12345:user/bob", "12345"); assertEquals(principal.type, PrincipalType.USER); assertEquals(principal.name, "bob" ); principal = Principal.fromArn("arn:aws:iam::12345:group/team-awesome", "12345"); assertEquals(principal.type, PrincipalType.GROUP); assertEquals(principal.name, "team-awesome"); principal = Principal.fromArn("arn:aws:iam::12345:role/myrole", "12345"); assertEquals(principal.type, PrincipalType.ROLE); assertEquals(principal.name, "myrole"); }
@Test(expectedExceptions = InvalidResourceName.class) public void testFromArnInvalidPrefix() { Principal principal = Principal.fromArn("arn:aws:invalid::12345:user/username", "12345"); }
@Test(expectedExceptions = InvalidResourceName.class) public void testFromArnInvalidNumberParts() { Principal principal = Principal.fromArn("arn:aws:iam::user/username", "12345"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testFromArnInvalidType() { Principal principal = Principal.fromArn("arn:aws:iam::12345:invalid-type/username", "12345"); }
@Test(expectedExceptions = InvalidResourceName.class) public void testFromArnInvalidResource() { Principal principal = Principal.fromArn("arn:aws:iam::12345:user/username/group", "12345"); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAnotherAccount() { Principal principal = Principal.fromArn("arn:aws:iam::123456:user/bob", "12345"); } |
Principal { @Override public String toString() { return String.format("%s [%s]", name, type.toString()); } Principal(PrincipalType type, String principalName); static Principal fromArn(String arn, String account); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final PrincipalType type; final String name; } | @Test public void testToString() { Principal principal = Principal.fromArn("arn:aws:iam::12345:user/bob", "12345"); assertEquals(principal.toString(), "bob [user]"); } |
Principal { @Override public boolean equals(final Object obj) { if(obj instanceof Principal){ final Principal other = (Principal) obj; return Objects.equal(name, other.name) && Objects.equal(type, other.type); } else{ return false; } } Principal(PrincipalType type, String principalName); static Principal fromArn(String arn, String account); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final PrincipalType type; final String name; } | @Test public void testEquals() { Principal principal1 = Principal.fromArn("arn:aws:iam::12345:user/bob", "12345"); Principal principal2 = new Principal(PrincipalType.USER, "bob"); assertTrue(principal1.equals(principal2)); } |
SecretEntry implements BestEffortShred { public SecretEntry(EncryptionPayload encryptionPayload, RawSecretEntry rawSecretEntry) { this.secretIdentifier = rawSecretEntry.secretIdentifier; this.version = rawSecretEntry.version; this.state = rawSecretEntry.state; this.notBefore = rawSecretEntry.notBefore; this.notAfter = rawSecretEntry.notAfter; this.secretValue = encryptionPayload.value; this.userData = encryptionPayload.userData; this.created = encryptionPayload.created; this.modified = encryptionPayload.modified; this.createdBy = encryptionPayload.createdBy; this.modifiedBy = encryptionPayload.modifiedBy; this.comment = encryptionPayload.comment; } SecretEntry(EncryptionPayload encryptionPayload, RawSecretEntry rawSecretEntry); protected SecretEntry(SecretIdentifier secretIdentifier,
long version, SecretValue secretValue,
ZonedDateTime created,
ZonedDateTime modified,
Optional<UserAlias> createdBy,
Optional<UserAlias> modifiedBy,
State state,
Optional<ZonedDateTime> notBefore,
Optional<ZonedDateTime> notAfter,
Optional<Comment> comment,
Optional<UserData> userData); @Override String toString(); @Override void bestEffortShred(); final SecretIdentifier secretIdentifier; final long version; final SecretValue secretValue; final ZonedDateTime created; final ZonedDateTime modified; final Optional<UserAlias> createdBy; final Optional<UserAlias> modifiedBy; final State state; final Optional<ZonedDateTime> notBefore; final Optional<ZonedDateTime> notAfter; final Optional<Comment> comment; final Optional<UserData> userData; } | @Test public void testSecretEntry() { EncryptionPayload payload = createPayload(true); RawSecretEntry rawEntry = createRawEntry(); SecretEntry secretEntry = new SecretEntry(payload, rawEntry); assertEquals(secretEntry.secretIdentifier.name, rawEntry.secretIdentifier.name); assertEquals(secretEntry.version, rawEntry.version.longValue()); assertEquals(secretEntry.secretValue, payload.value); assertEquals(secretEntry.created, payload.created); assertEquals(secretEntry.comment, payload.comment); assertEquals(secretEntry.userData, payload.userData); assertEquals( secretEntry.toString(), "SecretEntry{secretIdentifier=key, version=1, secretValue=SecretValue{type=opaque, secretEncoding=utf8}, " + "created=2016-06-01T00:00Z[UTC], modified=2017-06-01T00:00Z[UTC], state=enabled, notBefore=Optional[2016-06-01T13:37:42Z[UTC]], " + "notAfter=Optional.empty, comment=Optional[Comment{}], userData=Optional[UserData{}]}"); } |
SecretsGroupIdentifier implements Comparable<SecretsGroupIdentifier> { @Override public String toString() { return String.format("%s [%s]", name, region.getName()); } SecretsGroupIdentifier(@JsonProperty("region") Region region,
@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(SecretsGroupIdentifier o); @JsonProperty("region")
final Region region; @JsonProperty("name")
final String name; } | @Test public void testConstructWithValidNames() { SecretsGroupIdentifier group = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); assertEquals(group.name, "project.service.group1"); assertEquals(group.region, Region.US_WEST_1); assertEquals(group.toString(), "project.service.group1 [us-west-1]"); } |
SecretsGroupIdentifier implements Comparable<SecretsGroupIdentifier> { @Override public boolean equals(final Object obj) { if(obj instanceof SecretsGroupIdentifier){ final SecretsGroupIdentifier other = (SecretsGroupIdentifier) obj; return Objects.equal(name, other.name) && Objects.equal(region, other.region); } else { return false; } } SecretsGroupIdentifier(@JsonProperty("region") Region region,
@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(SecretsGroupIdentifier o); @JsonProperty("region")
final Region region; @JsonProperty("name")
final String name; } | @Test public void testEquals() throws Exception { SecretsGroupIdentifier group1 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group2 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group3 = new SecretsGroupIdentifier(Region.EU_WEST_1, "project.service.group1"); SecretsGroupIdentifier group4 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group2"); assertTrue(group1.equals(group2)); assertFalse(group1.equals(group3)); assertFalse(group1.equals(group4)); assertFalse(group1.equals("some string value")); } |
SecretsGroupIdentifier implements Comparable<SecretsGroupIdentifier> { @Override public int compareTo(SecretsGroupIdentifier o) { if (region.compareTo(o.region) == 0) { return name.compareTo(o.name); } else { return region.compareTo(o.region); } } SecretsGroupIdentifier(@JsonProperty("region") Region region,
@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); @Override int compareTo(SecretsGroupIdentifier o); @JsonProperty("region")
final Region region; @JsonProperty("name")
final String name; } | @Test public void testCompareTo() throws Exception { SecretsGroupIdentifier group1 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group2 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group1"); SecretsGroupIdentifier group3 = new SecretsGroupIdentifier(Region.EU_WEST_1, "project.service.group1"); SecretsGroupIdentifier group4 = new SecretsGroupIdentifier(Region.US_WEST_1, "project.service.group2"); assertEquals(group1.compareTo(group1), 0); assertEquals(group1.compareTo(group2), 0); assertEquals(group1.compareTo(group3), -2); assertEquals(group1.compareTo(group4), -1); assertEquals(group3.compareTo(group4), 2); } |
SecretIdentifier { @Override public String toString() { return name; } @JsonCreator SecretIdentifier(@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final String name; } | @Test public void testConstructWithValidNames() { SecretIdentifier secret = new SecretIdentifier("fooBar1"); assertEquals(secret.name, "fooBar1"); assertEquals(secret.toString(), "fooBar1"); }
@Test public void testConstructWithValidUnderscoreNames() { SecretIdentifier secret = new SecretIdentifier("foo_bar_1"); assertEquals(secret.name, "foo_bar_1"); assertEquals(secret.toString(), "foo_bar_1"); } |
SecretIdentifier { @Override public boolean equals(final Object obj) { if(obj instanceof SecretIdentifier){ final SecretIdentifier other = (SecretIdentifier) obj; return Objects.equal(name, other.name); } else { return false; } } @JsonCreator SecretIdentifier(@JsonProperty("name") String name); @Override String toString(); @Override int hashCode(); @Override boolean equals(final Object obj); final String name; } | @Test public void testEquals() throws Exception { SecretIdentifier secret1 = new SecretIdentifier("fooBar1"); SecretIdentifier secret2 = new SecretIdentifier("fooBar1"); SecretIdentifier secret3 = new SecretIdentifier("fooBar2"); assertTrue(secret1.equals(secret2)); assertFalse(secret1.equals(secret3)); assertFalse(secret1.equals("some value")); } |
IAMPolicyManager { public void detachAdmin(SecretsGroupIdentifier group, Principal principal) { detachPrincipal(group, principal, AccessLevel.ADMIN); } IAMPolicyManager(AmazonIdentityManagement client, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static IAMPolicyManager fromCredentials(AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration); static String getAccount(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration); String getAccount(); boolean adminPolicyExists(SecretsGroupIdentifier group); boolean readOnlyPolicyExists(SecretsGroupIdentifier group); String getAdminPolicyArn(SecretsGroupIdentifier group); String getReadOnlyArn(SecretsGroupIdentifier group); void attachAdmin(SecretsGroupIdentifier group, Principal principal); void attachReadOnly(SecretsGroupIdentifier group, Principal principal); void detachAllPrincipals(SecretsGroupIdentifier group); void detachAdmin(SecretsGroupIdentifier group, Principal principal); void detachReadOnly(SecretsGroupIdentifier group, Principal principal); void attachPrincipalToPolicy(SecretsGroupIdentifier group, Principal principal, AccessLevel accessLevel); List<Principal> listAttachedAdmin(SecretsGroupIdentifier group); List<Principal> listAttachedReadOnly(SecretsGroupIdentifier group); Set<SecretsGroupIdentifier> getSecretsGroupIdentifiers(); String createAdminPolicy(final SecretsGroupIdentifier group, final KMSEncryptor kmsEncryptor, final Store store); String createReadOnlyPolicy(SecretsGroupIdentifier group, KMSEncryptor kmsEncryptor, Store store); void deleteAdminPolicy(SecretsGroupIdentifier group); void deleteReadonlyPolicy(SecretsGroupIdentifier group); static final String PATH_PREFIX; } | @Test public void testDetachAdminUser() throws Exception { Principal principal = new Principal(PrincipalType.USER, "alice"); partiallyMockedPolicyManager.detachAdmin(group, principal); DetachUserPolicyRequest request = new DetachUserPolicyRequest() .withPolicyArn(ADMIN_POLICY_ARN) .withUserName(principal.name); verify(mockClient, times(1)).detachUserPolicy(request); } |
LambdaHandler implements RequestStreamHandler { @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { I inputObject = deserializeEventJson(input, getInputType()); O handlerResult = handleRequest(inputObject, context); serializeOutput(output, handlerResult); } protected LambdaHandler(); @Override void handleRequest(InputStream input, OutputStream output, Context context); abstract O handleRequest(I input, Context context); } | @Test public void handleRequest() throws Exception { String jsonInputAndExpectedOutput = "{\"value\":\"testValue\"}"; InputStream exampleInputStream = new ByteArrayInputStream(jsonInputAndExpectedOutput.getBytes(StandardCharsets.UTF_8)); OutputStream exampleOutputStream = new OutputStream() { private final StringBuilder stringBuilder = new StringBuilder(); @Override public void write(int b) { stringBuilder.append((char) b); } @Override public String toString() { return stringBuilder.toString(); } }; TestLambdaHandler lambdaHandler = new TestLambdaHandler(); lambdaHandler.handleRequest(exampleInputStream, exampleOutputStream, null); assertEquals(jsonInputAndExpectedOutput, exampleOutputStream.toString()); } |
Handler extends LambdaHandler<AuthorizationInput, AuthorizationOutput> { @Override public AuthorizationOutput handleRequest(AuthorizationInput input, Context context) { final String authenticationToken = input.getAuthorizationToken(); final PolicyDocument policyDocument = new PolicyDocument(); PolicyStatement.Effect policyEffect = PolicyStatement.Effect.ALLOW; String principalId = null; try { User authenticatedUser = userService.getUserByToken(authenticationToken); principalId = String.valueOf(authenticatedUser.getId()); } catch (UserNotFoundException userNotFoundException) { policyEffect = PolicyStatement.Effect.DENY; LOGGER.info("User authentication failed for token " + authenticationToken); } policyDocument.withPolicyStatement(new PolicyStatement("execute-api:Invoke", policyEffect, input.getMethodArn())); return new AuthorizationOutput(principalId, policyDocument); } Handler(); @Inject void setUserService(UserService userService); @Override AuthorizationOutput handleRequest(AuthorizationInput input, Context context); } | @Test public void testFailingToken() throws Exception { Handler testHandler = new Handler(); AuthorizationInput mockEvent = createNiceMock(AuthorizationInput.class); expect(mockEvent.getAuthorizationToken()).andReturn("INVALID_TOKEN").anyTimes(); replay(mockEvent); AuthorizationOutput authorizationOutput = testHandler.handleRequest(mockEvent, null); assertEquals(PolicyStatement.Effect.DENY, authorizationOutput.getPolicyDocument().getPolicyStatements().get(0).getEffect()); } |
UserServiceImpl implements UserService { @Override public User registerNewUser(String username, String email) throws UserRegistrationException { checkEmailValidity(email); checkEmailUniqueness(email); checkUsernameUniqueness(username); User newUser = new User() .setId(UUID.randomUUID().toString()) .setUsername(username) .setEmail(email); userRepository.saveUser(newUser); return newUser; } @Inject UserServiceImpl(UserRepository userRepository); @Override User getUserByToken(String token); @Override User registerNewUser(String username, String email); } | @Test public void failedUserRegistrationWithExistingUsernameTest() throws Exception { thrown.expect(AnotherUserWithSameUsernameExistsException.class); UserService userService = getUserService(); final String username = UUID.randomUUID() + "test-username"; userService.registerNewUser(username, UUID.randomUUID() + "@test.com"); userService.registerNewUser(username, UUID.randomUUID() + "@test.com"); }
@Test public void failedUserRegistrationWithExistingEMailTest() throws Exception { thrown.expect(AnotherUserWithSameEmailExistsException.class); UserService userService = getUserService(); final String email = UUID.randomUUID() + "@test.com"; userService.registerNewUser(UUID.randomUUID().toString(), email); userService.registerNewUser(UUID.randomUUID().toString(), email); }
@Test public void failedUserRegistrationWithInvalidEmailTest() throws Exception { thrown.expect(InvalidMailAddressException.class); UserService userService = getUserService(); userService.registerNewUser(UUID.randomUUID().toString(), "INVALID_EMAIL"); } |
DataTypes { public static <T extends Number> T parseNum(String num, Class<T> cls, T def) { if (num == null) { return def; } T result = def; String toParse = num; Long multiplier = 1L; try { switch (num.charAt(num.length() - 1)) { case 'k' : case 'K' : multiplier = 1024L; toParse = num.substring(0, num.length() - 1); break; case 'm' : case 'M' : multiplier = 1024L * 1024L; toParse = num.substring(0, num.length() - 1); break; case 'g' : case 'G' : multiplier = 1024L * 1024L * 1024L; toParse = num.substring(0, num.length() - 1); break; } if(cls.equals(Integer.class)) { result = cls.cast(Integer.valueOf(toParse) * multiplier.intValue()); } else if(cls.equals(Long.class)) { result = cls.cast(Long.valueOf(toParse) * multiplier); } else if(cls.equals(Double.class)) { result = cls.cast(Double.valueOf(toParse) * multiplier.doubleValue()); } else if(cls.equals(Float.class)) { result = cls.cast(Float.valueOf(toParse) * multiplier.floatValue()); } else if(cls.equals(Byte.class)) { Integer res = Byte.valueOf(toParse) * multiplier.byteValue(); result = cls.cast(res.byteValue()); } else if(cls.equals(Short.class)) { Integer res = Short.valueOf(toParse) * multiplier.shortValue(); result = cls.cast(res.shortValue()); } } catch (Exception e) { log.log( Level.WARNING, "Error parsing value: {0} as {1}, using default: {2}", new Object[] {num,cls,def}); return def; } return result; } static T parseNum(String num, Class<T> cls, T def); static int parseSizeInt(String size, int def); static boolean parseBool(final String val); static Object decodeValueType(char typeId, String value); static String valueToString(final Object value); static char decodeTypeIdFromName(String name); static String stripNameFromTypeId(String name); static String encodeTypeIdInName(String name, Object value); static char getTypeId(Object instance); static boolean getProperty(String key, Boolean def); static void main( String[] args ); static final Map<String, Character> typesMap; } | @Test public void testParseNum() { assertEquals( new Long( 262144L ), Long.valueOf( Integer.class.cast( DataTypes.parseNum( "256k", Integer.class, 1 ) ) ) ); assertEquals( new Long( 262144L ), Long.class.cast( DataTypes.parseNum( "256k", Long.class, 1L ) ) ); assertEquals( new Double( 670720.0D ), Double.class.cast( DataTypes.parseNum( "655k", Double.class, 1D ) ) ); assertEquals( new Double( 262144F ), Double.valueOf( Float.class.cast( DataTypes.parseNum( "256k", Float.class, 1F ) ) ) ); assertEquals( new Long( 25 ), Long.valueOf( (long) DataTypes.parseNum( "25", Short.class, Short.valueOf( "1" ) ) ) ); assertEquals( new Long( 25 ), Long.valueOf( Byte.class.cast( DataTypes.parseNum( "25", Byte.class, Byte.valueOf( "1" ) ) ) ) ); } |
MobileV3 extends AnnotatedXMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc { @Override @SuppressWarnings("unchecked") public void filter(Packet _packet, XMPPResourceConnection sessionFromSM, NonAuthUserRepository repo, Queue<Packet> results) { if ((sessionFromSM == null) ||!sessionFromSM.isAuthorized() || (results == null) || (results.size() == 0)) { return; } StateHolder holder = threadState.get(); if (holder == null) { holder = new StateHolder(); threadState.set(holder); } for (Iterator<Packet> it = results.iterator(); it.hasNext(); ) { Packet res = it.next(); if ((res == null) || (res.getPacketTo() == null)) { if (log.isLoggable(Level.FINEST)) { log.finest("packet without destination"); } continue; } XMPPResourceConnection session = sessionFromSM.getParentSession() .getResourceForConnectionId(res.getPacketTo()); if (session == null) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "no session for destination {0} for packet {1}", new Object[] { res.getPacketTo().toString(), res.toString() }); } continue; } Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); if (!isQueueEnabled(session)) { if ((presenceQueue == null && packetQueue == null) || (presenceQueue.isEmpty() && packetQueue.isEmpty())) { continue; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "mobile queues needs flushing - presences: {0}, packets: {1}", new Object[] {presenceQueue.size(), packetQueue.size() }); } holder.setState(res.getPacketTo(), QueueState.need_flush); } else { QueueState state = filter(session, res, holder.getState(res.getPacketTo()), presenceQueue, packetQueue); if (state == QueueState.queued) { it.remove(); if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "queue packet = {0}", res.toString()); if (presenceQueue.size() > maxQueueSize) { state = QueueState.need_flush; } else if (packetQueue.size() > maxQueueSize) state = QueueState.need_packet_flush; } state = holder.setState(res.getPacketTo(), state); } } for (Map.Entry<JID,QueueState> e : holder.states.entrySet()) { XMPPResourceConnection session = null; switch (e.getValue()) { case need_flush: try { session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Map<JID, Packet> presenceQueue = (Map<JID, Packet>) session.getSessionData(PRESENCE_QUEUE_KEY); synchronized (presenceQueue) { JID connId = session.getConnectionId(); for (Packet p : presenceQueue.values()) { p.setPacketTo(connId); holder.queue.offer(p); } presenceQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } case need_packet_flush: try { if (session == null) session = sessionFromSM.getParentSession().getResourceForConnectionId(e.getKey()); if (session != null) { Queue<Packet> packetQueue = (Queue<Packet>) session.getSessionData(PACKET_QUEUE_KEY); synchronized (packetQueue) { JID connId = session.getConnectionId(); Packet p = null; while ((p = packetQueue.poll()) != null) { p.setPacketTo(connId); holder.queue.offer(p); } packetQueue.clear(); } } } catch (NoConnectionIdException ex) { log.log(Level.SEVERE, "this should not happen", ex); } break; case queued: break; default: break; } } if (!holder.queue.isEmpty()) { if (log.isLoggable(Level.FINEST)) log.log(Level.FINEST, "sending queued packets = {0}", holder.queue.size()); holder.queue.addAll(results); results.clear(); results.addAll(holder.queue); } holder.reset(); } @Override void init(Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supStreamFeatures(XMPPResourceConnection session); @Override @SuppressWarnings("unchecked") void filter(Packet _packet, XMPPResourceConnection sessionFromSM,
NonAuthUserRepository repo, Queue<Packet> results); } | @Test public void testRecipientEnabledFor2ResourcesPresence() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); enableMobileV3(session1, recp1); Packet presence = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.available); presence.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(presence); Packet[] expected = new Packet[0]; mobileV3.filter(presence, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); }
@Test public void testRecipientEnabledFor2Resources2Presences() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); enableMobileV3(session1, recp1); Packet presence = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.available); presence.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(presence); Packet[] expected = new Packet[0]; mobileV3.filter(presence, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); presence = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.available); presence.setPacketTo(connId1); results = new ArrayDeque<Packet>(); results.offer(presence); expected = new Packet[0]; mobileV3.filter(presence, session1, null, results); processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); results.clear(); Packet p = Packet.packetInstance("message", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); results.offer(p); Packet p1 = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.error); p1.setPacketTo(connId1); results.offer(p1); expected = new Packet[] { presence, p, p1 }; mobileV3.filter(p, session1, null, results); processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); }
@Test public void testRecipientEnabledFor2Resources() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); enableMobileV3(session1, recp1); Packet presence = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.available); presence.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(presence); Packet[] expected = new Packet[0]; mobileV3.filter(presence, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); results.clear(); Packet p = Packet.packetInstance("message", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); results.offer(p); Packet p1 = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.error); p1.setPacketTo(connId1); results.offer(p1); expected = new Packet[] { presence, p, p1 }; mobileV3.filter(p, session1, null, results); processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); }
@Test public void testRecipientEnabledFor2ResourcesMixed() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); enableMobileV3(session1, recp1); Packet presence = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.available); presence.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(presence); Packet[] expected = new Packet[0]; mobileV3.filter(presence, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); results.clear(); Packet m1 = Packet.packetInstance("message", recp2.toString(), recp1.toString(), StanzaType.chat); Element receivedEl = new Element("received", new String[] { "xmlns" }, new String[] { "urn:xmpp:carbons:2" }); Element forwardedEl = new Element("forwarded", new String[] {"xmlns" }, new String[] { "urn:xmpp:forward:0" }); forwardedEl.addChild(new Element("message", new String[] { "from", "to" }, new String[] { recp2.toString(), "sender-1@localhost/res1" })); receivedEl.addChild(forwardedEl); m1.getElement().addChild(receivedEl); m1.setPacketTo(connId1); results.offer(m1); expected = new Packet[0]; mobileV3.filter(m1, session1, null, results); processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); results.clear(); presence = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.available); presence.setPacketTo(connId1); results.offer(presence); expected = new Packet[0]; mobileV3.filter(presence, session1, null, results); processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); results.clear(); Packet p = Packet.packetInstance("message", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); results.offer(p); Packet p1 = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.error); p1.setPacketTo(connId1); results.offer(p1); expected = new Packet[] { presence, m1, p, p1 }; mobileV3.filter(p, session1, null, results); processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); }
@Test public void testRecipientDisabledFor2ResourcesMessage() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); Packet p = Packet.packetInstance("message", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(p); Packet[] expected = results.toArray(new Packet[0]); mobileV3.filter(p, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); }
@Test public void testRecipientEnabledFor2ResourcesMessage() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); enableMobileV3(session1, recp1); Packet p = Packet.packetInstance("message", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(p); Packet[] expected = results.toArray(new Packet[0]); mobileV3.filter(p, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); }
@Test public void testRecipientDisabledFor2ResourcesPresence() throws TigaseStringprepException, NotAuthorizedException { String recipient = "recipient-1@localhost"; JID recp1 = JID.jidInstanceNS(recipient + "/res1"); JID recp2 = JID.jidInstanceNS(recipient + "/res2"); JID connId1 = JID.jidInstanceNS("c2s@localhost/recipient1-res1"); JID connId2 = JID.jidInstanceNS("c2s@localhost/recipient1-res2"); XMPPResourceConnection session1 = getSession(connId1, recp1); getSession(connId2, recp2); Packet p = Packet.packetInstance("presence", "sender-1@localhost/res1", recp1.toString(), StanzaType.chat); p.setPacketTo(connId1); ArrayDeque<Packet> results = new ArrayDeque<Packet>(); results.offer(p); Packet[] expected = results.toArray(new Packet[0]); mobileV3.filter(p, session1, null, results); Packet[] processed = results.toArray(new Packet[0]); Assert.assertArrayEquals(expected, processed); } |
BindResource extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc { @Override public boolean preProcess(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) { if ((session == null) || session.isServerSession() || !session.isAuthorized() || C2SDeliveryErrorProcessor.isDeliveryError( packet )) { return false; } try { if (session.getConnectionId().equals(packet.getPacketFrom())) { if (session.isResourceSet() || packet.isXMLNSStaticStr(Iq.IQ_BIND_PATH, "urn:ietf:params:xml:ns:xmpp-bind") || packet.isXMLNSStaticStr(COMPRESS_PATH, "http: JID from_jid = session.getJID(); if (from_jid != null) { if ( packet.getElemName() == tigase.server.Presence.ELEM_NAME && StanzaType.getSubsTypes().contains( packet.getType() ) && ( packet.getStanzaFrom() == null || !from_jid.getBareJID().equals( packet.getStanzaFrom().getBareJID() ) || packet.getStanzaFrom().getResource() != null ) ){ if ( log.isLoggable( Level.FINEST ) ){ log.log( Level.FINEST, "Setting correct from attribute: {0}", from_jid ); } packet.initVars( JID.jidInstance( from_jid.getBareJID() ), packet.getStanzaTo() ); } else if ( ( packet.getStanzaFrom() == null ) || ( ( packet.getElemName() == tigase.server.Presence.ELEM_NAME && !StanzaType.getSubsTypes().contains( packet.getType() ) || packet.getElemName() != tigase.server.Presence.ELEM_NAME ) && !from_jid.equals( packet.getStanzaFrom() ) ) ){ if ( log.isLoggable( Level.FINEST ) ){ log.log( Level.FINEST, "Setting correct from attribute: {0}", from_jid ); } packet.initVars( from_jid, packet.getStanzaTo() ); } else { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Skipping setting correct from attribute: {0}, is already correct.", packet.getStanzaFrom()); } } } else { log.log(Level.WARNING, "Session is authenticated but session.getJid() is empty: {0}", packet .toStringSecure()); } } else { results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You must bind the resource first: " + "http: if (log.isLoggable(Level.INFO)) { log.log(Level.INFO, "Session details: connectionId={0}, sessionId={1}", new Object[] { session.getConnectionId(), session.getSessionId() }); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Session more detais: JID={0}", session.getjid()); } return true; } } } catch (PacketErrorTypeException e) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Ignoring packet with an error to non-existen user session: {0}", packet .toStringSecure()); } } catch (Exception e) { log.log(Level.FINEST, "Packet preprocessing exception: ", e); return false; } return false; } @Override String id(); @Override void init(Map<String, Object> settings); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); @Override Element[] supStreamFeatures(final XMPPResourceConnection session); static final String DEF_RESOURCE_PREFIX_PROP_KEY; } | @Test public void testPreProcess() throws TigaseStringprepException, NotAuthorizedException, NoConnectionIdException { JID senderJid = JID.jidInstance("[email protected]/res-1"); JID recipientJid = JID.jidInstance("[email protected]/res-2"); XMPPResourceConnection senderSession = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), senderJid); Element messageEl = new Element("message", new String[] { "from" }, new String[] { senderJid.toString() }); Packet p = Packet.packetInstance(messageEl); p.setPacketFrom(senderSession.getConnectionId()); Map<String,Object> settings = new HashMap<>(); Queue<Packet> results = new ArrayDeque<>(); System.out.println( p.getElement() +"" ); System.out.println( ); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(senderJid, p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n" ); p.getElement().setAttribute( "from", senderJid.getBareJID().toString()); System.out.println( p.getElement() +"" ); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(senderJid, p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n"); p.getElement().removeAttribute("from"); System.out.println( p.getElement() +""); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(senderJid, p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n" ); System.out.println( "=====" ); Element presenceEl = new Element("presence", new String[] { "from" }, new String[] { senderJid.toString() }); p = Packet.packetInstance(presenceEl); p.setPacketFrom(senderSession.getConnectionId()); System.out.println( p.getElement() +"" ); System.out.println( ); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(senderJid, p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n" ); p.getElement().setAttribute( "from", senderJid.getBareJID().toString()); System.out.println( p.getElement() +"" ); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(senderJid, p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n"); p.getElement().removeAttribute("from"); System.out.println( p.getElement() +""); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(senderJid, p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n" ); System.out.println( "=====" ); p.getElement().setAttribute( "type", "subscribe"); p.getElement().setAttribute( "from", senderJid.toString()); p = Packet.packetInstance(p.getElement()); p.setPacketFrom(senderSession.getConnectionId()); System.out.println( p.getElement() +"" ); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(JID.jidInstance( senderJid.getBareJID()), p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n" ); p.getElement().setAttribute( "from", senderJid.getBareJID().toString()); System.out.println( p.getElement() +"" ); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(JID.jidInstance( senderJid.getBareJID()), p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n"); p.getElement().removeAttribute("from"); System.out.println( p.getElement() +""); assertFalse(bindResource.preProcess(p, senderSession, null, results, settings)); assertEquals(0, results.size()); assertEquals(JID.jidInstance( senderJid.getBareJID()), p.getStanzaFrom()); System.out.println( p.getStanzaFrom() +"\n" ); } |
C2SDeliveryErrorProcessor { public static boolean preProcess(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings, Message messageProcessor) { if (packet.getElemName() != tigase.server.Message.ELEM_NAME) return false; Element deliveryError = getDeliveryError(packet); if (deliveryError == null) return false; try { if (packet.getStanzaTo() != null && packet.getStanzaTo().getResource() == null && session != null) { if (packet.getElemName() != Message.ELEM_NAME) return true; List<XMPPResourceConnection> sessionsForMessageDelivery = messageProcessor.getConnectionsForMessageDelivery(session); if (sessionsForMessageDelivery.isEmpty()) return false; String delay = deliveryError.getAttributeStaticStr("stamp"); if (delay == null) return true; long time = Long.parseLong(delay); for (XMPPResourceConnection conn : sessionsForMessageDelivery) { if (conn.getCreationTime() <= time) continue; Packet result = packet.copyElementOnly(); result.setPacketFrom(packet.getPacketTo()); result.setPacketTo(conn.getConnectionId()); results.offer(result); } return true; } return false; } catch (NotAuthorizedException ex) { if (log.isLoggable(Level.FINEST)) { log.finest("NotAuthorizedException while processing undelivered message from " + "C2S, packet = " + packet); } } catch (NoConnectionIdException ex) { if (log.isLoggable(Level.FINEST)) { log.finest("NotAuthorizedException while processing undelivered message from " + "C2S, packet = " + packet); } } return false; } static void filter(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, JID toIgnore); static void filterErrorElement(Element messageElem); static boolean preProcess(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings, Message messageProcessor); static boolean isDeliveryError(Packet packet); static Element getDeliveryError(Packet packet); static Packet makeDeliveryError(Packet packet, Long stamp); static final String ELEM_NAME; static final String XMLNS; } | @Test public void testPreprocessingNotSupportedPackets() throws Exception { Element packetEl = null; Packet packet = null; JID from = JID.jidInstance("[email protected]/res"); JID to = JID.jidInstance("[email protected]"); packetEl = new Element("iq", new String[] { "id", "from", "to" }, new String[] { UUID.randomUUID().toString(), from.toString(), to.toString() }); packet = Packet.packetInstance(packetEl); assertFalse(C2SDeliveryErrorProcessor.preProcess(packet, null, null, null, null, messageProcessor)); packetEl = new Element("message", new String[] { "id", "from", "to" }, new String[] { UUID.randomUUID().toString(), from.toString(), to.toString() }); packet = Packet.packetInstance(packetEl); assertFalse(C2SDeliveryErrorProcessor.preProcess(packet, null, null, null, null, messageProcessor)); packetEl = new Element("message", new String[] { "id", "from", "to" }, new String[] { UUID.randomUUID().toString(), from.toString(), to.toString() }); packetEl.addChild(new Element("delivery-error", new String[] { "xmlns" }, new String[] { "http: packet = Packet.packetInstance(packetEl); assertFalse(C2SDeliveryErrorProcessor.preProcess(packet, null, null, null, null, messageProcessor)); } |
RosterElement { public final void setName(final String name) { if(name==this.name || (name!=null && this.name!=null && name.equals(this.name))){ return ; } else { this.name = name==null?null:XMLUtils.unescape(name); this.modified = true; } } RosterElement(Element roster_el, XMPPResourceConnection session); RosterElement(JID jid, String name, String[] groups,
XMPPResourceConnection session); void addGroups(String[] groups); String[] getGroups(); JID getJid(); String getName(); String getOtherData(); Element getRosterElement(); Element getRosterItem(); @Override String toString(); SubscriptionType getSubscription(); boolean isModified(); boolean isOnline(); boolean isPresence_sent(); final void setGroups(String[] groups); final void setName(final String name); void setOnline(String resource, boolean online); void setOtherData(String other_data); void setPresence_sent(boolean presence_sent); void setSubscription(SubscriptionType subscription); boolean isPersistent(); void setPersistent(boolean persistent); double getActivity(); void setActivity(double activity); double getWeight(); void setWeight(double weight); long getLastSeen(); void setLastSeen(long lastSeen); } | @Test public void testSetName() { RosterElement e = new RosterElement(JID.jidInstanceNS("[email protected]"), null, new String[] {}, null); assertNull(e.getName()); assertTrue(e.isModified()); e.getRosterElement(); assertFalse(e.isModified()); e.setName(null); assertFalse(e.isModified()); assertNull(e.getName()); e.setName("jeff"); assertTrue(e.isModified()); assertEquals("jeff", e.getName()); e.getRosterElement(); assertFalse(e.isModified()); e.setName("jeff"); assertFalse(e.isModified()); assertEquals("jeff", e.getName()); e.setName("bob"); assertTrue(e.isModified()); assertEquals("bob", e.getName()); e.getRosterElement(); assertFalse(e.isModified()); e.setName(null); assertTrue(e.isModified()); assertNull(e.getName()); e.getRosterElement(); assertFalse(e.isModified()); e.setName(null); assertFalse(e.isModified()); assertNull(e.getName()); } |
OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { @Override public void postProcess( final Packet packet, final XMPPResourceConnection conn, final NonAuthUserRepository repo, final Queue<Packet> queue, Map<String, Object> settings ) { if ( conn == null || !message.hasConnectionForMessageDelivery(conn) ){ try { if (packet.getElemName() == tigase.server.Message.ELEM_NAME && packet.getStanzaTo() != null && packet.getStanzaTo().getResource() != null) { return; } if (conn != null && packet.getStanzaTo() != null && !conn.isUserId(packet.getStanzaTo().getBareJID())) return; MsgRepositoryIfc msg_repo = getMsgRepoImpl( repo, conn ); publishInPubSub(packet, conn, queue, settings); Authorization saveResult = savePacketForOffLineUser( packet, msg_repo, repo ); Packet result = null; switch (saveResult) { case SERVICE_UNAVAILABLE: result = saveResult.getResponseMessage(packet, "Offline messages queue is full", true); break; default: break; } if (result != null) { queue.offer(result); } } catch ( UserNotFoundException e ) { if ( log.isLoggable( Level.FINEST ) ){ log.finest( "UserNotFoundException at trying to save packet for off-line user." + packet ); } } catch (NotAuthorizedException ex) { if ( log.isLoggable( Level.FINEST ) ){ log.log(Level.FINEST, "NotAuthorizedException when checking if message is to this " + "user at trying to save packet for off-line user, {0}, {1}", new Object[]{ packet, conn }); } } catch (PacketErrorTypeException ex) { log.log(Level.FINE, "Could not sent error to packet sent to offline user which storage to offline " + "store failed. Packet is error type already: {0}", packet.toStringSecure()); } } } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } | @Test public void testStorageOfflineMessageForBareJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", userJid.toString() }); packetEl.addChild(new Element("body", "Test message")); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("no message stored, while it should be stored", !msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPriority(1); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("no message stored, while it should be stored", !msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); }
@Test public void testStorageOfflineMessageForFullJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", res2.toString() }); packetEl.addChild(new Element("body", "Test message")); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPriority(1); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); offlineProcessor.postProcess(packet, session1, null, results, null); assertTrue("generated result even than no result should be generated", results.isEmpty()); assertTrue("message stored, while it should not be stored", msgRepo.getStored().isEmpty()); msgRepo.getStored().clear(); } |
OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { public Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn, MsgRepositoryIfc repo ) throws UserNotFoundException, NotAuthorizedException { Queue<Element> elems = repo.loadMessagesToJID( conn, true ); if ( elems != null ){ LinkedList<Packet> pacs = new LinkedList<Packet>(); Element elem = null; while ( ( elem = elems.poll() ) != null ) { try { Packet p = Packet.packetInstance( elem ); if (p.getElemName() == Iq.ELEM_NAME) { p.initVars(p.getStanzaFrom(), conn.getJID()); } pacs.offer( p ); } catch ( TigaseStringprepException ex ) { log.warning( "Packet addressing problem, stringprep failed: " + elem ); } } try { Collections.sort( pacs, new StampComparator() ); } catch ( NullPointerException e ) { try { log.warning( "Can not sort off line messages: " + pacs + ",\n" + e ); } catch ( Exception exc ) { log.log( Level.WARNING, "Can not print log message.", exc ); } } return pacs; } return null; } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } | @Test public void testRestorePacketForOffLineUser() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); assertEquals(Arrays.asList(session1), session1.getActiveSessions()); Element packetEl = new Element("iq", new String[] { "type", "from", "to", "time" }, new String[] { "set", "[email protected]/res1", userJid.toString(), "1440810935000" }); packetEl.addChild(new Element("jingle", new String[] { "action", "sid", "offline", "xmlns" }, new String[] { "session-terminate", UUID.randomUUID().toString(), "true", "urn:xmpp:jingle:1" })); Packet packet = Packet.packetInstance(packetEl); msgRepo.storeMessage( packet.getFrom(), packet.getTo(), null, packet.getElement(), null); packetEl = new Element("iq", new String[] { "type", "from", "to", "time" }, new String[] { "set", "[email protected]/res1", userJid.toString(), "1440810972000" }); packetEl.addChild(new Element("jingle", new String[] { "action", "sid", "offline", "xmlns" }, new String[] { "session-terminate", UUID.randomUUID().toString(), "true", "urn:xmpp:jingle:1" })); packet = Packet.packetInstance(packetEl); msgRepo.storeMessage( packet.getFrom(), packet.getTo(), null, packet.getElement(), null); assertTrue("no message stored, while it should be stored", !msgRepo.getStored().isEmpty()); Queue<Packet> restorePacketForOffLineUser = offlineProcessor.restorePacketForOffLineUser( session1, msgRepo ); assertEquals("number of restored messages differ!", restorePacketForOffLineUser.size(), 2); msgRepo.getStored().clear(); } |
DataTypes { public static int parseSizeInt(String size, int def) { return parseNum(size, Integer.class, def); } static T parseNum(String num, Class<T> cls, T def); static int parseSizeInt(String size, int def); static boolean parseBool(final String val); static Object decodeValueType(char typeId, String value); static String valueToString(final Object value); static char decodeTypeIdFromName(String name); static String stripNameFromTypeId(String name); static String encodeTypeIdInName(String name, Object value); static char getTypeId(Object instance); static boolean getProperty(String key, Boolean def); static void main( String[] args ); static final Map<String, Character> typesMap; } | @Test public void testParseSizeInt() { System.out.println( "parseSizeInt" ); assertEquals( 1, DataTypes.parseSizeInt( "1", 1 ) ); assertEquals( 1024, DataTypes.parseSizeInt( "1k", 1 ) ); assertEquals( 1024 * 1024, DataTypes.parseSizeInt( "1m", 1 ) ); assertEquals( 1024 * 1024 * 1024, DataTypes.parseSizeInt( "1g", 1 ) ); assertEquals( 1, DataTypes.parseSizeInt( "fail", 1 ) ); } |
OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean loadOfflineMessages( Packet packet, XMPPResourceConnection conn ) { if ( ( conn == null ) || conn.isAnonymous() ){ return false; } if ( conn.getSessionData( ID ) != null ){ return false; } if (packet.getStanzaTo() != null) return false; if ( conn.getCommonSessionData(FlexibleOfflineMessageRetrieval.FLEXIBLE_OFFLINE_XMLNS) != null ){ return false; } StanzaType type = packet.getType(); if ( ( type == null ) || ( type == StanzaType.available ) ){ String priority_str = packet.getElemCDataStaticStr( tigase.server.Presence.PRESENCE_PRIORITY_PATH ); int priority = 0; if ( priority_str != null ){ try { priority = Integer.decode( priority_str ); } catch ( NumberFormatException e ) { priority = 0; } } if ( priority >= 0 ){ conn.putSessionData( ID, ID ); return true; } } return false; } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } | @Test public void testLoadOfflineMessages() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element presenceEl = new Element("presence", new String[] { "from", "to" }, new String[] { res1.toString(), res2.toString() }); Packet packet = Packet.packetInstance(presenceEl); assertFalse(offlineProcessor.loadOfflineMessages(packet, session1)); presenceEl = new Element("presence", new String[] { "from" }, new String[] { res1.toString() }); packet = Packet.packetInstance(presenceEl); assertTrue(offlineProcessor.loadOfflineMessages(packet, session1)); } |
OfflineMessages extends XMPPProcessor implements XMPPPostprocessorIfc, XMPPProcessorIfc { protected boolean isAllowedForOfflineStorage(Packet pac) { for (ElementMatcher matcher : offlineStorageMatchers) { if (matcher.matches(pac)) return matcher.getValue(); } return isAllowedForOfflineStorageDefaults(pac); } @Override String id(); @Override void init(Map<String, Object> settings); @Override void postProcess( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> queue,
Map<String, Object> settings ); @Override void process( final Packet packet, final XMPPResourceConnection conn,
final NonAuthUserRepository repo, final Queue<Packet> results,
final Map<String, Object> settings ); void processIq(Packet packet, XMPPResourceConnection conn, NonAuthUserRepository repo, Queue<Packet> results); Queue<Packet> restorePacketForOffLineUser( XMPPResourceConnection conn,
MsgRepositoryIfc repo ); Authorization savePacketForOffLineUser( Packet pac, MsgRepositoryIfc repo, NonAuthUserRepository userRepo); @Override Element[] supDiscoFeatures( final XMPPResourceConnection session ); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); void publishInPubSub(final Packet packet, final XMPPResourceConnection conn, final Queue<Packet> queue,
Map<String, Object> settings); static final String[] MESSAGE_EVENT_PATH; static final String[] MESSAGE_HEADER_PATH; static final String[] MESSAGE_HINTS_NO_STORE; static final String MESSAGE_HINTS_XMLNS; static final String[] MESSAGE_RECEIVED_PATH; static final String MESSAGE_RECEIVED_XMLNS; static final String[] PUBSUB_NODE_PATH; static final String PUBSUB_NODE_KEY; } | @Test public void testIsAllowedForOfflineStorage() throws Exception { Packet packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("body", "Test message") }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("storeMe1", new String[] { "xmlns" }, new String[] { "custom_xmlns" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); Map<String,Object> settings = new HashMap<>(); settings.put("msg-store-offline-paths", new String[] { "/message/storeMe1[custom_xmlns]", "/message/storeMe2", "-/message/noStore1" }); offlineProcessor.init(settings); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("storeMe2", new String[] { "xmlns" }, new String[] { "custom_xmlns" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("storeMe3", new String[] { "xmlns" }, new String[] { "custom_xmlns" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("body", "Test message 123"), new Element("no-store", new String[] { "xmlns" }, new String[] { "urn:xmpp:hints" }) }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("noStore1"), new Element("body", "body of message") }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertFalse(offlineProcessor.isAllowedForOfflineStorage(packet)); packet = Packet.packetInstance(new Element("message", new Element[]{ new Element("body", "body of message") }, new String[] { "from", "to" }, new String[] { "[email protected]/res1", "[email protected]/res2" })); assertTrue(offlineProcessor.isAllowedForOfflineStorage(packet)); } |
JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { public static Authorization validateList(final XMPPResourceConnection session, final List<Element> items) { Authorization result = null; try { HashSet<Integer> orderSet = new HashSet<Integer>(); HashSet<String> groups = new HashSet<String>(); if (session != null) { JID[] jids = roster_util.getBuddies(session); if (jids != null) { for (JID jid : jids) { String[] buddyGroups = roster_util.getBuddyGroups(session, jid); if (buddyGroups != null) { for (String group : buddyGroups) { groups.add(group); } } } } } for (Element item : items) { ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); switch (type) { case jid : JID.jidInstance(value); break; case group : boolean matched = groups.contains(value); if (!matched) { result = Authorization.ITEM_NOT_FOUND; } break; case subscription : ITEM_SUBSCRIPTIONS.valueOf(value); break; case all : default : break; } if (result != null) { break; } ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); Integer order = Integer.parseInt(item.getAttributeStaticStr(ORDER)); if ((order == null) || (order < 0) ||!orderSet.add(order)) { result = Authorization.BAD_REQUEST; } if (result != null) { break; } } } catch (Exception ex) { result = Authorization.BAD_REQUEST; } return result; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | @Test public void testValidateListGood() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(null, result); }
@Test public void testValidateListBadAction() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "ignore", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); }
@Test public void testValidateListBadSubscription() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "or", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); }
@Test public void testValidateListBadType() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "other", "both", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); }
@Test public void testValidateListOrderUnsignedInt() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "allow", "-10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "15" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); }
@Test public void testValidateListOrderAttributeDuplicate() { List<Element> items = new ArrayList<Element>(); Authorization result = null; items.add(new Element("item", new String[] { "type", "value", "action", "order" }, new String[] { "subscription", "both", "allow", "10" })); items.add(new Element("item", new String[] { "action", "order" }, new String[] { "deny", "10" })); result = JabberIqPrivacy.validateList(null, items); assertEquals(Authorization.BAD_REQUEST, result); } |
JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc, XMPPPacketFilterIfc { protected boolean allowed(Packet packet, XMPPResourceConnection session) { try { if (allowedByDefault(packet, session)) return true; Element list = Privacy.getActiveList(session); if ((list == null) ) { list = Privacy.getDefaultList( session ); } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Using privcy list: {0}", list); } if (list != null) { List<Element> items = list.getChildren(); if (items != null) { BareJID sessionUserId = session.getBareJID(); JID jid = packet.getStanzaFrom(); boolean packetIn = true; if ((jid == null) || sessionUserId.equals(jid.getBareJID())) { jid = packet.getStanzaTo(); packetIn = false; } Collections.sort(items, compar); for (Element item : items) { final ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttributeStaticStr(ACTION)); boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttributeStaticStr(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttributeStaticStr(TYPE)); } String value = item.getAttributeStaticStr(VALUE); if (jid != null) { switch (type) { case jid : type_matched = jid.toString().contains(value); break; case group : String[] groups = roster_util.getBuddyGroups(session, jid); if (groups != null) { for (String group : groups) { if (type_matched = group.equals(value)) { break; } } } break; case subscription : ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to : type_matched = roster_util.isSubscribedTo(session, jid); break; case from : type_matched = roster_util.isSubscribedFrom(session, jid); break; case none : type_matched = (!roster_util.isSubscribedFrom(session, jid) && !roster_util.isSubscribedTo(session, jid)); break; case both : type_matched = (roster_util.isSubscribedFrom(session, jid) && roster_util.isSubscribedTo(session, jid)); break; default : break; } break; case all : default : type_matched = true; break; } } else { if (type == ITEM_TYPE.all) { type_matched = true; } } if (!type_matched) { continue; } List<Element> elems = item.getChildren(); if ((elems == null) || (elems.size() == 0)) { elem_matched = true; } else { for (Element elem : elems) { if (matchToPrivacyListElement(packetIn, packet, elem, action)) { elem_matched = true; break; } } } if (!elem_matched) { break; } switch (action) { case allow : return true; case deny : return false; default : break; } } } } else { return true; } } catch (NoConnectionIdException e) { } catch (NotAuthorizedException e) { } catch (TigaseDBException e) { log.log(Level.WARNING, "Database problem, please notify the admin. {0}", e); } return true; } @Override void filter(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results); @Override String id(); @Override boolean preProcess(Packet packet, XMPPResourceConnection session,
NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings); @Override void process(final Packet packet, final XMPPResourceConnection session,
final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String,
Object> settings); @Override Element[] supDiscoFeatures(final XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); static Authorization validateList(final XMPPResourceConnection session,
final List<Element> items); } | @Test public void testFilterPresenceOut() throws Exception { JID jid = JID.jidInstance("test@example/res-1"); JID connId = JID.jidInstance("[email protected]/asdasd"); XMPPResourceConnection session = getSession(connId, jid); Element list = new Element("list", new String[] { "name" }, new String[] { "default" }); Element item = new Element("item", new String[]{"type", "value", "action", "order"}, new String[]{"jid", "test1.example.com", "deny", "100"}); item.addChild(new Element("presence-out")); list.addChild(item); list.addChild(new Element("item", new String[]{"action", "order"}, new String[]{"allow", "110"})); session.putSessionData("active-list", list); Packet presence = Packet.packetInstance(new Element("presence", new String[] { "from", "to" }, new String[] { "test@example/res-1", "test1.example.com" })); assertFalse(privacyFilter.allowed(presence, session)); presence = Packet.packetInstance(new Element("presence", new String[] { "to", "from" }, new String[] { "test@example/res-1", "test1.example.com" })); assertTrue(privacyFilter.allowed(presence, session)); } |
MessageCarbons extends XMPPProcessor implements XMPPProcessorIfc, XMPPPacketFilterIfc,
XMPPPresenceUpdateProcessorIfc { @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (session == null) return; if (packet.getElemName() == Iq.ELEM_NAME) { boolean enable = packet.getElement().getChild(ENABLE_ELEM_NAME, XMLNS) != null; boolean disable = packet.getElement().getChild(DISABLE_ELEM_NAME, XMLNS) != null; if ((enable && disable) || (!enable && !disable)) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, null, false)); } else { JID sessionJid = session.getJID(); if (packet.getStanzaFrom() != null && !sessionJid.equals(packet.getStanzaFrom()) && session.isUserId(packet.getStanzaFrom().getBareJID()) && packet.getStanzaFrom().getResource() != null) { Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { synchronized (session.getParentSession()) { resources = (Map<JID, Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null) { resources = new ConcurrentHashMap<JID, Boolean>(); session.putCommonSessionData(ENABLED_RESOURCES_KEY, resources); } } } if (log.isLoggable(Level.FINER)) { log.log(Level.FINER, "received state notification from {0} with value = {1}", new Object[]{packet.getStanzaFrom(), enable}); } Boolean oldValue = resources.put(packet.getStanzaFrom(), enable); if (oldValue == null) { for (XMPPResourceConnection conn : session.getActiveSessions()) { notifyStateChanged(conn.getJID(), packet.getStanzaFrom(), isEnabled(conn), results); } } } else { setEnabled(session, enable, results); results.offer(packet.okResult((Element) null, 0)); } } } else if (packet.getElemName() == Message.ELEM_NAME && packet.getType() == StanzaType.chat && packet.getStanzaTo() != null) { if (C2SDeliveryErrorProcessor.isDeliveryError(packet)) return; Map<JID,Boolean> resources = (Map<JID,Boolean>) session.getCommonSessionData(ENABLED_RESOURCES_KEY); if (resources == null || resources.isEmpty()) { return; } if (packet.getType() == StanzaType.chat) { if (packet.getElement().getChild("received", XMLNS) != null || packet.getElement().getChild("sent", XMLNS) != null) { return; } if (packet.getAttributeStaticStr(MESSAGE_HINTS_NO_COPY, "xmlns") == MESSAGE_HINTS_XMLNS) { return; } Element privateEl = packet.getElement().getChild("private", XMLNS); if (privateEl != null) { packet.getElement().removeChild(privateEl); return; } String type = session.isUserId(packet.getStanzaTo().getBareJID()) ? "received" : "sent"; JID srcJid = JID.jidInstance(session.getBareJID()); Set<JID> skipForkingTo = null; if (session.isUserId(packet.getStanzaTo().getBareJID()) && packet.getStanzaTo().getResource() == null) { skipForkingTo = messageProcessor.getJIDsForMessageDelivery(session); for (JID jid : resources.keySet()) { if (session.getParentSession().getResourceForJID(jid) == null) skipForkingTo.add(jid); } } else { skipForkingTo = Collections.singleton(session.getJID()); } if ( log.isLoggable( Level.FINER ) ){ log.log( Level.FINER, "Sending message carbon copy, packet: {0}, resources {1}, skipForkingTo: {2}, session: {3}", new Object[] { packet, resources, skipForkingTo, session } ); } for (Map.Entry<JID, Boolean> entry : resources.entrySet()) { if (!entry.getValue()) { continue; } JID jid = entry.getKey(); if (skipForkingTo.contains(entry.getKey())) { continue; } Packet msgClone = prepareCarbonCopy(packet, srcJid, jid, type); results.offer(msgClone); } } } } @Override String id(); @Override void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo,
Queue<Packet> results, Map<String, Object> settings); @Override Element[] supDiscoFeatures(XMPPResourceConnection session); @Override String[][] supElementNamePaths(); @Override String[] supNamespaces(); @Override void presenceUpdate(XMPPResourceConnection session, Packet packet, Queue<Packet> results); @Override void filter(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results); static final String XMLNS; } | @Test public void testResourceSelectionForMessageDeliveryForBareJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); session2.putSessionData(MessageCarbons.XMLNS + "-enabled", true); Map<JID,Boolean> enabled = new HashMap<>(); enabled.put(res2, true); session2.putCommonSessionData(MessageCarbons.XMLNS + "-resources", enabled); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", userJid.toString() }); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session2, null, results, null); assertEquals("generated result even than no resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session2, null, results, null); assertEquals("not generated result even than 1 resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session2.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("not generated result even than 2 resource had nonnegative priority", 0, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(), collectStanzaTo(results)); }
@Test public void testResourceSelectionForMessageDeliveryForFullJid() throws Exception { BareJID userJid = BareJID.bareJIDInstance("[email protected]"); JID res1 = JID.jidInstance(userJid, "res1"); JID res2 = JID.jidInstance(userJid, "res2"); XMPPResourceConnection session1 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res1); XMPPResourceConnection session2 = getSession(JID.jidInstance("[email protected]/" + UUID.randomUUID().toString()), res2); session2.putSessionData(MessageCarbons.XMLNS + "-enabled", true); Map<JID,Boolean> enabled = new HashMap<>(); enabled.put(res2, true); session2.putCommonSessionData(MessageCarbons.XMLNS + "-resources", enabled); assertEquals(Arrays.asList(session1, session2), session1.getActiveSessions()); Element packetEl = new Element("message", new String[] { "type", "from", "to" }, new String[] { "chat", "[email protected]/res1", res1.toString() }); Packet packet = Packet.packetInstance(packetEl); Queue<Packet> results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("generated result even than no resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session1.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("not generated result even than 1 resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); session2.setPresence(new Element("presence")); results = new ArrayDeque<Packet>(); carbonsProcessor.process(packet, session1, null, results, null); assertEquals("not generated result even than 2 resource had nonnegative priority", 1, results.size()); assertEquals("packet sent to wrong jids", Arrays.asList(session2.getJID()), collectStanzaTo(results)); results = new ArrayDeque<Packet>(); Packet packet1 = packet.copyElementOnly(); packet1.getElement().addChild(new Element("no-copy", new String[] { "xmlns" }, new String[] { "urn:xmpp:hints" })); carbonsProcessor.process(packet1, session1, null, results, null); assertEquals("generated result even that no-copy was sent", 0, results.size()); assertEquals("packet sent to wrong jids", Collections.EMPTY_LIST, collectStanzaTo(results)); } |
SSLContextContainer implements SSLContextContainerIfc { public static <T> T find(Map<String, T> data, String key) { if (data.containsKey(key)) { return data.get(key); } int idx = key.indexOf("."); if (idx >= 0) { String asteriskKey = "*" + key.substring(idx); T value = data.get(asteriskKey); if (value != null) { data.put(key, value); return value; } } return null; } @Override void addCertificates(Map<String, String> params); SSLContext getSSLContext(String protocol, String hostname, boolean clientMode); static T find(Map<String, T> data, String key); @Override SSLContext getSSLContext(String protocol, String hostname, boolean clientMode, TrustManager... tms); @Override KeyStore getTrustStore(); @Override void init(Map<String, Object> params); final static String PER_DOMAIN_CERTIFICATE_KEY; } | @Test public void testFind() { final HashMap<String, String> domains = new HashMap<String, String>(); domains.put("one.com", "one.com"); domains.put("a.two.com", "a.two.com"); domains.put("*.two.com", "*.two.com"); assertEquals("one.com", SSLContextContainer.find(domains, "one.com")); assertNull(SSLContextContainer.find(domains, "tone.com")); assertNull(SSLContextContainer.find(domains, "zero.com")); assertEquals("a.two.com", SSLContextContainer.find(domains, "a.two.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, "b.two.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, "b.two.com")); assertNull(SSLContextContainer.find(domains, "btwo.com")); assertEquals("*.two.com", SSLContextContainer.find(domains, ".two.com")); } |
Dialback extends S2SAbstractProcessor { @Override public boolean process(Packet p, S2SIOService serv, Queue<Packet> results) { CID cid = (CID) serv.getSessionData().get("cid"); boolean skipTLS = (cid == null) ? false : skipTLSForHost(cid.getRemoteHost()); if (p.getXMLNS() == XMLNS_DB_VAL) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Processing dialback packet: {1}", new Object[] { serv, p }); } processDialback(p, serv); return true; } if (p.isElement(FEATURES_EL, FEATURES_NS)) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Stream features received packet: {1}", new Object[] { serv, p }); } CertCheckResult certCheckResult = (CertCheckResult) serv.getSessionData().get(S2SIOService.CERT_CHECK_RESULT); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, TLS Certificate check: {1}, packet: {2}", new Object[] { serv, certCheckResult, p }); } if (p.isXMLNSStaticStr(FEATURES_STARTTLS_PATH, START_TLS_NS) && (certCheckResult == null) &&!skipTLS) { if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Waiting for starttls, packet: {1}", new Object[] { serv, p }); } return true; } if ((certCheckResult == CertCheckResult.trusted) && !(p.isXMLNSStaticStr(FEATURES_DIALBACK_PATH, DIALBACK_NS))) { if (ejabberd_bug_workaround_active) { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, Ejabberd bug workaround active, proceeding to dialback anyway, packet: {1}", new Object[] { serv, p }); } } else { if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "{0}, TLS trusted peer, no dialback needed or requested, packet: {1}", new Object[] { serv, p }); } CIDConnections cid_conns; try { cid_conns = handler.getCIDConnections(cid, true); cid_conns.connectionAuthenticated(serv, cid); } catch (NotLocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect local hostname, packet: {1}", new Object[] { serv, p }); serv.forceStop(); } catch (LocalhostException ex) { log.log(Level.INFO, "{0}, Incorrect remote hostname name, packet: {1}", new Object[] { serv, p }); serv.stop(); } return true; } } if (!skipTLS && cid != null && !serv.getSessionData().containsKey("TLS") && handler.isTlsRequired(cid.getLocalHost())) { log.log(Level.FINER, "{0}, TLS is required for domain {1} but STARTTLS was not " + "offered by {2} - policy-violation", new Object[] { serv, cid.getLocalHost(), cid.getRemoteHost() }); serv.forceStop(); return true; } if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "{0}, Initializing dialback, packet: {1}", new Object[] { serv, p }); } initDialback(serv, serv.getSessionId()); } return false; } Dialback(); @Override int order(); @Override boolean process(Packet p, S2SIOService serv, Queue<Packet> results); @Override void serviceStarted(S2SIOService serv); @Override void streamFeatures(S2SIOService serv, List<Element> results); @Override String streamOpened(S2SIOService serv, Map<String, String> attribs); } | @Test public void testAuthorizationForSingleDomain() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertEquals(remote1, cid.getRemoteHost())); }
@Test public void testAuthorizationForSingleDomainFailure() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "invalid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.invalid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertNotSame(remote1, cid.getRemoteHost())); }
@Test public void testAuthorizationWithMultiplexing() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertEquals(remote1, cid.getRemoteHost())); key = UUID.randomUUID().toString(); resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote2); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote2.equals(p.getStanzaTo().getDomain())); assertTrue(serv.getCIDs().stream().anyMatch((CID cid) -> remote1.equals(cid.getRemoteHost()))); assertTrue(serv.getCIDs().stream().anyMatch((CID cid) -> remote2.equals(cid.getRemoteHost()))); }
@Test public void testAuthorizationWithMultiplexingWithFailure() throws TigaseStringprepException { Queue<Packet> results = new ArrayDeque<>(); handler = new S2SConnectionHandlerImpl(results); dialback.init(handler, new HashMap()); String key = UUID.randomUUID().toString(); S2SIOService serv = new S2SIOService(); serv.setSessionId("sess-id-1"); Map<String,Object> props = new HashMap<>(); props.put(PORT_TYPE_PROP_KEY, "accept"); serv.setSessionData(props); Packet p = null; Element resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote1); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); Packet r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "valid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.valid && remote1.equals(p.getStanzaTo().getDomain())); serv.getCIDs().forEach((CID cid) -> assertEquals(remote1, cid.getRemoteHost())); key = UUID.randomUUID().toString(); resultEl = new Element("db:result"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("from", remote2); resultEl.setAttribute("to", local); resultEl.setCData(key); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); r = results.poll(); resultEl = new Element("db:verify"); resultEl.setXMLNS(Dialback.XMLNS_DB_VAL); resultEl.setAttribute("id", r.getAttributeStaticStr("id")); resultEl.setAttribute("from", r.getAttributeStaticStr("to")); resultEl.setAttribute("to", r.getAttributeStaticStr("from")); resultEl.setAttribute("type", "invalid"); p = Packet.packetInstance(resultEl); dialback.process(p, serv, results); p = results.poll(); assertTrue(p.getType() == StanzaType.invalid && remote2.equals(p.getStanzaTo().getDomain())); assertTrue(serv.getCIDs().stream().anyMatch((CID cid) -> remote1.equals(cid.getRemoteHost()))); assertTrue(serv.getCIDs().stream().allMatch((CID cid) -> !remote2.equals(cid.getRemoteHost()))); } |
WebSocketHybi implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (!headers.containsKey(WS_VERSION_KEY)) { return false; } StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); int version = Integer.parseInt(headers.get(WS_VERSION_KEY)); String key = headers.get(WS_KEY_KEY) + GUID; MessageDigest md = MessageDigest.getInstance("SHA1"); byte[] resp = md.digest(key.getBytes()); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); response.append(WS_ACCEPT_KEY + ": "); response.append(Base64.encode(resp)); response.append("\r\n"); response.append("\r\n"); service.maskingKey = new byte[4]; service.writeRawData(response.toString()); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); static final String ID; } | @Test public void testHandshakeFail() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Key1", "1C2J899_05 6 ! M 9 ^4"); params.put("Sec-WebSocket-Key2", "23 2ff0M_E0#.454X23"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertFalse("Handshake succeeded", impl.handshake(io, params, bytes)); }
@Test public void testHandshakeOK() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Version", "13"); params.put("Sec-WebSocket-Key", "some random data as a key"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertTrue("Handshake failed", impl.handshake(io, params, bytes)); } |
WebSocketXMPPIOService extends XMPPIOService<RefObject> { protected int parseHttpHeaders(byte[] buf, Map<String, String> headers) { int i = 0; while (buf[i] != '\n') { i++; } i++; if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "parsing request = \n{0}", new String(buf)); } StringBuilder builder = new StringBuilder(64); String key = null; boolean skipWhitespace = false; for (; i < buf.length; i++) { switch (buf[i]) { case ':': if (key == null) { key = builder.toString().trim(); builder = new StringBuilder(64); skipWhitespace = true; } else { builder.append((char) buf[i]); } break; case '\r': headers.put(key, builder.toString().trim()); key = null; builder = new StringBuilder(64); if (buf[i + 2] == '\r') { i += 3; } else { i++; } break; case ' ': case '\t': if (!skipWhitespace) { builder.append((char) buf[i]); } break; default: skipWhitespace = false; builder.append((char) buf[i]); } } return i; } WebSocketXMPPIOService(WebSocketProtocolIfc[] enabledProtocols); @Override void stop(); void dumpHeaders(Map<String,String> headers); } | @Test public void testHttpHeadersParsingWithSpaces() throws UnsupportedEncodingException { byte[] data = prepareHTTPRequest(headers, true); Map<String, String> parsedHeaders = new HashMap<>(); service.parseHttpHeaders(data, parsedHeaders); assertMaps(headers, parsedHeaders); }
@Test public void testHttpHeadersParsingWithoutSpaces() throws UnsupportedEncodingException { byte[] data = prepareHTTPRequest(headers, false); Map<String, String> parsedHeaders = new HashMap<>(); service.parseHttpHeaders(data, parsedHeaders); assertMaps(headers, parsedHeaders); } |
WebSocketHixie76 implements WebSocketProtocolIfc { @Override public boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf) throws NoSuchAlgorithmException, IOException { if (headers.containsKey(WS_VERSION_KEY)) { return false; } byte[] secBufArr = new byte[16]; Long secKey1 = decodeHyxie76SecKey(headers.get(WS_KEY1_KEY)); Long secKey2 = decodeHyxie76SecKey(headers.get(WS_KEY2_KEY)); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "WS-KEY1 = {0}", secKey1); log.log(Level.FINEST, "WS-KEY2 = {0}", secKey2); } uintToBytes(secBufArr, 0, secKey1); uintToBytes(secBufArr, 4, secKey2); if (buf[buf.length - 9] != '\n') { throw new IOException("buf[len-9] != \\n!!"); } for (int j = 8; j > 0; j--) { secBufArr[8 + 8 - j] = buf[buf.length - j]; } MessageDigest md = MessageDigest.getInstance("MD5"); byte[] resp = md.digest(secBufArr); StringBuilder response = new StringBuilder(RESPONSE_HEADER.length() * 2); response.append(RESPONSE_HEADER); response.append("Content-Length: ").append(resp.length).append("\r\n"); response.append(WS_PROTOCOL_KEY).append(": "); if (headers.get(WS_PROTOCOL_KEY).contains("xmpp-framing")) { response.append("xmpp-framing"); } else { response.append("xmpp"); } response.append("\r\n"); if (headers.containsKey(ORIGIN_KEY)) { response.append(WS_ORIGIN_KEY).append(": ").append(headers.get(ORIGIN_KEY)).append("\r\n"); } boolean ssl = SocketType.ssl == ((SocketType) service.getSessionData().get("socket")); int localPort = service.getLocalPort(); String location = (ssl ? "wss: + headers.get(HOST_KEY) + (((ssl && localPort == 443) || (!ssl && localPort == 80) || headers.get(HOST_KEY).contains(":")) ? "" : (":" + localPort)) + "/"; response.append(WS_LOCATION_KEY).append(": ").append(location).append("\r\n"); response.append("\r\n"); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "sending response = \n{0}", response.toString()); } byte[] respBytes = response.toString().getBytes(); ByteBuffer out = ByteBuffer.allocate(respBytes.length + 16); out.put(respBytes); out.put(resp); out.flip(); service.writeBytes(out); return true; } @Override String getId(); @Override boolean handshake(WebSocketXMPPIOService service, Map<String, String> headers, byte[] buf); @Override ByteBuffer decodeFrame(WebSocketXMPPIOService service, ByteBuffer buf); @Override void encodeFrameAndWrite(WebSocketXMPPIOService service, ByteBuffer buf); @Override void closeConnection(WebSocketXMPPIOService service); static final String ID; } | @Test public void testHandshakeOK() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Key1", "1C2J899_05 6 ! M 9 ^4"); params.put("Sec-WebSocket-Key2", "23 2ff0M_E0#.454X23"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertTrue("Handshake failed", impl.handshake(io, params, bytes)); }
@Test public void testHandshakeFail() throws NoSuchAlgorithmException, IOException { final ByteBuffer tmp = ByteBuffer.allocate(2048); WebSocketXMPPIOService<Object> io = new WebSocketXMPPIOService<Object>(new WebSocketProtocolIfc[]{ new WebSocketHixie76() }) { @Override protected void writeBytes(ByteBuffer data) { tmp.put(data); } @Override public int getLocalPort() { return 80; } }; Map<String,String> params = new HashMap<String,String>(); params.put("Sec-WebSocket-Version", "13"); params.put("Sec-WebSocket-Protocol", "xmpp"); byte[] bytes = new byte[10]; bytes[0] = '\r'; bytes[1] = '\n'; Assert.assertFalse("Handshake succeeded", impl.handshake(io, params, bytes)); } |
JDBCRepository implements AuthRepository, UserRepository { @Override public String getData(BareJID user_id, final String subnode, final String key, final String def) throws UserNotFoundException, TigaseDBException { try { long nid = getNodeNID(null, user_id, subnode); if (log.isLoggable(Level.FINEST)) { log.log( Level.FINEST, "Loading data for key: {0}, user: {1}, node: {2}, def: {3}, found nid: {4}", new Object[] { key, user_id, subnode, def, nid }); } if (nid > 0) { ResultSet rs = null; PreparedStatement data_for_node_st = data_repo.getPreparedStatement(user_id, DATA_FOR_NODE_QUERY); synchronized (data_for_node_st) { try { String result = def; data_for_node_st.setLong(1, nid); data_for_node_st.setString(2, key); rs = data_for_node_st.executeQuery(); if (rs.next()) { result = rs.getString(1); if (log.isLoggable(Level.FINEST)) { log.log(Level.FINEST, "Found data: {0}", result); } } return result; } finally { data_repo.release(null, rs); } } } else { return def; } } catch (SQLException e) { throw new TigaseDBException("Error getting user data for: " + user_id + "/" + subnode + "/" + key, e); } } @Override void addDataList(BareJID user_id, final String subnode, final String key,
final String[] list); @Override void addUser(BareJID user_id); @Override void addUser(BareJID user, final String password); @Override @Deprecated boolean digestAuth(BareJID user, final String digest, final String id,
final String alg); @Override String getData(BareJID user_id, final String subnode, final String key,
final String def); @Override String getData(BareJID user_id, final String subnode, final String key); @Override String getData(BareJID user_id, final String key); @Override String[] getDataList(BareJID user_id, final String subnode, final String key); @Override String[] getKeys(BareJID user_id, final String subnode); @Override String[] getKeys(BareJID user_id); @Override String getResourceUri(); @Override String[] getSubnodes(BareJID user_id, final String subnode); @Override String[] getSubnodes(BareJID user_id); @Override long getUserUID(BareJID user_id); long getUserUID(DataRepository repo, BareJID user_id); @Override List<BareJID> getUsers(); @Override long getUsersCount(); @Override long getUsersCount(String domain); @Override void initRepository(final String connection_str, Map<String, String> params); @Override void logout(BareJID user); @Override boolean otherAuth(final Map<String, Object> props); @Override @Deprecated boolean plainAuth(BareJID user, final String password); @Override void queryAuth(Map<String, Object> authProps); @Override void removeData(BareJID user_id, final String subnode, final String key); @Override void removeData(BareJID user_id, final String key); @Override void removeSubnode(BareJID user_id, final String subnode); @Override void removeUser(BareJID user_id); @Override void setData(BareJID user_id, final String subnode, final String key,
final String value); @Override void setData(BareJID user_id, final String key, final String value); @Override void setDataList(BareJID user_id, final String subnode, final String key,
final String[] list); @Override void updatePassword(BareJID user, final String password); @Override boolean userExists(BareJID user); @Override String getPassword(BareJID user); @Override boolean isUserDisabled(BareJID user); @Override void setUserDisabled(BareJID user, Boolean value); static final String CURRENT_DB_SCHEMA_VER; static final String DEF_MAXIDS_TBL; static final String DEF_NODES_TBL; static final String DEF_PAIRS_TBL; static final String DEF_ROOT_NODE; static final String DEF_USERS_TBL; static final String DERBY_GETSCHEMAVER_QUERY; static final String SQLSERVER_GETSCHEMAVER_QUERY; static final String JDBC_GETSCHEMAVER_QUERY; static final String SCHEMA_UPGRADE_LINK; } | @Test public void testGetData() throws InterruptedException { System.out.println( "repo: " + repo ); if ( repo != null ){ LocalDateTime localNow = LocalDateTime.now(); long initalDelay = 5; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool( 10 ); final int iter = 50; final int threads = 10; for ( int i = 0 ; i < threads ; i++ ) { scheduler.scheduleAtFixedRate( new RunnableImpl( iter ), initalDelay, 100, TimeUnit.MILLISECONDS ); } Thread.sleep( threads * 1000 ); } } |
ClusterElement { public String getMethodName() { return method_name; } ClusterElement(Element elem); ClusterElement(JID from, JID to, StanzaType type, Packet packet); static Element clusterElement(JID from, JID to, StanzaType type); static Element createClusterElement(JID from, JID to, StanzaType type,
String packet_from); static ClusterElement createClusterMethodCall(JID from, JID to, StanzaType type,
String method_name, Map<String, String> params); static ClusterElement createForNextNode(ClusterElement clel,
List<JID> cluster_nodes, JID comp_id); void addDataPacket(Packet packet); void addDataPacket(Element packet); void addDataPackets(Queue<Element> packets); void addMethodResult(String key, String val); void addVisitedNode(JID node_id); void addVisitedNodes(Set<JID> nodes); ClusterElement createMethodResponse(JID from, StanzaType type,
Map<String, String> results); ClusterElement createMethodResponse(JID from, JID to, StanzaType type,
Map<String, String> results); Map<String, String> getAllMethodParams(); Map<String, String> getAllMethodResults(); Element getClusterElement(String id); Queue<Element> getDataPackets(); JID getFirstNode(); String getMethodName(); String getMethodParam(String par_name); long getMethodParam(String par_name, long def); String getMethodResultVal(String val_name); long getMethodResultVal(String val_name, long def); Priority getPriority(); Set<JID> getVisitedNodes(); boolean isVisitedNode(JID node_id); void setPriority(Priority priority); ClusterElement nextClusterNode(JID node_id); static final String CLUSTER_CONTROL_EL_NAME; static final String CLUSTER_DATA_EL_NAME; static final String CLUSTER_EL_NAME; static final String CLUSTER_METHOD_EL_NAME; static final String CLUSTER_METHOD_PAR_EL_NAME; static final String CLUSTER_METHOD_RESULTS_EL_NAME; static final String CLUSTER_METHOD_RESULTS_VAL_EL_NAME; static final String CLUSTER_NAME_ATTR; static final String FIRST_NODE_EL_NAME; static final String NODE_ID_EL_NAME; static final String VISITED_NODES_EL_NAME; static final String XMLNS; static final String[] VISITED_NODES_PATH; static final String[] FIRST_NODE_PATH; static final String[] CLUSTER_METHOD_RESULTS_PATH; static final String[] CLUSTER_METHOD_PATH; static final String[] CLUSTER_DATA_PATH; static final String[] CLUSTER_CONTROL_PATH; } | @Test @SuppressWarnings("deprecation") public void testGetMethodName() { SimpleParser parser = new SimpleParser(); DomBuilderHandler handler = new DomBuilderHandler(); char[] data = "<cluster to=\"sess-man@blue\" type=\"set\" id=\"cl-6627\" xmlns=\"tigase:cluster\" from=\"sess-man@green\"><control><visited-nodes><node-id>sess-man@green</node-id></visited-nodes><method-call name=\"packet-forward-sm-cmd\"/><first-node>sess-man@green</first-node></control><data><presence to=\"test2@test\" xmlns=\"jabber:client\" from=\"test1@test/test\"><status/><priority>5</priority></presence></data></cluster>".toCharArray(); parser.parse(handler, data, 0, data.length); Element elem = handler.getParsedElements().poll(); assertEquals( "packet-forward-sm-cmd", elem.findChild("/cluster/control/method-call").getAttributeStaticStr("name")); ClusterElement clElem = new ClusterElement(elem); assertEquals("packet-forward-sm-cmd", clElem.getMethodName()); } |
ClusterConnectionSelector implements ClusterConnectionSelectorIfc { @Override public XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn) { if (conn == null) return null; int code = Math.abs(handler.hashCodeForPacket(p)); List<XMPPIOService<Object>> conns = conn.getConnections(); if (conns.size() > 0) { if (conns.size() > sysConns) { if (p.getPriority() != null && p.getPriority().ordinal() <= Priority.CLUSTER.ordinal()) { return conns.get(code % sysConns); } else { return conns.get(sysConns + (code % (conns.size() - sysConns))); } } else { return conns.get(code % conns.size()); } } return null; } @Override XMPPIOService<Object> selectConnection(Packet p, ClusterConnection conn); @Override void setClusterConnectionHandler(ClusterConnectionHandler handler); @Override void setProperties(Map<String,Object> props); } | @Test public void testSelectConnection() throws Exception { ClusterConnection conn = new ClusterConnection("test"); ClusterConnectionSelector selector = new ClusterConnectionSelector(); selector.setClusterConnectionHandler(new ClusterConnectionHandler() { @Override public int hashCodeForPacket(Packet packet) { return packet.getStanzaFrom().hashCode(); } }); Map<String,Object> props = new HashMap<>(); props.put(CLUSTER_SYS_CONNECTIONS_PER_NODE_PROP_KEY, 1); selector.setProperties(props); Element el = new Element("iq", new String[] { "from" }, new String[] { "test1" }); Packet p = Packet.packetInstance(el); assertNull(selector.selectConnection(p, conn)); XMPPIOService<Object> serv1 = new XMPPIOService<Object>(); conn.addConn(serv1); assertEquals(serv1, selector.selectConnection(p, conn)); p.setPriority(Priority.SYSTEM); assertEquals(serv1, selector.selectConnection(p, conn)); p.setPriority(null); XMPPIOService<Object> serv2 = new XMPPIOService<Object>(); conn.addConn(serv2); assertEquals(2, conn.size()); assertEquals(serv2, selector.selectConnection(p, conn)); p.setPriority(Priority.SYSTEM); assertEquals(serv1, selector.selectConnection(p, conn)); p.setPriority(null); XMPPIOService<Object> serv3 = new XMPPIOService<Object>(); conn.addConn(serv3); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); p.setPriority(Priority.SYSTEM); assertEquals(serv1, selector.selectConnection(p, conn)); el = new Element("iq", new String[] { "from" }, new String[] { "test2" }); p = Packet.packetInstance(el); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); el = new Element("iq", new String[] { "from" }, new String[] { "test3" }); p = Packet.packetInstance(el); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); el = new Element("iq", new String[] { "from" }, new String[] { "test4" }); p = Packet.packetInstance(el); assertEquals(3, conn.size()); assertNotSame(serv1, selector.selectConnection(p, conn)); } |
CustomDomainFilter { public static Set<Rule> parseRules( String rules ) throws ParseException { String[] rulesArr = rules.split( ";" ); if ( rulesArr != null ){ return parseRules( rulesArr ); } return null; } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } | @Test public void testParseRules() throws TigaseStringprepException, ParseException { System.out.println( "parseRules" ); Set<Rule> expResult = new TreeSet<>(); Rule rule = new Rule( 1, true, RuleType.self, null ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 2, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 3, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 4, false, RuleType.all, null ); if ( rule != null ){ expResult.add( rule ); } Set<Rule> result = CustomDomainFilter.parseRules( rules ); assertEquals( expResult, result ); }
@Test public void testParseRulesString() throws TigaseStringprepException, ParseException { System.out.println( "parseRules" ); String rulseString = "4|deny|all;1|allow|self;3|allow|jid|[email protected];2|allow|jid|[email protected]"; Set<Rule> expResult = new TreeSet<>(); Rule rule = new Rule( 1, true, RuleType.self, null ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 2, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 3, true, RuleType.jid, JID.jidInstance( "[email protected]" ) ); if ( rule != null ){ expResult.add( rule ); } rule = new Rule( 4, false, RuleType.all, null ); if ( rule != null ){ expResult.add( rule ); } Set<Rule> result = CustomDomainFilter.parseRules( rulseString ); assertEquals( expResult, result ); rulseString = "1|allow|self;2|allow|jid|[email protected];3|allow|jid|[email protected];4|deny|all;"; String resultString = new String(); for ( Rule res : result) { resultString += res.toConfigurationString(); } assertEquals( rulseString, resultString ); }
@Test(expected = ParseException.class) public void testParseRulesException() throws TigaseStringprepException, ParseException { String[] rules_fail = { "8|deny|||self,", "|||18|||deny,self::::" }; Set<Rule> result = CustomDomainFilter.parseRules( rules_fail ); } |
CustomDomainFilter { public static boolean isAllowed( JID source, JID destination, String rules ) { try { Set<Rule> parseRules = parseRules( rules ); if ( parseRules != null ){ return isAllowed( source, destination, parseRules ); } else { return true; } } catch ( ParseException e ) { return true; } } private CustomDomainFilter(); static Set<Rule> parseRules( String rules ); static Set<Rule> parseRules( String[] rules ); static boolean isAllowed( JID source, JID destination, String rules ); static boolean isAllowed( JID source, JID destination, String[] rules ); static boolean isAllowed( JID source, JID destination, Set<Rule> rules ); } | @Test public void testIsAllowed() throws TigaseStringprepException, ParseException { JID jid1_r1 = JID.jidInstance( "user1", "domain1", "resource1" ); JID jid1_r2 = JID.jidInstance( "user1", "domain1", "resource2" ); JID jid2_r1 = JID.jidInstance( "user2", "domain1", "resource1" ); JID jid3_r1 = JID.jidInstance( "user3", "domain1", "resource1" ); JID admin = JID.jidInstance( "admin", "test2.com" ); JID pubsub = JID.jidInstance( "pubsub", "test.com" ); boolean allowed = CustomDomainFilter.isAllowed( jid1_r1, jid1_r2, rules ); assertTrue( "should be allowed / self / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid1_r1, admin, rules ); assertTrue( "should be allowed / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid1_r1, pubsub, rules ); assertTrue( "should be allowed / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid1_r1, jid2_r1, rules ); assertFalse( "should be denyed / permitted jid", allowed ); allowed = CustomDomainFilter.isAllowed( jid2_r1, jid2_r1, rules ); assertTrue( "should be allowed / self", allowed ); allowed = CustomDomainFilter.isAllowed( jid3_r1, jid2_r1, rules ); assertFalse( "should be denied / not permitted jids", allowed ); } |
NodeNameUtil { public static String createNodeName(String eventName, String xmlns) { return (eventName == null ? "*" : eventName) + "|" + (xmlns == null ? "*" : xmlns); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); } | @Test public void testCreateNodeName() throws Exception { assertEquals("1|2", NodeNameUtil.createNodeName("1", "2")); assertEquals("*|2", NodeNameUtil.createNodeName(null, "2")); assertEquals("*|*", NodeNameUtil.createNodeName(null, null)); assertEquals("1|*", NodeNameUtil.createNodeName("1", null)); } |
NodeNameUtil { public static EventName parseNodeName(String nodeName) { int i = nodeName.indexOf('|'); String n = nodeName.substring(0, i); String x = nodeName.substring(i + 1); return new EventName(n.equals("*") ? null : n, x.equals("*") ? null : x); } private NodeNameUtil(); static String createNodeName(String eventName, String xmlns); static EventName parseNodeName(String nodeName); } | @Test public void testParseNodeName() throws Exception { assertEquals(new EventName("1", "2"), NodeNameUtil.parseNodeName("1|2")); assertEquals(new EventName(null, "2"), NodeNameUtil.parseNodeName("*|2")); assertEquals(new EventName(null, null), NodeNameUtil.parseNodeName("*|*")); assertEquals(new EventName("1", null), NodeNameUtil.parseNodeName("1|*")); assertEquals(new EventName("1", ""), NodeNameUtil.parseNodeName("1|")); assertEquals(new EventName("", ""), NodeNameUtil.parseNodeName("|")); } |
EventName { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; EventName other = (EventName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (xmlns == null) { if (other.xmlns != null) return false; } else if (!xmlns.equals(other.xmlns)) return false; return true; } EventName(String name, String xmlns); @Override boolean equals(Object obj); String getName(); String getXmlns(); @Override int hashCode(); String toEventBusNode(); @Override String toString(); } | @Test public void testEquals() throws Exception { assertEquals(new EventName(null, null), new EventName(null, null)); assertEquals(new EventName(null, "2"), new EventName(null, "2")); assertEquals(new EventName("1", "2"), new EventName("1", "2")); assertNotEquals(new EventName(null, null), new EventName("2", "2")); assertNotEquals(new EventName(null, null), new EventName(null, "2")); assertNotEquals(new EventName(null, null), new EventName("2", null)); assertNotEquals(new EventName("1", null), new EventName("2", "2")); assertNotEquals(new EventName(null, "2"), new EventName("2", "2")); assertNotEquals(new EventName("2", "1"), new EventName("2", "2")); } |
ImageResizer { public byte[] resize(BufferedImage originalImage) throws IOException { if (originalImage == null) { throw new IIOException("Image is null. Did ImageIO fail to decode the image?"); } BufferedImage resized = ImageUtil.resizeImage(originalImage, size, size); originalImage.flush(); byte[] resizedBytes = com.github.dozedoff.similarImage.util.ImageUtil.imageToBytes(resized); resized.flush(); return resizedBytes; } ImageResizer(int size); byte[] resize(BufferedImage originalImage); } | @Test(expected = IIOException.class) public void testResizeNullImage() throws Exception { cut.resize((BufferedImage) null); } |
OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getByHash(long hash) throws RepositoryException { try { return imageDao.queryForMatching(new ImageRecord(null, hash)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | @Test public void testGetByHashNotFound() throws Exception { assertThat(cut.getByHash(HASH_NEW_RECORD), hasSize(0)); }
@Test public void testGetByHashExists() throws Exception { assertThat(cut.getByHash(HASH_EXISTING_RECORD), containsInAnyOrder(imageExisting)); } |
OrmliteImageRepository implements ImageRepository { @Override public ImageRecord getByPath(Path path) throws RepositoryException { try { return imageDao.queryForId(path.toString()); } catch (SQLException e) { throw new RepositoryException("Failed to query for path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | @Test public void testGetByPathExists() throws Exception { assertThat(cut.getByPath(Paths.get(pathExisting)), is(imageExisting)); }
@Test public void testGetByPathNotFound() throws Exception { assertThat(cut.getByPath(Paths.get(pathNew)), is(nullValue())); } |
OrmliteImageRepository implements ImageRepository { @Override public synchronized List<ImageRecord> startsWithPath(Path directory) throws RepositoryException { argStartsWithPath.setValue(directory.toString() + STRING_QUERY_WILDCARD); try { return imageDao.query(queryStartsWithPath); } catch (SQLException e) { throw new RepositoryException("Failed to query for starts with path", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | @Test public void testStartsWithPath() throws Exception { assertThat(cut.startsWithPath(Paths.get("exi")), containsInAnyOrder(imageExisting)); } |
OrmliteImageRepository implements ImageRepository { @Override public void remove(ImageRecord image) throws RepositoryException { try { imageDao.delete(image); } catch (SQLException e) { throw new RepositoryException("Failed to remove image", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | @Test public void testRemoveImageRecord() throws Exception { cut.remove(imageExisting); assertThat(imageDao.queryForMatching(imageExisting), hasSize(0)); }
@Test public void testRemoveImageRecordCollection() throws Exception { imageDao.create(imageNew); List<ImageRecord> toRemove = new LinkedList<ImageRecord>(); toRemove.add(imageExisting); toRemove.add(imageNew); assertThat(imageDao.queryForAll(), hasSize(2)); cut.remove(toRemove); assertThat(imageDao.queryForMatching(imageExisting), hasSize(0)); } |
OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAll() throws RepositoryException { try { return imageDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | @Test public void testGetAll() throws Exception { imageDao.create(imageNew); assertThat(cut.getAll(), containsInAnyOrder(imageExisting, imageNew)); } |
OrmliteImageRepository implements ImageRepository { @Override public List<ImageRecord> getAllWithoutIgnored() throws RepositoryException { try { return imageDao.query(queryNotIgnored); } catch (SQLException e) { throw new RepositoryException("Failed to query for non-ignored", e); } } OrmliteImageRepository(Dao<ImageRecord, String> imageDao, Dao<IgnoreRecord, String> ignoreDao); @Override void store(ImageRecord image); @Override List<ImageRecord> getByHash(long hash); @Override ImageRecord getByPath(Path path); @Override synchronized List<ImageRecord> startsWithPath(Path directory); @Override void remove(ImageRecord image); @Override void remove(Collection<ImageRecord> images); @Override List<ImageRecord> getAll(); @Override List<ImageRecord> getAllWithoutIgnored(); @Override List<ImageRecord> getAllWithoutIgnored(Path directory); } | @Test public void testGetAllWithoutIgnored() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(); assertThat(result, hasItem(imageNew)); assertThat(result, hasSize(1)); }
@Test public void testGetAllWithoutIgnoredPath() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(Paths.get(pathNew)); assertThat(result, hasItem(imageNew)); assertThat(result, hasSize(1)); }
@Test public void testGetAllWithoutIgnoredPathNoMatch() throws Exception { imageDao.create(imageNew); List<ImageRecord> result = cut.getAllWithoutIgnored(Paths.get(pathExisting)); assertThat(result, is(empty())); } |
ExtendedAttribute implements ExtendedAttributeQuery { public static void setExtendedAttribute(Path path, String name, String value) throws IOException { setExtendedAttribute(path, name, StandardCharsets.US_ASCII.encode(value)); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } | @Test public void testSetExtendedAttributePathStringString() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, TEST_NAME, TEST_VALUE); } |
OrmliteTagRepository implements TagRepository { @Override public synchronized Tag getByName(String name) throws RepositoryException { try { nameArg.setValue(name); return tagDao.queryForFirst(nameQuery); } catch (SQLException e) { throw new RepositoryException("Failed to query by name", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | @Test public void testGetByName() throws Exception { Tag result = cut.getByName(TAG_EXSTING); assertThat(result, is(tagExsting)); } |
OrmliteTagRepository implements TagRepository { @Override public void store(Tag tag) throws RepositoryException { try { tagDao.createOrUpdate(tag); } catch (SQLException e) { throw new RepositoryException("Failed to store", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | @Test public void testStore() throws Exception { cut.store(tagNew); Tag result = cut.getByName(TAG_NEW); assertThat(result, is(tagNew)); }
@Test(expected = RepositoryException.class) public void testStoreDuplicate() throws Exception { cut.store(tagNew); cut.store(new Tag(TAG_NEW)); } |
OrmliteTagRepository implements TagRepository { @Override public void remove(Tag tag) throws RepositoryException { try { tagDao.delete(tag); } catch (SQLException e) { throw new RepositoryException("Failed to delete", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | @Test public void testRemove() throws Exception { cut.remove(tagExsting); Tag result = cut.getByName(TAG_EXSTING); assertThat(result, is(nullValue())); } |
OrmliteTagRepository implements TagRepository { @Override public List<Tag> getAll() throws RepositoryException { try { return tagDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query all", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | @Test public void testGetAll() throws Exception { List<Tag> results = cut.getAll(); assertThat(results, containsInAnyOrder(tagContext, tagExsting)); } |
OrmliteTagRepository implements TagRepository { @Override public List<Tag> getWithContext() throws RepositoryException { try { return tagDao.queryForMatching(new Tag(null, true)); } catch (SQLException e) { throw new RepositoryException("Failed to query by context flag", e); } } OrmliteTagRepository(Dao<Tag, Long> tagDao); @Override synchronized Tag getByName(String name); @Override void store(Tag tag); @Override void remove(Tag tag); @Override List<Tag> getAll(); @Override List<Tag> getWithContext(); } | @Test public void testGetWithContext() throws Exception { List<Tag> results = cut.getWithContext(); assertThat(results, containsInAnyOrder(tagContext)); } |
OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByHash(long hash) throws RepositoryException { try { return filterDao.queryForMatching(new FilterRecord(hash, null, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by hash", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | @Test public void testGetByHash() throws Exception { List<FilterRecord> filters = cut.getByHash(HASH_TWO); assertThat(filters, containsInAnyOrder(new FilterRecord(HASH_TWO, TAG_TWO, null))); }
@Test(expected = RepositoryException.class) public void testGetByHashException() throws Exception { deleteFilterTable(); cut.getByHash(HASH_TWO); } |
OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getByTag(Tag tag) throws RepositoryException { try { return filterDao.queryForMatchingArgs(new FilterRecord(0, tag, null)); } catch (SQLException e) { throw new RepositoryException("Failed to query by tag", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | @Test public void testGetByTag() throws Exception { List<FilterRecord> filters = cut.getByTag(TAG_ONE); assertThat(filters, containsInAnyOrder(new FilterRecord(HASH_ONE, TAG_ONE, null))); }
@Test(expected = RepositoryException.class) public void testGetByTagException() throws Exception { deleteFilterTable(); cut.getByTag(TAG_ONE); } |
ExtendedAttribute implements ExtendedAttributeQuery { public static String readExtendedAttributeAsString(Path path, String name) throws IOException { ByteBuffer buffer = readExtendedAttribute(path, name); return StandardCharsets.US_ASCII.decode(buffer).toString(); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } | @Test public void testReadExtendedAttributeAsString() throws Exception { ExtendedAttribute.setExtendedAttribute(tempFile, TEST_NAME, TEST_VALUE); assertThat(ExtendedAttribute.readExtendedAttributeAsString(tempFile, TEST_NAME), is(TEST_VALUE)); } |
OrmliteFilterRepository implements FilterRepository { @Override public List<FilterRecord> getAll() throws RepositoryException { try { return filterDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to get all filters", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | @Test public void testGetAll() throws Exception { List<FilterRecord> filters = cut.getAll(); assertThat(filters, containsInAnyOrder(allFilters.toArray(new FilterRecord[0]))); }
@Test(expected = RepositoryException.class) public void testGetAllException() throws Exception { deleteFilterTable(); cut.getAll(); } |
OrmliteFilterRepository implements FilterRepository { @Override public void store(FilterRecord toStore) throws RepositoryException { if (toStore.hasThumbnail()) { checkAndCreateThumbnail(toStore); } try { if (filterDao.queryForMatchingArgs(toStore).isEmpty()) { filterDao.create(toStore); } } catch (SQLException e) { throw new RepositoryException(STORE_FILTER_ERROR_MSG, e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | @Test(expected = RepositoryException.class) public void testStoreThumbnailException() throws Exception { TableUtils.dropTable(cs, Thumbnail.class, false); cut.store(new FilterRecord(HASH_NEW_THUMBNAIL, TAG_ONE, newThumbnail)); }
@Test(expected = RepositoryException.class) public void testStoreFilterException() throws Exception { TableUtils.dropTable(cs, FilterRecord.class, false); cut.store(new FilterRecord(HASH_NEW_THUMBNAIL, TAG_ONE, null)); } |
OrmliteFilterRepository implements FilterRepository { @Override public void remove(FilterRecord filter) throws RepositoryException { try { filterDao.delete(filter); } catch (SQLException e) { throw new RepositoryException("Failed to remove Filter", e); } } OrmliteFilterRepository(Dao<FilterRecord, Integer> filterDao, Dao<Thumbnail, Integer> thumbnailDao); @Override List<FilterRecord> getByHash(long hash); @Override List<FilterRecord> getByTag(Tag tag); @Override List<FilterRecord> getAll(); @Override void store(FilterRecord toStore); @Override void remove(FilterRecord filter); } | @Test public void testRemove() throws Exception { FilterRecord toRemove = allFilters.get(0); cut.remove(toRemove); assertThat(cut.getAll(), not(hasItem(toRemove))); } |
OrmliteIgnoreRepository implements IgnoreRepository { @Override public void store(IgnoreRecord toStore) throws RepositoryException { try { ignoreDao.createIfNotExists(toStore); } catch (SQLException e) { throw new RepositoryException("Failed to store ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | @Test public void testStoreNew() throws Exception { cut.store(newIgnore); assertThat(dao.queryForAll(), hasItem(newIgnore)); }
@Test public void testStoreDuplicate() throws Exception { cut.store(existingIgnore); assertThat(dao.queryForAll(), hasSize(1)); }
@Test public void testStoreNewSize() throws Exception { cut.store(newIgnore); assertThat(dao.queryForAll(), hasSize(2)); } |
OrmliteIgnoreRepository implements IgnoreRepository { @Override public void remove(IgnoreRecord toRemove) throws RepositoryException { try { ignoreDao.delete(toRemove); } catch (SQLException e) { throw new RepositoryException("Failed to delete ignore", e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | @Test public void testRemove() throws Exception { cut.remove(existingIgnore); assertThat(dao.queryForAll(), not(hasItem(existingIgnore))); }
@Test public void testRemoveSize() throws Exception { cut.remove(existingIgnore); assertThat(dao.queryForAll(), is(empty())); } |
ExtendedAttribute implements ExtendedAttributeQuery { public static boolean isExtendedAttributeSet(Path path, String name) throws IOException { return createUserDefinedFileAttributeView(path).list().contains(name); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } | @Test public void testExtendedAttributeIsNotSet() throws Exception { assertThat(ExtendedAttribute.isExtendedAttributeSet(tempFile, TEST_NAME), is(false)); } |
OrmliteIgnoreRepository implements IgnoreRepository { @Override public IgnoreRecord findByPath(Path path) throws RepositoryException { return findByPath(path.toString()); } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | @Test public void testFindByPathPath() throws Exception { assertThat(cut.findByPath(toPath(PATH_A)), is(existingIgnore)); }
@Test public void testFindByPathPathNotFound() throws Exception { assertThat(cut.findByPath(toPath(PATH_B)), is(nullValue())); }
@Test public void testFindByPathString() throws Exception { assertThat(cut.findByPath(PATH_A), is(existingIgnore)); } |
OrmliteIgnoreRepository implements IgnoreRepository { @Override public boolean isPathIgnored(String path) throws RepositoryException { return findByPath(path) != null; } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | @Test public void testFindByPathStringNotFound() throws Exception { assertThat(cut.isPathIgnored(PATH_B), is(false)); }
@Test public void testIsPathIgnoredString() throws Exception { assertThat(cut.isPathIgnored(PATH_A), is(true)); }
@Test public void testIsPathIgnoredStringNope() throws Exception { assertThat(cut.isPathIgnored(PATH_B), is(false)); }
@Test public void testIsPathIgnoredPath() throws Exception { assertThat(cut.isPathIgnored(toPath(PATH_A)), is(true)); } |
OrmliteIgnoreRepository implements IgnoreRepository { @Override public List<IgnoreRecord> getAll() throws RepositoryException { try { return ignoreDao.queryForAll(); } catch (SQLException e) { throw new RepositoryException("Failed to query for all ingored images: " + e.toString(), e); } } OrmliteIgnoreRepository(Dao<IgnoreRecord, String> ignoreDao); @Override void store(IgnoreRecord toStore); @Override void remove(IgnoreRecord toRemove); @Override IgnoreRecord findByPath(Path path); @Override IgnoreRecord findByPath(String path); @Override boolean isPathIgnored(String path); @Override boolean isPathIgnored(Path path); @Override List<IgnoreRecord> getAll(); } | @Test public void testGetAll() throws Exception { dao.create(newIgnore); assertThat(cut.getAll(), containsInAnyOrder(newIgnore, existingIgnore)); } |
Tag { @Override public final boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Tag)) { return false; } Tag other = (Tag) obj; if (contextMenu != other.contextMenu) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } return true; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } | @Test public void testEquals() throws Exception { EqualsVerifier.forClass(Tag.class).withIgnoredFields("userTagId") .suppress(Warning.NONFINAL_FIELDS).verify();; } |
Tag { public final String getTag() { return tag; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } | @Test public void testTagStringName() throws Exception { assertThat(cut.getTag(), is(TEST_TAG)); } |
ExtendedAttribute implements ExtendedAttributeQuery { public static String createName(String... names) { StringBuilder sb = new StringBuilder(SIMILARIMAGE_NAMESPACE); for (String name : names) { sb.append("."); sb.append(name); } return sb.toString(); } static String createName(String... names); static boolean supportsExtendedAttributes(Path path); static void deleteExtendedAttribute(Path path, String name); static void setExtendedAttribute(Path path, String name, String value); static void setExtendedAttribute(Path path, String name, ByteBuffer value); static ByteBuffer readExtendedAttribute(Path path, String name); static String readExtendedAttributeAsString(Path path, String name); static boolean isExtendedAttributeSet(Path path, String name); @Override boolean isEaSupported(Path path); static final String SIMILARIMAGE_NAMESPACE; } | @Test public void testCreateName() throws Exception { assertThat(ExtendedAttribute.createName("foo", "bar"), is(ExtendedAttribute.SIMILARIMAGE_NAMESPACE + ".foo.bar")); } |
Tag { public final boolean isContextMenu() { return contextMenu; } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } | @Test public void testTagStringContextMenu() throws Exception { assertThat(cut.isContextMenu(), is(false)); } |
Tag { public boolean isMatchAll() { return StringUtil.MATCH_ALL_TAGS.equals(tag); } @Deprecated Tag(); Tag(String tag); Tag(String tag, boolean contextMenu); final String getTag(); final void setTag(String tag); final boolean isContextMenu(); boolean isMatchAll(); final void setContextMenu(boolean contextMenu); @Override String toString(); @Override final int hashCode(); @Override final boolean equals(Object obj); static final String NAME_FIELD_NAME; } | @Test public void testIsMatchAll() throws Exception { assertThat(cut.isMatchAll(), is(false)); }
@Test public void testIsMatchAllAsterisk() throws Exception { cut = new Tag(StringUtil.MATCH_ALL_TAGS); assertThat(cut.isMatchAll(), is(true)); } |
SQLiteDatabase implements Database { @Override public ConnectionSource getCs() { return connectionSource; } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); } | @Test public void testGetCs() throws Exception { assertThat(cut.getCs().isOpen(EMPTY_STRING), is(true)); } |
SQLiteDatabase implements Database { @Override public void close() { connectionSource.closeQuietly(); } SQLiteDatabase(); SQLiteDatabase(Path dbPath); SQLiteDatabase(String dbPath); @Override ConnectionSource getCs(); @Override void close(); } | @Ignore("Closing a closed connection when using pooled connections results in NPE") @Test public void testClose() throws Exception { ConnectionSource cs = cut.getCs(); assertThat(cs.isOpen(EMPTY_STRING), is(true)); cut.close(); assertThat(cs.isOpen(EMPTY_STRING), is(false)); } |
FilterRecord { public long getpHash() { return pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | @Test public void testGetpHash() throws Exception { assertThat(filterRecord.getpHash(), is(HASH_ONE)); } |
FilterRecord { public void setpHash(long pHash) { this.pHash = pHash; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | @Test public void testSetpHash() throws Exception { assertThat(GUARD_MSG, filterRecord.getpHash(), is(HASH_ONE)); filterRecord.setpHash(HASH_TWO); assertThat(filterRecord.getpHash(), is(HASH_TWO)); } |
FilterRecord { public Tag getTag() { return tag; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | @Test public void testGetReason() throws Exception { assertThat(filterRecord.getTag(), is(TEST_TAG_ONE)); } |
FilterRecord { @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } FilterRecord other = (FilterRecord) obj; if (pHash != other.pHash) { return false; } if (tag == null) { if (other.tag != null) { return false; } } else if (!tag.equals(other.tag)) { return false; } if (thumbnail == null) { if (other.thumbnail != null) { return false; } } else if (!thumbnail.equals(other.thumbnail)) { return false; } return true; } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | @Test public void testEqualsIsEqual() throws Exception { FilterRecord other = new FilterRecord(HASH_ONE, TEST_TAG_ONE, null); assertThat(filterRecord.equals(other), is(true)); }
@Test public void testEquals() throws Exception { EqualsVerifier.forClass(FilterRecord.class).withIgnoredFields("id").suppress(Warning.NONFINAL_FIELDS).verify(); } |
ExtendedAttributeDirectoryCache implements ExtendedAttributeQuery { @Override public boolean isEaSupported(Path path) { Path parent = path.getParent(); if (path.getRoot() != null && path.equals(path.getRoot())) { parent = path; } if (parent == null) { return false; } return eaSupport.getUnchecked(parent); } @Inject ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery); ExtendedAttributeDirectoryCache(ExtendedAttributeQuery eaQuery, int expireTime, TimeUnit expireUnit); @Override boolean isEaSupported(Path path); } | @Test public void testIsEaSupportedUseCache() throws Exception { assertThat(cut.isEaSupported(subDirectory), is(true)); when(eaQuery.isEaSupported(any(Path.class))).thenReturn(false); assertThat(cut.isEaSupported(subDirectory), is(true)); }
@Test public void testIsEaSupportedExpireCache() throws Exception { cut = new ExtendedAttributeDirectoryCache(eaQuery, 1, TimeUnit.MICROSECONDS); assertThat(cut.isEaSupported(subDirectory), is(true)); when(eaQuery.isEaSupported(any(Path.class))).thenReturn(false); assertThat(cut.isEaSupported(subDirectory), is(false)); }
@Test public void testIsEaSupportedRootParent() throws Exception { assertThat(cut.isEaSupported(rootDirectory), is(true)); }
@Test public void testIsEaSupportedRoot() throws Exception { assertThat(cut.isEaSupported(root), is(true)); }
@Test public void testIsEaSupportedNoParent() throws Exception { assertThat(cut.isEaSupported(relative), is(false)); } |
FilterRecord { public static List<FilterRecord> getTags(FilterRepository repository, Tag tag) throws RepositoryException { if (tag.isMatchAll()) { return repository.getAll(); } else { return repository.getByTag(tag); } } @Deprecated FilterRecord(); FilterRecord(long hash, Tag tag); FilterRecord(long pHash, Tag tag, Thumbnail thumbnail); long getpHash(); void setpHash(long pHash); Tag getTag(); void setTag(Tag tag); Thumbnail getThumbnail(); final void setThumbnail(Thumbnail thumbnail); boolean hasThumbnail(); @Override int hashCode(); @Override boolean equals(Object obj); static List<FilterRecord> getTags(FilterRepository repository, Tag tag); } | @Test public void testGetTags() throws Exception { FilterRecord.getTags(filterRepository, TEST_TAG_ONE); verify(filterRepository).getByTag(TEST_TAG_ONE); }
@Test public void testGetTagsAllTags() throws Exception { FilterRecord.getTags(filterRepository, new Tag(StringUtil.MATCH_ALL_TAGS)); verify(filterRepository).getAll(); } |
IgnoreRecord { public ImageRecord getImage() { return image; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static final String IMAGEPATH_FIELD_NAME; } | @Test public void testGetPathAsString() throws Exception { assertThat(cut.getImage(), is(IMAGE)); } |
IgnoreRecord { @Override public boolean equals(Object obj) { if (obj instanceof IgnoreRecord) { IgnoreRecord other = (IgnoreRecord) obj; return Objects.equals(this.image, other.image); } return false; } @Deprecated IgnoreRecord(); IgnoreRecord(ImageRecord image); ImageRecord getImage(); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); static final String IMAGEPATH_FIELD_NAME; } | @Test public void testEquals() throws Exception { assertThat(cut.equals(new IgnoreRecord(IMAGE)), is(true)); } |
MainSettingValidator { public static void validate(MainSetting mainSetting) throws IllegalArgumentException { if (mainSetting.threads() < 1) { throw new IllegalArgumentException("Thread number must be greater than zero"); } } private MainSettingValidator(); static void validate(MainSetting mainSetting); } | @Test public void testValidatePositiveThread() throws Exception { MainSettingValidator.validate(mainSetting); }
@Test(expected = IllegalArgumentException.class) public void testValidateZeroThread() throws Exception { when(mainSetting.threads()).thenReturn(0); MainSettingValidator.validate(mainSetting); }
@Test(expected = IllegalArgumentException.class) public void testValidateNegativeThread() throws Exception { when(mainSetting.threads()).thenReturn(-1); MainSettingValidator.validate(mainSetting); } |
HashingHandler implements HashHandler { @Override public boolean handle(Path file) { LOGGER.trace("Handling {} with {}", file, HashingHandler.class.getSimpleName()); ImageHashJob job = new ImageHashJob(file, hasher, imageRepository, statistics); job.setHashAttribute(hashAttribute); threadPool.execute(job); return true; } HashingHandler(ExecutorService threadPool, ImagePHash hasher, ImageRepository imageRepository,
Statistics statistics, HashAttribute hashAttribute); @Override boolean handle(Path file); } | @Test public void testHandleAlwaysTrue() throws Exception { assertThat(cut.handle(testPath), is(true)); }
@Test public void testHandleJobIsExecuted() throws Exception { cut.handle(testPath); verify(threadPool).execute(any(ImageHashJob.class)); } |
ExtendedAttributeHandler implements HashHandler { @Override public boolean handle(Path file) { LOGGER.trace("Handling {} with {}", file, ExtendedAttributeHandler.class.getSimpleName()); if (eaQuery.isEaSupported(file)) { try { if (ExtendedAttribute.isExtendedAttributeSet(file, CORRUPT_EA_NAMESPACE)) { LOGGER.trace("{} is corrupt", file); return true; } } catch (IOException e1) { LOGGER.error("Failed to read attributes from {}", file); } if (hashAttribute.areAttributesValid(file)) { LOGGER.trace("{} has valid extended attributes", file); try { imageRepository.store(new ImageRecord(file.toString(), hashAttribute.readHash(file))); LOGGER.trace("Successfully read and stored the hash for {}", file); return true; } catch (InvalidAttributeValueException | IOException e) { LOGGER.error("Failed to read extended attribute from {} ({})", file, e.toString()); } catch (RepositoryException e) { LOGGER.error("Failed to access database for {} ({})", file, e.toString()); } } } return false; } ExtendedAttributeHandler(HashAttribute hashAttribute, ImageRepository imageRepository,
ExtendedAttributeQuery eaQuery); @Override boolean handle(Path file); static final String CORRUPT_EA_NAMESPACE; } | @Test public void testHandleFileHasHash() throws Exception { assertThat(cut.handle(testFile), is(true)); }
@Test public void testHandleFileHasNoHash() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); assertThat(cut.handle(testFile), is(false)); }
@Test public void testHandleDbError() throws Exception { Mockito.doThrow(RepositoryException.class).when(imageRepository).store(any(ImageRecord.class)); assertThat(cut.handle(testFile), is(false)); }
@Test public void testHandleFileReadError() throws Exception { when(hashAttribute.readHash(testFile)).thenThrow(new IOException()); assertThat(cut.handle(testFile), is(false)); }
@Test public void testHandleAttributeError() throws Exception { when(hashAttribute.readHash(testFile)).thenThrow(new InvalidAttributeValueException()); assertThat(cut.handle(testFile), is(false)); }
@Test public void testHandleCorruptFileIsHandled() throws Exception { when(eaQuery.isEaSupported(testFile)).thenReturn(true); when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); ExtendedAttribute.setExtendedAttribute(testFile, ExtendedAttributeHandler.CORRUPT_EA_NAMESPACE, ""); assertThat(cut.handle(testFile), is(true)); } |
DatabaseHandler implements HashHandler { @Override public boolean handle(Path file) { LOGGER.trace("Handling {} with {}", file, ExtendedAttributeHandler.class.getSimpleName()); try { if (isInDatabase(file)) { LOGGER.trace("{} was found in the database"); statistics.incrementSkippedFiles(); statistics.incrementProcessedFiles(); return true; } } catch (RepositoryException e) { LOGGER.error("Failed to check the database for {} ({})", file, e.toString()); } return false; } DatabaseHandler(ImageRepository imageRepository, Statistics statistics); @Override boolean handle(Path file); } | @Test public void testHandleFileFoundGood() throws Exception { when(imageRepository.getByPath(testFile)).thenReturn(existingImage); assertThat(cut.handle(testFile), is(true)); }
@Test public void testHandleFileNotFound() throws Exception { assertThat(cut.handle(testFile), is(false)); }
@Test public void testHandleDatabaseError() throws Exception { when(imageRepository.getByPath(testFile)).thenThrow(new RepositoryException("test")); assertThat(cut.handle(testFile), is(false)); } |
ExtendedAttributeUpdateHandler implements HashHandler { @Override public boolean handle(Path file) { if (!hashAttribute.areAttributesValid(file)) { try { long hash = hasher.getLongHash(Files.newInputStream(file)); hashAttribute.writeHash(file, hash); } catch (IOException e) { LOGGER.warn("Failed to hash {}, {}", file, e.toString()); return false; } } return true; } ExtendedAttributeUpdateHandler(HashAttribute hashAttribute, ImagePHash hasher); @Override boolean handle(Path file); } | @Test public void testHandleValidExtendedAttribute() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(true); assertThat(cut.handle(testFile), is(true)); }
@Test public void testHandleInvalidExtendedAttribute() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); assertThat(cut.handle(testFile), is(true)); }
@Test public void testHandleIOError() throws Exception { when(hashAttribute.areAttributesValid(testFile)).thenReturn(false); when(hasher.getLongHash(any(InputStream.class))).thenThrow(new IOException()); assertThat(cut.handle(testFile), is(false)); } |
IgnoredImageQueryStage implements Function<Path, List<ImageRecord>> { @Override public List<ImageRecord> apply(Path path) { List<ImageRecord> result = Collections.emptyList(); try { if (path == null || Paths.get("").equals(path)) { result = imageRepository.getAllWithoutIgnored(); } else { result = imageRepository.getAllWithoutIgnored(path); } } catch (RepositoryException e) { LOGGER.error("Failed to query non-ignored images: {}, cause: {}", e.toString(), e.getCause()); } return result; } IgnoredImageQueryStage(ImageRepository imageRepository); @Override List<ImageRecord> apply(Path path); } | @Test public void testQueryForNull() throws Exception { cut.apply(null); verify(imageRepository).getAllWithoutIgnored(); }
@Test public void testQueryForEmpty() throws Exception { cut.apply(Paths.get("")); verify(imageRepository).getAllWithoutIgnored(); }
@Test public void testQueryForPath() throws Exception { cut.apply(PATH); verify(imageRepository).getAllWithoutIgnored(PATH); }
@Test public void testRepositoryError() throws Exception { when(imageRepository.getAllWithoutIgnored()).thenThrow(new RepositoryException("")); assertThat(cut.apply(null), is(empty())); } |
ImageQueryStage implements Function<Path, List<ImageRecord>> { @Override public List<ImageRecord> apply(Path path) { List<ImageRecord> result = Collections.emptyList(); try { if (path == null || Paths.get("").equals(path)) { result = imageRepository.getAll(); } else { result = imageRepository.startsWithPath(path); } } catch (RepositoryException e) { LOGGER.error("Failed to query images: {}, cause: {}", e.toString(), e.getCause()); } return result; } ImageQueryStage(ImageRepository imageRepository); @Override List<ImageRecord> apply(Path path); } | @Test public void testQueryForNull() throws Exception { cut.apply(null); verify(imageRepository).getAll(); }
@Test public void testQueryForEmpty() throws Exception { cut.apply(Paths.get("")); verify(imageRepository).getAll(); }
@Test public void testQueryForPath() throws Exception { cut.apply(PATH); verify(imageRepository).startsWithPath(PATH); }
@Test public void testRepositoryError() throws Exception { when(imageRepository.getAll()).thenThrow(new RepositoryException("")); assertThat(cut.apply(null), is(empty())); } |
ImageQueryPipeline implements Function<Path, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Path path) { List<ImageRecord> images = imageQueryStage.apply(path); Multimap<Long, ImageRecord> groups = imageGrouper.apply(images); return postProcessing(groups); } ImageQueryPipeline(Function<Path, List<ImageRecord>> imageQueryStage,
Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> imageGrouper,
Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> postProcessingStages); @Override Multimap<Long, ImageRecord> apply(Path path); Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages(); Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper(); } | @Test public void testQueryExecuted() throws Exception { verify(imageQueryStage).apply(any()); }
@Test public void testGroupingExecuted() throws Exception { verify(grouper).apply(images); }
@Test public void testPostprocessingAExecuted() throws Exception { verify(postProcessingStageA).apply(groups); }
@Test public void testPostprocessingBExecuted() throws Exception { verify(postProcessingStageB).apply(groups); }
@Test public void testPipelineReturnsGroups() throws Exception { assertThat(cut.apply(null), is(groups)); } |
ImageQueryPipeline implements Function<Path, Multimap<Long, ImageRecord>> { public Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper() { return imageGrouper; } ImageQueryPipeline(Function<Path, List<ImageRecord>> imageQueryStage,
Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> imageGrouper,
Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> postProcessingStages); @Override Multimap<Long, ImageRecord> apply(Path path); Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages(); Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper(); } | @Test public void testGrouperInstance() throws Exception { assertThat(cut.getImageGrouper(), is(instanceOf(GroupImagesStage.class))); } |
ImageQueryPipeline implements Function<Path, Multimap<Long, ImageRecord>> { public Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages() { return ImmutableList.copyOf(postProcessingStages); } ImageQueryPipeline(Function<Path, List<ImageRecord>> imageQueryStage,
Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> imageGrouper,
Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> postProcessingStages); @Override Multimap<Long, ImageRecord> apply(Path path); Collection<Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>>> getPostProcessingStages(); Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> getImageGrouper(); } | @Test public void testGetPostProcessingStages() throws Exception { assertThat(cut.getPostProcessingStages(), hasSize(2)); } |
GroupByTagStage implements Function<Collection<ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Collection<ImageRecord> t) { Multimap<Long, ImageRecord> result = MultimapBuilder.hashKeys().hashSetValues().build(); rs.build(t); TagFilter tagFilter = new TagFilter(filterRepository); result = tagFilter.getFilterMatches(rs, tag, hammingDistance); return result; } GroupByTagStage(FilterRepository filterRepository, Tag tag, int hammingDistance); GroupByTagStage(FilterRepository filterRepository, Tag tag); @Override Multimap<Long, ImageRecord> apply(Collection<ImageRecord> t); } | @Test public void testGroupedByTag() throws Exception { assertThat(cut.apply(images).get(HASH_A), containsInAnyOrder(imageA)); }
@Test public void testTagsWithDistance() throws Exception { cut = new GroupByTagStage(filterRepository, TAG, 1); assertThat(cut.apply(images).get(HASH_A), containsInAnyOrder(imageA, imageB)); }
@Test public void testRepositoryError() throws Exception { when(filterRepository.getByTag(TAG)).thenThrow(new RepositoryException("")); assertThat(cut.apply(images), is(EMPTY_MAP)); } |
ImageQueryPipelineBuilder { public ImageQueryPipeline build() { if (imageGrouper == null) { imageGrouper = new GroupImagesStage(hammingDistance); LOGGER.warn("No image group stage set, using {}", imageGrouper.getClass().getSimpleName()); } return new ImageQueryPipeline(imageQuery, imageGrouper, postProcessing); } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository,
FilterRepository filterRepository); } | @Test public void testImagesWithIgnore() throws Exception { cut.build().apply(null); verify(imageRepository).getAll(); } |
ImageQueryPipelineBuilder { public ImageQueryPipelineBuilder removeSingleImageGroups() { this.postProcessing.add(new RemoveSingleImageSetStage()); return this; } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository,
FilterRepository filterRepository); } | @Test public void testRemoveSingleImageGroups() throws Exception { assertThat(cut.removeSingleImageGroups().build().getPostProcessingStages(), hasItem(instanceOf(RemoveSingleImageSetStage.class))); } |
ImageQueryPipelineBuilder { public ImageQueryPipelineBuilder removeDuplicateGroups() { this.postProcessing.add(new RemoveDuplicateSetStage()); return this; } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository,
FilterRepository filterRepository); } | @Test public void testRemoveDuplicateGroups() throws Exception { assertThat(cut.removeDuplicateGroups().build().getPostProcessingStages(), hasItem(instanceOf(RemoveDuplicateSetStage.class))); } |
ImageQueryPipelineBuilder { public static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository, FilterRepository filterRepository) { return new ImageQueryPipelineBuilder(imageRepository, filterRepository); } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository,
FilterRepository filterRepository); } | @Test public void testNewBuilder() throws Exception { assertThat(ImageQueryPipelineBuilder.newBuilder(imageRepository, filterRepository), is(instanceOf(ImageQueryPipelineBuilder.class))); } |
ImageQueryPipelineBuilder { public ImageQueryPipelineBuilder groupAll() { this.imageGrouper = new GroupImagesStage(hammingDistance); return this; } ImageQueryPipelineBuilder(ImageRepository imageRepository, FilterRepository filterRepository); ImageQueryPipelineBuilder excludeIgnored(); ImageQueryPipelineBuilder excludeIgnored(boolean exclude); ImageQueryPipelineBuilder removeSingleImageGroups(); ImageQueryPipelineBuilder removeDuplicateGroups(); ImageQueryPipelineBuilder distance(int distance); ImageQueryPipelineBuilder groupByTag(Tag tag); ImageQueryPipelineBuilder groupAll(); ImageQueryPipeline build(); static ImageQueryPipelineBuilder newBuilder(ImageRepository imageRepository,
FilterRepository filterRepository); } | @Test public void testGroupAll() throws Exception { ImageQueryPipeline pipeline = cut.groupAll().build(); assertThat(pipeline.getImageGrouper(), is(instanceOf(GroupImagesStage.class))); } |
RemoveDuplicateSetStage implements Function<Multimap<Long, ImageRecord>, Multimap<Long, ImageRecord>> { @Override public Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune) { DuplicateUtil.removeDuplicateSets(toPrune); return toPrune; } @Override Multimap<Long, ImageRecord> apply(Multimap<Long, ImageRecord> toPrune); } | @Test public void testRemoveDuplicateGroups() throws Exception { cut.apply(testMap); assertThat(testMap.containsKey(HASH_C), is(false)); }
@Test public void testParameterReturned() throws Exception { assertThat(cut.apply(testMap), is(sameInstance(testMap))); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.