repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
davidmoten/grumpy
grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java
// Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double longitudeDiff(double a, double b) { // a = to180(a); // b = to180(b); // return Math.abs(to180(a - b)); // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double to180(double d) { // if (d < 0) // return -to180(abs(d)); // else { // if (d > 180) { // long n = round(floor((d + 180) / 360.0)); // return d - n * 360; // } else // return d; // } // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static class LongitudePair { // private final double lon1, lon2; // // public LongitudePair(double lon1, double lon2) { // this.lon1 = lon1; // this.lon2 = lon2; // } // // public double getLon1() { // return lon1; // } // // public double getLon2() { // return lon2; // } // // @Override // public String toString() { // return "LongitudePair [lon1=" + lon1 + ", lon2=" + lon2 + "]"; // } // // }
import static com.github.davidmoten.grumpy.core.Position.longitudeDiff; import static com.github.davidmoten.grumpy.core.Position.to180; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import com.github.davidmoten.grumpy.core.Position.LongitudePair;
Position p = new Position(-10, 110); assertTrue(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is on the region path. */ @Test public void testIsOutside3() { Position p = new Position(20.07030897931526, 24.999999999999996); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is within the region path. */ @Test public void testIsOutside4() { Position p = new Position(30, 30); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } @Test public void testTo180() {
// Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double longitudeDiff(double a, double b) { // a = to180(a); // b = to180(b); // return Math.abs(to180(a - b)); // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double to180(double d) { // if (d < 0) // return -to180(abs(d)); // else { // if (d > 180) { // long n = round(floor((d + 180) / 360.0)); // return d - n * 360; // } else // return d; // } // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static class LongitudePair { // private final double lon1, lon2; // // public LongitudePair(double lon1, double lon2) { // this.lon1 = lon1; // this.lon2 = lon2; // } // // public double getLon1() { // return lon1; // } // // public double getLon2() { // return lon2; // } // // @Override // public String toString() { // return "LongitudePair [lon1=" + lon1 + ", lon2=" + lon2 + "]"; // } // // } // Path: grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java import static com.github.davidmoten.grumpy.core.Position.longitudeDiff; import static com.github.davidmoten.grumpy.core.Position.to180; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import com.github.davidmoten.grumpy.core.Position.LongitudePair; Position p = new Position(-10, 110); assertTrue(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is on the region path. */ @Test public void testIsOutside3() { Position p = new Position(20.07030897931526, 24.999999999999996); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is within the region path. */ @Test public void testIsOutside4() { Position p = new Position(30, 30); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } @Test public void testTo180() {
assertEquals(0, to180(0), PRECISION);
davidmoten/grumpy
grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java
// Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double longitudeDiff(double a, double b) { // a = to180(a); // b = to180(b); // return Math.abs(to180(a - b)); // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double to180(double d) { // if (d < 0) // return -to180(abs(d)); // else { // if (d > 180) { // long n = round(floor((d + 180) / 360.0)); // return d - n * 360; // } else // return d; // } // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static class LongitudePair { // private final double lon1, lon2; // // public LongitudePair(double lon1, double lon2) { // this.lon1 = lon1; // this.lon2 = lon2; // } // // public double getLon1() { // return lon1; // } // // public double getLon2() { // return lon2; // } // // @Override // public String toString() { // return "LongitudePair [lon1=" + lon1 + ", lon2=" + lon2 + "]"; // } // // }
import static com.github.davidmoten.grumpy.core.Position.longitudeDiff; import static com.github.davidmoten.grumpy.core.Position.to180; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import com.github.davidmoten.grumpy.core.Position.LongitudePair;
Position p = new Position(20.07030897931526, 24.999999999999996); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is within the region path. */ @Test public void testIsOutside4() { Position p = new Position(30, 30); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } @Test public void testTo180() { assertEquals(0, to180(0), PRECISION); assertEquals(10, to180(10), PRECISION); assertEquals(-10, to180(-10), PRECISION); assertEquals(180, to180(180), PRECISION); assertEquals(-180, to180(-180), PRECISION); assertEquals(-170, to180(190), PRECISION); assertEquals(170, to180(-190), PRECISION); assertEquals(-170, to180(190 + 360), PRECISION); } @Test public void testLongitudeDiff() {
// Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double longitudeDiff(double a, double b) { // a = to180(a); // b = to180(b); // return Math.abs(to180(a - b)); // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double to180(double d) { // if (d < 0) // return -to180(abs(d)); // else { // if (d > 180) { // long n = round(floor((d + 180) / 360.0)); // return d - n * 360; // } else // return d; // } // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static class LongitudePair { // private final double lon1, lon2; // // public LongitudePair(double lon1, double lon2) { // this.lon1 = lon1; // this.lon2 = lon2; // } // // public double getLon1() { // return lon1; // } // // public double getLon2() { // return lon2; // } // // @Override // public String toString() { // return "LongitudePair [lon1=" + lon1 + ", lon2=" + lon2 + "]"; // } // // } // Path: grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java import static com.github.davidmoten.grumpy.core.Position.longitudeDiff; import static com.github.davidmoten.grumpy.core.Position.to180; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import com.github.davidmoten.grumpy.core.Position.LongitudePair; Position p = new Position(20.07030897931526, 24.999999999999996); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } /** * Test when a position is outside a given region consisting of several * joining points. In this test the region is a roughly square region * consisting of four segments or eight {@link Position}s. The test position * is within the region path. */ @Test public void testIsOutside4() { Position p = new Position(30, 30); assertFalse(p.isOutside(squareRegion, MIN_DISTANCE_KM)); } @Test public void testTo180() { assertEquals(0, to180(0), PRECISION); assertEquals(10, to180(10), PRECISION); assertEquals(-10, to180(-10), PRECISION); assertEquals(180, to180(180), PRECISION); assertEquals(-180, to180(-180), PRECISION); assertEquals(-170, to180(190), PRECISION); assertEquals(170, to180(-190), PRECISION); assertEquals(-170, to180(190 + 360), PRECISION); } @Test public void testLongitudeDiff() {
assertEquals(10, longitudeDiff(15, 5), PRECISION);
davidmoten/grumpy
grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java
// Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double longitudeDiff(double a, double b) { // a = to180(a); // b = to180(b); // return Math.abs(to180(a - b)); // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double to180(double d) { // if (d < 0) // return -to180(abs(d)); // else { // if (d > 180) { // long n = round(floor((d + 180) / 360.0)); // return d - n * 360; // } else // return d; // } // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static class LongitudePair { // private final double lon1, lon2; // // public LongitudePair(double lon1, double lon2) { // this.lon1 = lon1; // this.lon2 = lon2; // } // // public double getLon1() { // return lon1; // } // // public double getLon2() { // return lon2; // } // // @Override // public String toString() { // return "LongitudePair [lon1=" + lon1 + ", lon2=" + lon2 + "]"; // } // // }
import static com.github.davidmoten.grumpy.core.Position.longitudeDiff; import static com.github.davidmoten.grumpy.core.Position.to180; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import com.github.davidmoten.grumpy.core.Position.LongitudePair;
Position a = Position.create(0, 20); Position b = Position.create(0, 30); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, 25); assertEquals(0, halfwayLat, 0.1); } @Test public void testGetLatitudeOnGreatCircleFromLaxToJfk() { Position a = Position.create(33 + 57 / 60.0, -118 - 24 / 60.0); Position b = Position.create(40 + 38 / 60.0, -73 - 47 / 60.0); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, -111); assertEquals(36 + 24 / 60.0, halfwayLat, 0.1); } @Test public void testGetLatitudeOnGreatCircleForSmallSegment() { Position a = Position.create(-40, 100); Position b = Position.create(-40, 100.016); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, 100.008); assertEquals(-40, halfwayLat, 0.001); } @Test public void testGetLongitudeOnGreatCircleFromLaxToJfk() { Position a = Position.create(33 + 57 / 60.0, -118 - 24 / 60.0); Position b = Position.create(40 + 38 / 60.0, -73 - 47 / 60.0); System.out.println(a.getBearingDegrees(b));
// Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double longitudeDiff(double a, double b) { // a = to180(a); // b = to180(b); // return Math.abs(to180(a - b)); // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static double to180(double d) { // if (d < 0) // return -to180(abs(d)); // else { // if (d > 180) { // long n = round(floor((d + 180) / 360.0)); // return d - n * 360; // } else // return d; // } // } // // Path: grumpy-core/src/main/java/com/github/davidmoten/grumpy/core/Position.java // public static class LongitudePair { // private final double lon1, lon2; // // public LongitudePair(double lon1, double lon2) { // this.lon1 = lon1; // this.lon2 = lon2; // } // // public double getLon1() { // return lon1; // } // // public double getLon2() { // return lon2; // } // // @Override // public String toString() { // return "LongitudePair [lon1=" + lon1 + ", lon2=" + lon2 + "]"; // } // // } // Path: grumpy-core/src/test/java/com/github/davidmoten/grumpy/core/PositionTest.java import static com.github.davidmoten.grumpy.core.Position.longitudeDiff; import static com.github.davidmoten.grumpy.core.Position.to180; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; import com.github.davidmoten.grumpy.core.Position.LongitudePair; Position a = Position.create(0, 20); Position b = Position.create(0, 30); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, 25); assertEquals(0, halfwayLat, 0.1); } @Test public void testGetLatitudeOnGreatCircleFromLaxToJfk() { Position a = Position.create(33 + 57 / 60.0, -118 - 24 / 60.0); Position b = Position.create(40 + 38 / 60.0, -73 - 47 / 60.0); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, -111); assertEquals(36 + 24 / 60.0, halfwayLat, 0.1); } @Test public void testGetLatitudeOnGreatCircleForSmallSegment() { Position a = Position.create(-40, 100); Position b = Position.create(-40, 100.016); System.out.println(a.getBearingDegrees(b)); Double halfwayLat = a.getLatitudeOnGreatCircle(b, 100.008); assertEquals(-40, halfwayLat, 0.001); } @Test public void testGetLongitudeOnGreatCircleFromLaxToJfk() { Position a = Position.create(33 + 57 / 60.0, -118 - 24 / 60.0); Position b = Position.create(40 + 38 / 60.0, -73 - 47 / 60.0); System.out.println(a.getBearingDegrees(b));
LongitudePair candidates = a.getLongitudeOnGreatCircle(b, 36 + 23.65967428 / 60.0);
davidmoten/grumpy
grumpy-ogc/src/main/java/com/github/davidmoten/util/servlet/RequestUtil.java
// Path: grumpy-ogc/src/main/java/com/github/davidmoten/grumpy/wms/MissingMandatoryParameterException.java // public class MissingMandatoryParameterException extends Exception { // // private static final long serialVersionUID = -9206288232141856630L; // // public MissingMandatoryParameterException(String parameter) { // super(parameter + " is a mandatory parameter and was missing"); // } // // }
import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.github.davidmoten.grumpy.wms.MissingMandatoryParameterException;
package com.github.davidmoten.util.servlet; public class RequestUtil { private static final String COMMA = ","; public static List<String> getList(HttpServletRequest request, String parameter, boolean mandatory) { String[] items = new String[] {}; if (request.getParameter(parameter) != null) items = request.getParameter(parameter).split(COMMA); return Arrays.asList(items); } public static String getParameter(HttpServletRequest request, String parameter,
// Path: grumpy-ogc/src/main/java/com/github/davidmoten/grumpy/wms/MissingMandatoryParameterException.java // public class MissingMandatoryParameterException extends Exception { // // private static final long serialVersionUID = -9206288232141856630L; // // public MissingMandatoryParameterException(String parameter) { // super(parameter + " is a mandatory parameter and was missing"); // } // // } // Path: grumpy-ogc/src/main/java/com/github/davidmoten/util/servlet/RequestUtil.java import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.github.davidmoten.grumpy.wms.MissingMandatoryParameterException; package com.github.davidmoten.util.servlet; public class RequestUtil { private static final String COMMA = ","; public static List<String> getList(HttpServletRequest request, String parameter, boolean mandatory) { String[] items = new String[] {}; if (request.getParameter(parameter) != null) items = request.getParameter(parameter).split(COMMA); return Arrays.asList(items); } public static String getParameter(HttpServletRequest request, String parameter,
boolean mandatory) throws MissingMandatoryParameterException {
juiser/juiser
spring/spring-security/src/main/java/org/juiser/spring/security/authentication/JwsToUserDetailsConverter.java
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // } // // Path: spring/spring-security/src/main/java/org/juiser/spring/security/core/userdetails/ForwardedUserDetails.java // public class ForwardedUserDetails implements UserDetails { // // private final User user; // private final Collection<? extends GrantedAuthority> grantedAuthorities; // // public ForwardedUserDetails(User user, Collection<? extends GrantedAuthority> grantedAuthorities) { // Assert.notNull(user, "User argument cannot be null."); // Assert.hasText(user.getUsername(), "User username cannot be null or empty."); // this.user = user; // if (CollectionUtils.isEmpty(grantedAuthorities)) { // this.grantedAuthorities = java.util.Collections.emptyList(); // } else { // this.grantedAuthorities = java.util.Collections.unmodifiableCollection(grantedAuthorities); // } // } // // public User getUser() { // return this.user; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return this.grantedAuthorities; // } // // @Override // public String getPassword() { // return null; // } // // @Override // public String getUsername() { // return getUser().getUsername(); // } // // @Override // public boolean isAccountNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isAccountNonLocked() { // return true; //gateway will not forward locked accounts // } // // @Override // public boolean isCredentialsNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isEnabled() { // return true; //gateway will not forward disabled accounts // } // }
import org.juiser.model.User; import org.juiser.spring.security.core.userdetails.ForwardedUserDetails; import io.jsonwebtoken.Claims; import io.jsonwebtoken.lang.Assert; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.Collections; import java.util.function.Function;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.security.authentication; /** * @since 1.0.0 */ public class JwsToUserDetailsConverter implements Function<String, UserDetails> { private final Function<String, Claims> claimsExtractor;
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // } // // Path: spring/spring-security/src/main/java/org/juiser/spring/security/core/userdetails/ForwardedUserDetails.java // public class ForwardedUserDetails implements UserDetails { // // private final User user; // private final Collection<? extends GrantedAuthority> grantedAuthorities; // // public ForwardedUserDetails(User user, Collection<? extends GrantedAuthority> grantedAuthorities) { // Assert.notNull(user, "User argument cannot be null."); // Assert.hasText(user.getUsername(), "User username cannot be null or empty."); // this.user = user; // if (CollectionUtils.isEmpty(grantedAuthorities)) { // this.grantedAuthorities = java.util.Collections.emptyList(); // } else { // this.grantedAuthorities = java.util.Collections.unmodifiableCollection(grantedAuthorities); // } // } // // public User getUser() { // return this.user; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return this.grantedAuthorities; // } // // @Override // public String getPassword() { // return null; // } // // @Override // public String getUsername() { // return getUser().getUsername(); // } // // @Override // public boolean isAccountNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isAccountNonLocked() { // return true; //gateway will not forward locked accounts // } // // @Override // public boolean isCredentialsNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isEnabled() { // return true; //gateway will not forward disabled accounts // } // } // Path: spring/spring-security/src/main/java/org/juiser/spring/security/authentication/JwsToUserDetailsConverter.java import org.juiser.model.User; import org.juiser.spring.security.core.userdetails.ForwardedUserDetails; import io.jsonwebtoken.Claims; import io.jsonwebtoken.lang.Assert; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.Collections; import java.util.function.Function; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.security.authentication; /** * @since 1.0.0 */ public class JwsToUserDetailsConverter implements Function<String, UserDetails> { private final Function<String, Claims> claimsExtractor;
private final Function<Claims, User> claimsUserFactory;
juiser/juiser
spring/spring-security/src/main/java/org/juiser/spring/security/authentication/JwsToUserDetailsConverter.java
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // } // // Path: spring/spring-security/src/main/java/org/juiser/spring/security/core/userdetails/ForwardedUserDetails.java // public class ForwardedUserDetails implements UserDetails { // // private final User user; // private final Collection<? extends GrantedAuthority> grantedAuthorities; // // public ForwardedUserDetails(User user, Collection<? extends GrantedAuthority> grantedAuthorities) { // Assert.notNull(user, "User argument cannot be null."); // Assert.hasText(user.getUsername(), "User username cannot be null or empty."); // this.user = user; // if (CollectionUtils.isEmpty(grantedAuthorities)) { // this.grantedAuthorities = java.util.Collections.emptyList(); // } else { // this.grantedAuthorities = java.util.Collections.unmodifiableCollection(grantedAuthorities); // } // } // // public User getUser() { // return this.user; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return this.grantedAuthorities; // } // // @Override // public String getPassword() { // return null; // } // // @Override // public String getUsername() { // return getUser().getUsername(); // } // // @Override // public boolean isAccountNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isAccountNonLocked() { // return true; //gateway will not forward locked accounts // } // // @Override // public boolean isCredentialsNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isEnabled() { // return true; //gateway will not forward disabled accounts // } // }
import org.juiser.model.User; import org.juiser.spring.security.core.userdetails.ForwardedUserDetails; import io.jsonwebtoken.Claims; import io.jsonwebtoken.lang.Assert; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.Collections; import java.util.function.Function;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.security.authentication; /** * @since 1.0.0 */ public class JwsToUserDetailsConverter implements Function<String, UserDetails> { private final Function<String, Claims> claimsExtractor; private final Function<Claims, User> claimsUserFactory; private final Function<Claims, Collection<? extends GrantedAuthority>> authoritiesResolver; public JwsToUserDetailsConverter(Function<String, Claims> claimsExtractor, Function<Claims, User> claimsUserFactory, Function<Claims, Collection<? extends GrantedAuthority>> authoritiesResolver) { Assert.notNull(claimsExtractor, "claimsExtractor cannot be null."); Assert.notNull(claimsUserFactory, "claimsUserFactory cannot be null."); this.claimsExtractor = claimsExtractor; this.claimsUserFactory = claimsUserFactory; this.authoritiesResolver = authoritiesResolver; } @Override public UserDetails apply(String headerValue) { Claims claims = claimsExtractor.apply(headerValue); User user = claimsUserFactory.apply(claims); Collection<? extends GrantedAuthority> authorities = Collections.emptyList(); if (authoritiesResolver != null) { authorities = authoritiesResolver.apply(claims); }
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // } // // Path: spring/spring-security/src/main/java/org/juiser/spring/security/core/userdetails/ForwardedUserDetails.java // public class ForwardedUserDetails implements UserDetails { // // private final User user; // private final Collection<? extends GrantedAuthority> grantedAuthorities; // // public ForwardedUserDetails(User user, Collection<? extends GrantedAuthority> grantedAuthorities) { // Assert.notNull(user, "User argument cannot be null."); // Assert.hasText(user.getUsername(), "User username cannot be null or empty."); // this.user = user; // if (CollectionUtils.isEmpty(grantedAuthorities)) { // this.grantedAuthorities = java.util.Collections.emptyList(); // } else { // this.grantedAuthorities = java.util.Collections.unmodifiableCollection(grantedAuthorities); // } // } // // public User getUser() { // return this.user; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return this.grantedAuthorities; // } // // @Override // public String getPassword() { // return null; // } // // @Override // public String getUsername() { // return getUser().getUsername(); // } // // @Override // public boolean isAccountNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isAccountNonLocked() { // return true; //gateway will not forward locked accounts // } // // @Override // public boolean isCredentialsNonExpired() { // return true; //gateway will not forward expired accounts // } // // @Override // public boolean isEnabled() { // return true; //gateway will not forward disabled accounts // } // } // Path: spring/spring-security/src/main/java/org/juiser/spring/security/authentication/JwsToUserDetailsConverter.java import org.juiser.model.User; import org.juiser.spring.security.core.userdetails.ForwardedUserDetails; import io.jsonwebtoken.Claims; import io.jsonwebtoken.lang.Assert; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.Collections; import java.util.function.Function; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.security.authentication; /** * @since 1.0.0 */ public class JwsToUserDetailsConverter implements Function<String, UserDetails> { private final Function<String, Claims> claimsExtractor; private final Function<Claims, User> claimsUserFactory; private final Function<Claims, Collection<? extends GrantedAuthority>> authoritiesResolver; public JwsToUserDetailsConverter(Function<String, Claims> claimsExtractor, Function<Claims, User> claimsUserFactory, Function<Claims, Collection<? extends GrantedAuthority>> authoritiesResolver) { Assert.notNull(claimsExtractor, "claimsExtractor cannot be null."); Assert.notNull(claimsUserFactory, "claimsUserFactory cannot be null."); this.claimsExtractor = claimsExtractor; this.claimsUserFactory = claimsUserFactory; this.authoritiesResolver = authoritiesResolver; } @Override public UserDetails apply(String headerValue) { Claims claims = claimsExtractor.apply(headerValue); User user = claimsUserFactory.apply(claims); Collection<? extends GrantedAuthority> authorities = Collections.emptyList(); if (authoritiesResolver != null) { authorities = authoritiesResolver.apply(claims); }
return new ForwardedUserDetails(user, authorities);
juiser/juiser
spring/spring-web/src/main/java/org/juiser/spring/web/SpringForwardedUserFilter.java
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // } // // Path: servlet/src/main/java/org/juiser/servlet/ForwardedUserFilter.java // public class ForwardedUserFilter implements Filter { // // private final String headerName; // private final Function<HttpServletRequest, User> userFactory; // private final Collection<String> requestAttributeNames; // // public ForwardedUserFilter(String headerName, // Function<HttpServletRequest, User> userFactory, // Collection<String> requestAttributeNames) { // Assert.hasText(headerName, "headerName cannot be null or empty."); // Assert.notNull(userFactory, "userFactory function cannot be null."); // // this.headerName = headerName; // this.userFactory = userFactory; // // //always ensure that the fully qualified interface name is accessible: // LinkedHashSet<String> set = new LinkedHashSet<>(); // set.add(User.class.getName()); // if (!Collections.isEmpty(requestAttributeNames)) { // set.addAll(requestAttributeNames); // } // this.requestAttributeNames = set; // } // // @Override // public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // if (isEnabled(req)) { // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) resp; // doFilter(request, response, chain); // } else { // chain.doFilter(req, resp); // } // } // // public boolean isEnabled(ServletRequest request) throws ServletException { // return request instanceof HttpServletRequest && isEnabled((HttpServletRequest) request); // } // // public boolean isEnabled(HttpServletRequest request) throws ServletException { // String headerValue = request.getHeader(headerName); // return Strings.hasText(headerValue); // } // // public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) // throws ServletException, IOException { // // String value = request.getHeader(headerName); // assert Strings.hasText(value) : "request header value cannot be null or empty. Call isEnabled before calling doFilter"; // // User user = userFactory.apply(request); // assert user != null : "user instance returned from userFactory function cannot be null."; // // for (String requestAttributeName : requestAttributeNames) { // request.setAttribute(requestAttributeName, user); // } // try { // filterChain.doFilter(request, response); // } finally { // for (String requestAttributeName : requestAttributeNames) { // Object object = request.getAttribute(requestAttributeName); // if (user.equals(object)) { // //only remove the object if we put it there. If someone downstream of this filter changed // //it to be something else, we shouldn't touch it: // request.removeAttribute(requestAttributeName); // } // } // } // } // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // //no op // } // // @Override // public void destroy() { // //no op // } // }
import org.juiser.model.User; import org.juiser.servlet.ForwardedUserFilter; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection; import java.util.function.Function;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.web; /** * @since 1.0.0 */ public class SpringForwardedUserFilter extends OncePerRequestFilter { private final ForwardedUserFilter delegate; public SpringForwardedUserFilter(String headerName,
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // } // // Path: servlet/src/main/java/org/juiser/servlet/ForwardedUserFilter.java // public class ForwardedUserFilter implements Filter { // // private final String headerName; // private final Function<HttpServletRequest, User> userFactory; // private final Collection<String> requestAttributeNames; // // public ForwardedUserFilter(String headerName, // Function<HttpServletRequest, User> userFactory, // Collection<String> requestAttributeNames) { // Assert.hasText(headerName, "headerName cannot be null or empty."); // Assert.notNull(userFactory, "userFactory function cannot be null."); // // this.headerName = headerName; // this.userFactory = userFactory; // // //always ensure that the fully qualified interface name is accessible: // LinkedHashSet<String> set = new LinkedHashSet<>(); // set.add(User.class.getName()); // if (!Collections.isEmpty(requestAttributeNames)) { // set.addAll(requestAttributeNames); // } // this.requestAttributeNames = set; // } // // @Override // public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // if (isEnabled(req)) { // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) resp; // doFilter(request, response, chain); // } else { // chain.doFilter(req, resp); // } // } // // public boolean isEnabled(ServletRequest request) throws ServletException { // return request instanceof HttpServletRequest && isEnabled((HttpServletRequest) request); // } // // public boolean isEnabled(HttpServletRequest request) throws ServletException { // String headerValue = request.getHeader(headerName); // return Strings.hasText(headerValue); // } // // public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) // throws ServletException, IOException { // // String value = request.getHeader(headerName); // assert Strings.hasText(value) : "request header value cannot be null or empty. Call isEnabled before calling doFilter"; // // User user = userFactory.apply(request); // assert user != null : "user instance returned from userFactory function cannot be null."; // // for (String requestAttributeName : requestAttributeNames) { // request.setAttribute(requestAttributeName, user); // } // try { // filterChain.doFilter(request, response); // } finally { // for (String requestAttributeName : requestAttributeNames) { // Object object = request.getAttribute(requestAttributeName); // if (user.equals(object)) { // //only remove the object if we put it there. If someone downstream of this filter changed // //it to be something else, we shouldn't touch it: // request.removeAttribute(requestAttributeName); // } // } // } // } // // @Override // public void init(FilterConfig filterConfig) throws ServletException { // //no op // } // // @Override // public void destroy() { // //no op // } // } // Path: spring/spring-web/src/main/java/org/juiser/spring/web/SpringForwardedUserFilter.java import org.juiser.model.User; import org.juiser.servlet.ForwardedUserFilter; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection; import java.util.function.Function; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.web; /** * @since 1.0.0 */ public class SpringForwardedUserFilter extends OncePerRequestFilter { private final ForwardedUserFilter delegate; public SpringForwardedUserFilter(String headerName,
Function<HttpServletRequest, User> userFactory,
juiser/juiser
spring/spring-security/src/main/java/org/juiser/spring/security/web/authentication/HeaderAuthenticationFilter.java
// Path: spring/spring-security/src/main/java/org/juiser/spring/security/authentication/HeaderAuthenticationToken.java // public class HeaderAuthenticationToken extends AbstractAuthenticationToken { // // private final String headerName; // // private final String headerValue; // // public HeaderAuthenticationToken(String headerName, String headerValue) { // super(null); // Assert.hasText(headerName, "headerName cannot be null or empty."); // this.headerName = headerName; // Assert.hasText(headerValue, "headerValue cannot be null or empty."); // this.headerValue = headerValue; // } // // public String getHeaderName() { // return headerName; // } // // @Override // public Object getCredentials() { // return this.headerValue; // } // // @Override // public Object getPrincipal() { // return this.headerValue; // } // }
import org.juiser.spring.security.authentication.HeaderAuthenticationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException;
/** * Clears the {@link SecurityContextHolder} and returns {@code true}. */ protected boolean unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException failed) throws IOException, ServletException { SecurityContextHolder.clearContext(); if (log.isDebugEnabled()) { log.debug("Authentication request failed: " + failed.toString(), failed); log.debug("Updated SecurityContextHolder to contain null Authentication"); log.debug("Continuing filter chain with null Authentication"); } return true; } protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String name = getHeaderName(); String value = request.getHeader(name); Assert.hasText(value, "Missing expected request header value.");
// Path: spring/spring-security/src/main/java/org/juiser/spring/security/authentication/HeaderAuthenticationToken.java // public class HeaderAuthenticationToken extends AbstractAuthenticationToken { // // private final String headerName; // // private final String headerValue; // // public HeaderAuthenticationToken(String headerName, String headerValue) { // super(null); // Assert.hasText(headerName, "headerName cannot be null or empty."); // this.headerName = headerName; // Assert.hasText(headerValue, "headerValue cannot be null or empty."); // this.headerValue = headerValue; // } // // public String getHeaderName() { // return headerName; // } // // @Override // public Object getCredentials() { // return this.headerValue; // } // // @Override // public Object getPrincipal() { // return this.headerValue; // } // } // Path: spring/spring-security/src/main/java/org/juiser/spring/security/web/authentication/HeaderAuthenticationFilter.java import org.juiser.spring.security.authentication.HeaderAuthenticationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Clears the {@link SecurityContextHolder} and returns {@code true}. */ protected boolean unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException failed) throws IOException, ServletException { SecurityContextHolder.clearContext(); if (log.isDebugEnabled()) { log.debug("Authentication request failed: " + failed.toString(), failed); log.debug("Updated SecurityContextHolder to contain null Authentication"); log.debug("Continuing filter chain with null Authentication"); } return true; } protected Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { String name = getHeaderName(); String value = request.getHeader(name); Assert.hasText(value, "Missing expected request header value.");
HeaderAuthenticationToken token = new HeaderAuthenticationToken(name, value);
juiser/juiser
core/src/main/java/org/juiser/jwt/config/ConfigJwkResolver.java
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // // Path: core/src/main/java/org/juiser/jwt/AlgorithmFamily.java // public enum AlgorithmFamily { // // HMAC, // RSA, // EC; //Elliptic Curve // // public static AlgorithmFamily forName(String name) { // // if (HMAC.name().equalsIgnoreCase(name)) { // return HMAC; // } else if (RSA.name().equalsIgnoreCase(name)) { // return RSA; // } else if (EC.name().equalsIgnoreCase(name) || // "ECDSA".equalsIgnoreCase(name) || // "Elliptic Curve".equalsIgnoreCase(name)) { // return EC; // } // // //couldn't associate, invalid arg: // String msg = "Unrecognized algorithm family name value: " + name; // throw new IllegalArgumentException(msg); // } // }
import java.security.PublicKey; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.util.function.Function; import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import org.juiser.jwt.AlgorithmFamily; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Classes; import io.jsonwebtoken.lang.RuntimeEnvironment; import io.jsonwebtoken.lang.Strings; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.Key;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.jwt.config; /** * @since 1.0.0 */ public class ConfigJwkResolver implements Function<JwkConfig, Key> { private final ResourceLoader resourceLoader; public ConfigJwkResolver(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader); this.resourceLoader = resourceLoader; } @Override public Key apply(JwkConfig jwk) { Key key = null;
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // // Path: core/src/main/java/org/juiser/jwt/AlgorithmFamily.java // public enum AlgorithmFamily { // // HMAC, // RSA, // EC; //Elliptic Curve // // public static AlgorithmFamily forName(String name) { // // if (HMAC.name().equalsIgnoreCase(name)) { // return HMAC; // } else if (RSA.name().equalsIgnoreCase(name)) { // return RSA; // } else if (EC.name().equalsIgnoreCase(name) || // "ECDSA".equalsIgnoreCase(name) || // "Elliptic Curve".equalsIgnoreCase(name)) { // return EC; // } // // //couldn't associate, invalid arg: // String msg = "Unrecognized algorithm family name value: " + name; // throw new IllegalArgumentException(msg); // } // } // Path: core/src/main/java/org/juiser/jwt/config/ConfigJwkResolver.java import java.security.PublicKey; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.util.function.Function; import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import org.juiser.jwt.AlgorithmFamily; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Classes; import io.jsonwebtoken.lang.RuntimeEnvironment; import io.jsonwebtoken.lang.Strings; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.Key; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.jwt.config; /** * @since 1.0.0 */ public class ConfigJwkResolver implements Function<JwkConfig, Key> { private final ResourceLoader resourceLoader; public ConfigJwkResolver(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader); this.resourceLoader = resourceLoader; } @Override public Key apply(JwkConfig jwk) { Key key = null;
AlgorithmFamily algorithmFamily = null;
juiser/juiser
core/src/main/java/org/juiser/jwt/config/ConfigJwkResolver.java
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // // Path: core/src/main/java/org/juiser/jwt/AlgorithmFamily.java // public enum AlgorithmFamily { // // HMAC, // RSA, // EC; //Elliptic Curve // // public static AlgorithmFamily forName(String name) { // // if (HMAC.name().equalsIgnoreCase(name)) { // return HMAC; // } else if (RSA.name().equalsIgnoreCase(name)) { // return RSA; // } else if (EC.name().equalsIgnoreCase(name) || // "ECDSA".equalsIgnoreCase(name) || // "Elliptic Curve".equalsIgnoreCase(name)) { // return EC; // } // // //couldn't associate, invalid arg: // String msg = "Unrecognized algorithm family name value: " + name; // throw new IllegalArgumentException(msg); // } // }
import java.security.PublicKey; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.util.function.Function; import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import org.juiser.jwt.AlgorithmFamily; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Classes; import io.jsonwebtoken.lang.RuntimeEnvironment; import io.jsonwebtoken.lang.Strings; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.Key;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.jwt.config; /** * @since 1.0.0 */ public class ConfigJwkResolver implements Function<JwkConfig, Key> { private final ResourceLoader resourceLoader; public ConfigJwkResolver(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader); this.resourceLoader = resourceLoader; } @Override public Key apply(JwkConfig jwk) { Key key = null; AlgorithmFamily algorithmFamily = null; String algFamilyName = jwk.getAlgFamily(); if (Strings.hasText(algFamilyName)) { try { algorithmFamily = AlgorithmFamily.forName(algFamilyName); } catch (IllegalArgumentException e) { String msg = "Unsupported juiser.header.jwt.jwk.algFamily value: " + algFamilyName + ". " + "Please use only " + AlgorithmFamily.class.getName() + " enum names: " + Strings.arrayToCommaDelimitedString(AlgorithmFamily.values()); throw new IllegalArgumentException(msg, e); } } byte[] bytes = null;
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // // Path: core/src/main/java/org/juiser/jwt/AlgorithmFamily.java // public enum AlgorithmFamily { // // HMAC, // RSA, // EC; //Elliptic Curve // // public static AlgorithmFamily forName(String name) { // // if (HMAC.name().equalsIgnoreCase(name)) { // return HMAC; // } else if (RSA.name().equalsIgnoreCase(name)) { // return RSA; // } else if (EC.name().equalsIgnoreCase(name) || // "ECDSA".equalsIgnoreCase(name) || // "Elliptic Curve".equalsIgnoreCase(name)) { // return EC; // } // // //couldn't associate, invalid arg: // String msg = "Unrecognized algorithm family name value: " + name; // throw new IllegalArgumentException(msg); // } // } // Path: core/src/main/java/org/juiser/jwt/config/ConfigJwkResolver.java import java.security.PublicKey; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.util.function.Function; import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import org.juiser.jwt.AlgorithmFamily; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Classes; import io.jsonwebtoken.lang.RuntimeEnvironment; import io.jsonwebtoken.lang.Strings; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.Key; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.jwt.config; /** * @since 1.0.0 */ public class ConfigJwkResolver implements Function<JwkConfig, Key> { private final ResourceLoader resourceLoader; public ConfigJwkResolver(ResourceLoader resourceLoader) { Assert.notNull(resourceLoader); this.resourceLoader = resourceLoader; } @Override public Key apply(JwkConfig jwk) { Key key = null; AlgorithmFamily algorithmFamily = null; String algFamilyName = jwk.getAlgFamily(); if (Strings.hasText(algFamilyName)) { try { algorithmFamily = AlgorithmFamily.forName(algFamilyName); } catch (IllegalArgumentException e) { String msg = "Unsupported juiser.header.jwt.jwk.algFamily value: " + algFamilyName + ". " + "Please use only " + AlgorithmFamily.class.getName() + " enum names: " + Strings.arrayToCommaDelimitedString(AlgorithmFamily.values()); throw new IllegalArgumentException(msg, e); } } byte[] bytes = null;
Resource keyResource = getResource(jwk);
juiser/juiser
core/src/main/java/org/juiser/jwt/config/ConfigJwkResolver.java
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // // Path: core/src/main/java/org/juiser/jwt/AlgorithmFamily.java // public enum AlgorithmFamily { // // HMAC, // RSA, // EC; //Elliptic Curve // // public static AlgorithmFamily forName(String name) { // // if (HMAC.name().equalsIgnoreCase(name)) { // return HMAC; // } else if (RSA.name().equalsIgnoreCase(name)) { // return RSA; // } else if (EC.name().equalsIgnoreCase(name) || // "ECDSA".equalsIgnoreCase(name) || // "Elliptic Curve".equalsIgnoreCase(name)) { // return EC; // } // // //couldn't associate, invalid arg: // String msg = "Unrecognized algorithm family name value: " + name; // throw new IllegalArgumentException(msg); // } // }
import java.security.PublicKey; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.util.function.Function; import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import org.juiser.jwt.AlgorithmFamily; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Classes; import io.jsonwebtoken.lang.RuntimeEnvironment; import io.jsonwebtoken.lang.Strings; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.Key;
if (keyResource != null && keyStringSpecified) { String msg = "Both the juiser.header.jwt.key.value and " + "juiser.header.jwt.key.resource properties may not be set simultaneously. " + "Please choose one."; throw new IllegalArgumentException(msg); } if (keyStringSpecified) { String encoding = jwk.getEncoding(); if (keyString.startsWith(PemResourceKeyResolver.PEM_PREFIX)) { encoding = "pem"; } if (encoding == null) { //default to the JWK specification format: encoding = "base64url"; } if (encoding.equalsIgnoreCase("base64url")) { bytes = TextCodec.BASE64URL.decode(keyString); } else if (encoding.equalsIgnoreCase("base64")) { bytes = TextCodec.BASE64.decode(keyString); } else if (encoding.equalsIgnoreCase("utf8")) { bytes = keyString.getBytes(StandardCharsets.UTF_8); } else if (encoding.equalsIgnoreCase("pem")) { byte[] resourceBytes = keyString.getBytes(StandardCharsets.UTF_8); final ByteArrayInputStream bais = new ByteArrayInputStream(resourceBytes);
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // // Path: core/src/main/java/org/juiser/jwt/AlgorithmFamily.java // public enum AlgorithmFamily { // // HMAC, // RSA, // EC; //Elliptic Curve // // public static AlgorithmFamily forName(String name) { // // if (HMAC.name().equalsIgnoreCase(name)) { // return HMAC; // } else if (RSA.name().equalsIgnoreCase(name)) { // return RSA; // } else if (EC.name().equalsIgnoreCase(name) || // "ECDSA".equalsIgnoreCase(name) || // "Elliptic Curve".equalsIgnoreCase(name)) { // return EC; // } // // //couldn't associate, invalid arg: // String msg = "Unrecognized algorithm family name value: " + name; // throw new IllegalArgumentException(msg); // } // } // Path: core/src/main/java/org/juiser/jwt/config/ConfigJwkResolver.java import java.security.PublicKey; import java.security.interfaces.ECKey; import java.security.interfaces.RSAKey; import java.util.function.Function; import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import org.juiser.jwt.AlgorithmFamily; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.TextCodec; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Classes; import io.jsonwebtoken.lang.RuntimeEnvironment; import io.jsonwebtoken.lang.Strings; import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.Key; if (keyResource != null && keyStringSpecified) { String msg = "Both the juiser.header.jwt.key.value and " + "juiser.header.jwt.key.resource properties may not be set simultaneously. " + "Please choose one."; throw new IllegalArgumentException(msg); } if (keyStringSpecified) { String encoding = jwk.getEncoding(); if (keyString.startsWith(PemResourceKeyResolver.PEM_PREFIX)) { encoding = "pem"; } if (encoding == null) { //default to the JWK specification format: encoding = "base64url"; } if (encoding.equalsIgnoreCase("base64url")) { bytes = TextCodec.BASE64URL.decode(keyString); } else if (encoding.equalsIgnoreCase("base64")) { bytes = TextCodec.BASE64.decode(keyString); } else if (encoding.equalsIgnoreCase("utf8")) { bytes = keyString.getBytes(StandardCharsets.UTF_8); } else if (encoding.equalsIgnoreCase("pem")) { byte[] resourceBytes = keyString.getBytes(StandardCharsets.UTF_8); final ByteArrayInputStream bais = new ByteArrayInputStream(resourceBytes);
keyResource = new DefaultResource(bais, "juiser.header.jwt.key.value");
juiser/juiser
spring/spring-core/src/main/java/org/juiser/spring/io/SpringResourceLoader.java
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // }
import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import java.io.IOException;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.io; /** * @since 1.0.0 */ public class SpringResourceLoader implements ResourceLoader { private final org.springframework.core.io.ResourceLoader loader; public SpringResourceLoader(org.springframework.core.io.ResourceLoader loader) { this.loader = loader; }
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // Path: spring/spring-core/src/main/java/org/juiser/spring/io/SpringResourceLoader.java import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import java.io.IOException; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.io; /** * @since 1.0.0 */ public class SpringResourceLoader implements ResourceLoader { private final org.springframework.core.io.ResourceLoader loader; public SpringResourceLoader(org.springframework.core.io.ResourceLoader loader) { this.loader = loader; }
public Resource getResource(String path) throws IOException {
juiser/juiser
spring/spring-core/src/main/java/org/juiser/spring/io/SpringResourceLoader.java
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // }
import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import java.io.IOException;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.io; /** * @since 1.0.0 */ public class SpringResourceLoader implements ResourceLoader { private final org.springframework.core.io.ResourceLoader loader; public SpringResourceLoader(org.springframework.core.io.ResourceLoader loader) { this.loader = loader; } public Resource getResource(String path) throws IOException { org.springframework.core.io.Resource resource = loader.getResource(path);
// Path: core/src/main/java/org/juiser/io/DefaultResource.java // public class DefaultResource implements Resource { // // private final InputStream is; // private final String name; // // public DefaultResource(InputStream is, String name) { // Assert.notNull(is, "InputStream cannot be null."); // Assert.hasText(name, "String name argument cannot be null or empty."); // this.is = is; // this.name = name; // } // // @Override // public InputStream getInputStream() { // return this.is; // } // // @Override // public String getName() { // return this.name; // } // // @Override // public String toString() { // return "DefaultResource name='" + getName() + "'"; // } // } // // Path: core/src/main/java/org/juiser/io/Resource.java // public interface Resource { // // InputStream getInputStream(); // // String getName(); // } // // Path: core/src/main/java/org/juiser/io/ResourceLoader.java // public interface ResourceLoader { // // Resource getResource(String path) throws IOException; // } // Path: spring/spring-core/src/main/java/org/juiser/spring/io/SpringResourceLoader.java import org.juiser.io.DefaultResource; import org.juiser.io.Resource; import org.juiser.io.ResourceLoader; import java.io.IOException; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.spring.io; /** * @since 1.0.0 */ public class SpringResourceLoader implements ResourceLoader { private final org.springframework.core.io.ResourceLoader loader; public SpringResourceLoader(org.springframework.core.io.ResourceLoader loader) { this.loader = loader; } public Resource getResource(String path) throws IOException { org.springframework.core.io.Resource resource = loader.getResource(path);
return new DefaultResource(resource.getInputStream(), resource.getDescription());
juiser/juiser
servlet/src/main/java/org/juiser/servlet/ForwardedUserFilter.java
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // }
import java.util.LinkedHashSet; import java.util.function.Function; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Collections; import io.jsonwebtoken.lang.Strings; import org.juiser.model.User; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection;
/* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.servlet; /** * @since 1.0.0 */ public class ForwardedUserFilter implements Filter { private final String headerName;
// Path: core/src/main/java/org/juiser/model/User.java // public interface User { // // /** // * Returns {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // * // * @return {@code true} if the user has been authenticated (proven their identity) or {@code false} if the user // * is considered anonymous. // */ // boolean isAuthenticated(); // // /** // * Returns {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // * // * @return {@code true} if the user identity is unknown, {@code false} if the user is authenticated. // */ // boolean isAnonymous(); // // String getHref(); // // String getId(); // // String getName(); //full name // // String getGivenName(); //aka 'first name' in Western cultures // // String getFamilyName(); //aka surname // // String getMiddleName(); // // String getNickname(); //aka 'Mike' if givenName is 'Michael' // // String getUsername(); //OIDC 'preferred_username' // // URL getProfile(); // // URL getPicture(); // // URL getWebsite(); // // String getEmail(); // // boolean isEmailVerified(); // // String getGender(); // // LocalDate getBirthdate(); // // TimeZone getZoneInfo(); // // Locale getLocale(); // // Phone getPhone(); // // String getPhoneNumber(); // // boolean isPhoneNumberVerified(); // // ZonedDateTime getCreatedAt(); // // ZonedDateTime getUpdatedAt(); // } // Path: servlet/src/main/java/org/juiser/servlet/ForwardedUserFilter.java import java.util.LinkedHashSet; import java.util.function.Function; import io.jsonwebtoken.lang.Assert; import io.jsonwebtoken.lang.Collections; import io.jsonwebtoken.lang.Strings; import org.juiser.model.User; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Collection; /* * Copyright 2017 Les Hazlewood and the respective Juiser contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.juiser.servlet; /** * @since 1.0.0 */ public class ForwardedUserFilter implements Filter { private final String headerName;
private final Function<HttpServletRequest, User> userFactory;
juiser/juiser
spring/spring-security/src/main/java/org/juiser/spring/security/authentication/HeaderAuthenticationProvider.java
// Path: spring/spring-security/src/main/java/org/juiser/spring/security/core/ForwardedUserAuthentication.java // public class ForwardedUserAuthentication implements Authentication { // // private final UserDetails details; // // public ForwardedUserAuthentication(UserDetails details) { // Assert.notNull(details, "details argument cannot be null."); // this.details = details; // } // // @SuppressWarnings("unchecked") // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return details.getAuthorities(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return details; // } // // @Override // public Object getPrincipal() { // return details; // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // throw new IllegalArgumentException(getClass().getName() + " instances are immutable."); // } // // @Override // public String getName() { // return details.getUsername(); // } // }
import io.jsonwebtoken.JwtException; import org.juiser.spring.security.core.ForwardedUserAuthentication; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.util.function.Function;
public boolean supports(Class<?> authentication) { return HeaderAuthenticationToken.class.isAssignableFrom(authentication); } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { HeaderAuthenticationToken token = (HeaderAuthenticationToken) authentication; Object creds = token.getCredentials(); if (!(creds instanceof String)) { throw new BadCredentialsException("HeaderAuthenticationToken credentials must be a String."); } String value = (String) creds; if (!StringUtils.hasText(value)) { throw new BadCredentialsException("HeaderAuthenticationToken credentials String cannot be null or empty."); } UserDetails details; try { details = converter.apply(value); } catch (JwtException e) { String msg = "Invalid or unsupported request header JWT: " + e.getMessage(); throw new BadCredentialsException(msg, e); } catch (Exception e) { String msg = "Unexpected exception during authentication header parsing: " + e.getMessage(); throw new InternalAuthenticationServiceException(msg, e); }
// Path: spring/spring-security/src/main/java/org/juiser/spring/security/core/ForwardedUserAuthentication.java // public class ForwardedUserAuthentication implements Authentication { // // private final UserDetails details; // // public ForwardedUserAuthentication(UserDetails details) { // Assert.notNull(details, "details argument cannot be null."); // this.details = details; // } // // @SuppressWarnings("unchecked") // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return details.getAuthorities(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return details; // } // // @Override // public Object getPrincipal() { // return details; // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // throw new IllegalArgumentException(getClass().getName() + " instances are immutable."); // } // // @Override // public String getName() { // return details.getUsername(); // } // } // Path: spring/spring-security/src/main/java/org/juiser/spring/security/authentication/HeaderAuthenticationProvider.java import io.jsonwebtoken.JwtException; import org.juiser.spring.security.core.ForwardedUserAuthentication; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.util.function.Function; public boolean supports(Class<?> authentication) { return HeaderAuthenticationToken.class.isAssignableFrom(authentication); } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { HeaderAuthenticationToken token = (HeaderAuthenticationToken) authentication; Object creds = token.getCredentials(); if (!(creds instanceof String)) { throw new BadCredentialsException("HeaderAuthenticationToken credentials must be a String."); } String value = (String) creds; if (!StringUtils.hasText(value)) { throw new BadCredentialsException("HeaderAuthenticationToken credentials String cannot be null or empty."); } UserDetails details; try { details = converter.apply(value); } catch (JwtException e) { String msg = "Invalid or unsupported request header JWT: " + e.getMessage(); throw new BadCredentialsException(msg, e); } catch (Exception e) { String msg = "Unexpected exception during authentication header parsing: " + e.getMessage(); throw new InternalAuthenticationServiceException(msg, e); }
return new ForwardedUserAuthentication(details);
mibo/janos
janos-core/src/test/java/org/apache/olingo/odata2/janos/processor/core/util/AnnotationHelperTest.java
// Path: janos-core/src/test/java/org/apache/olingo/odata2/janos/processor/core/model/Location.java // @EdmComplexType(name = "c_Location", namespace = ModelSharedConstants.NAMESPACE_1) // public class Location { // @EdmProperty // private String country; // @EdmProperty // private City city; // // public Location(final String country, final String postalCode, final String cityName) { // this.country = country; // city = new City(postalCode, cityName); // } // // public void setCountry(final String country) { // this.country = country; // } // // public String getCountry() { // return country; // } // // public void setCity(final City city) { // this.city = city; // } // // public City getCity() { // return city; // } // // @Override // public String toString() { // return String.format("%s, %s", country, city.toString()); // } // // }
import junit.framework.Assert; import org.apache.olingo.odata2.api.annotation.edm.*; import org.apache.olingo.odata2.api.edm.FullQualifiedName; import org.apache.olingo.odata2.api.edm.provider.*; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.janos.processor.core.model.Location; import org.junit.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map;
@Test public void getFieldTypeForPropertyNullInstance() throws Exception { Object result = annotationHelper.getFieldTypeForProperty(null, ""); Assert.assertNull(result); } @Test public void getValueForPropertyNullInstance() throws Exception { Object result = annotationHelper.getValueForProperty(null, ""); Assert.assertNull(result); } @Test public void setValueForPropertyNullInstance() throws Exception { annotationHelper.setValueForProperty(null, "", null); } @Test public void extractEntitySetNameObject() { Assert.assertNull(annotationHelper.extractEntitySetName(Object.class)); } @Test public void extractComplexTypeFqnObject() { Assert.assertNull(annotationHelper.extractComplexTypeFqn(Object.class)); } @Test public void extractComplexTypeFqn() {
// Path: janos-core/src/test/java/org/apache/olingo/odata2/janos/processor/core/model/Location.java // @EdmComplexType(name = "c_Location", namespace = ModelSharedConstants.NAMESPACE_1) // public class Location { // @EdmProperty // private String country; // @EdmProperty // private City city; // // public Location(final String country, final String postalCode, final String cityName) { // this.country = country; // city = new City(postalCode, cityName); // } // // public void setCountry(final String country) { // this.country = country; // } // // public String getCountry() { // return country; // } // // public void setCity(final City city) { // this.city = city; // } // // public City getCity() { // return city; // } // // @Override // public String toString() { // return String.format("%s, %s", country, city.toString()); // } // // } // Path: janos-core/src/test/java/org/apache/olingo/odata2/janos/processor/core/util/AnnotationHelperTest.java import junit.framework.Assert; import org.apache.olingo.odata2.api.annotation.edm.*; import org.apache.olingo.odata2.api.edm.FullQualifiedName; import org.apache.olingo.odata2.api.edm.provider.*; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.janos.processor.core.model.Location; import org.junit.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; @Test public void getFieldTypeForPropertyNullInstance() throws Exception { Object result = annotationHelper.getFieldTypeForProperty(null, ""); Assert.assertNull(result); } @Test public void getValueForPropertyNullInstance() throws Exception { Object result = annotationHelper.getValueForProperty(null, ""); Assert.assertNull(result); } @Test public void setValueForPropertyNullInstance() throws Exception { annotationHelper.setValueForProperty(null, "", null); } @Test public void extractEntitySetNameObject() { Assert.assertNull(annotationHelper.extractEntitySetName(Object.class)); } @Test public void extractComplexTypeFqnObject() { Assert.assertNull(annotationHelper.extractComplexTypeFqn(Object.class)); } @Test public void extractComplexTypeFqn() {
FullQualifiedName fqn = annotationHelper.extractComplexTypeFqn(Location.class);
mibo/janos
janos-core/src/test/java/org/apache/olingo/odata2/janos/processor/core/data/store/AnnotationValueAccessTest.java
// Path: janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/data/access/AnnotationValueAccess.java // public class AnnotationValueAccess implements ValueAccess { // private final AnnotationHelper annotationHelper = new AnnotationHelper(); // // /** // * Retrieves the value of an EDM property for the given data object. // * @param data the Java data object // * @param property the requested {@link EdmProperty} // * @return the requested property value // */ // @Override // public <T> Object getPropertyValue(final T data, final EdmProperty property) throws ODataException { // if (data == null) { // return null; // } else if (annotationHelper.isEdmAnnotated(data)) { // return annotationHelper.getValueForProperty(data, property.getName()); // } // throw new ODataNotImplementedException(ODataNotImplementedException.COMMON); // } // // /** // * Sets the value of an EDM property for the given data object. // * @param data the Java data object // * @param property the {@link EdmProperty} // * @param value the new value of the property // */ // @Override // public <T, V> void setPropertyValue(final T data, final EdmProperty property, final V value) throws ODataException { // if (data != null) { // if (annotationHelper.isEdmAnnotated(data)) { // annotationHelper.setValueForProperty(data, property.getName(), value); // } else { // throw new ODataNotImplementedException(ODataNotImplementedException.COMMON); // } // } // } // // /** // * Retrieves the Java type of an EDM property for the given data object. // * @param data the Java data object // * @param property the requested {@link EdmProperty} // * @return the requested Java type // */ // @Override // public <T> Class<?> getPropertyType(final T data, final EdmProperty property) throws ODataException { // if (data == null) { // return null; // } else if (annotationHelper.isEdmAnnotated(data)) { // Class<?> fieldType = annotationHelper.getFieldTypeForProperty(data, property.getName()); // if (fieldType == null) { // throw new ODataException("No field type found for property " + property); // } // return fieldType; // } // throw new ODataNotImplementedException(ODataNotImplementedException.COMMON); // } // // /** // * Retrieves the value defined by a mapping object for the given data object. // * @param data the Java data object // * @param mapping the requested {@link EdmMapping} // * @return the requested value // */ // @Override // public <T> Object getMappingValue(final T data, final EdmMapping mapping) throws ODataException { // if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) { // return annotationHelper.getValueForProperty(data, mapping.getMediaResourceMimeTypeKey()); // } // return null; // } // // /** // * Sets the value defined by a mapping object for the given data object. // * @param data the Java data object // * @param mapping the {@link EdmMapping} // * @param value the new value // */ // @Override // public <T, V> void setMappingValue(final T data, final EdmMapping mapping, final V value) throws ODataException { // if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) { // annotationHelper.setValueForProperty(data, mapping.getMediaResourceMimeTypeKey(), value); // } // } // }
import junit.framework.Assert; import org.apache.olingo.odata2.api.annotation.edm.EdmEntityType; import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.edm.EdmMapping; import org.apache.olingo.odata2.api.edm.EdmProperty; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.api.exception.ODataNotImplementedException; import org.apache.olingo.odata2.janos.processor.core.data.access.AnnotationValueAccess; import org.junit.Test; import org.mockito.Mockito;
/* * Copyright 2013 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.olingo.odata2.janos.processor.core.data.store; /** * */ public class AnnotationValueAccessTest { @Test public void getPropertyType() throws ODataException {
// Path: janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/data/access/AnnotationValueAccess.java // public class AnnotationValueAccess implements ValueAccess { // private final AnnotationHelper annotationHelper = new AnnotationHelper(); // // /** // * Retrieves the value of an EDM property for the given data object. // * @param data the Java data object // * @param property the requested {@link EdmProperty} // * @return the requested property value // */ // @Override // public <T> Object getPropertyValue(final T data, final EdmProperty property) throws ODataException { // if (data == null) { // return null; // } else if (annotationHelper.isEdmAnnotated(data)) { // return annotationHelper.getValueForProperty(data, property.getName()); // } // throw new ODataNotImplementedException(ODataNotImplementedException.COMMON); // } // // /** // * Sets the value of an EDM property for the given data object. // * @param data the Java data object // * @param property the {@link EdmProperty} // * @param value the new value of the property // */ // @Override // public <T, V> void setPropertyValue(final T data, final EdmProperty property, final V value) throws ODataException { // if (data != null) { // if (annotationHelper.isEdmAnnotated(data)) { // annotationHelper.setValueForProperty(data, property.getName(), value); // } else { // throw new ODataNotImplementedException(ODataNotImplementedException.COMMON); // } // } // } // // /** // * Retrieves the Java type of an EDM property for the given data object. // * @param data the Java data object // * @param property the requested {@link EdmProperty} // * @return the requested Java type // */ // @Override // public <T> Class<?> getPropertyType(final T data, final EdmProperty property) throws ODataException { // if (data == null) { // return null; // } else if (annotationHelper.isEdmAnnotated(data)) { // Class<?> fieldType = annotationHelper.getFieldTypeForProperty(data, property.getName()); // if (fieldType == null) { // throw new ODataException("No field type found for property " + property); // } // return fieldType; // } // throw new ODataNotImplementedException(ODataNotImplementedException.COMMON); // } // // /** // * Retrieves the value defined by a mapping object for the given data object. // * @param data the Java data object // * @param mapping the requested {@link EdmMapping} // * @return the requested value // */ // @Override // public <T> Object getMappingValue(final T data, final EdmMapping mapping) throws ODataException { // if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) { // return annotationHelper.getValueForProperty(data, mapping.getMediaResourceMimeTypeKey()); // } // return null; // } // // /** // * Sets the value defined by a mapping object for the given data object. // * @param data the Java data object // * @param mapping the {@link EdmMapping} // * @param value the new value // */ // @Override // public <T, V> void setMappingValue(final T data, final EdmMapping mapping, final V value) throws ODataException { // if (mapping != null && mapping.getMediaResourceMimeTypeKey() != null) { // annotationHelper.setValueForProperty(data, mapping.getMediaResourceMimeTypeKey(), value); // } // } // } // Path: janos-core/src/test/java/org/apache/olingo/odata2/janos/processor/core/data/store/AnnotationValueAccessTest.java import junit.framework.Assert; import org.apache.olingo.odata2.api.annotation.edm.EdmEntityType; import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.edm.EdmMapping; import org.apache.olingo.odata2.api.edm.EdmProperty; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.api.exception.ODataNotImplementedException; import org.apache.olingo.odata2.janos.processor.core.data.access.AnnotationValueAccess; import org.junit.Test; import org.mockito.Mockito; /* * Copyright 2013 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.olingo.odata2.janos.processor.core.data.store; /** * */ public class AnnotationValueAccessTest { @Test public void getPropertyType() throws ODataException {
AnnotationValueAccess ava = new AnnotationValueAccess();
mibo/janos
janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/extension/ExtensionRegistry.java
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // }
import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map;
static class ExtensionHolder { private final String entitySetName; private final Extension.Method type; private final Method method; private final Object instance; public ExtensionHolder(String entitySetName, Extension.Method type, Object instance, Method method) { this.entitySetName = entitySetName; this.type = type; this.instance = instance; this.method = method; } public String getEntitySetName() { return entitySetName; } public Extension.Method getType() { return type; } public Object getInstance() { return instance; } public Method getMethod() { return method; } public Object process(ExtensionProcessor extProcessor) throws InvocationTargetException, IllegalAccessException {
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // } // Path: janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/extension/ExtensionRegistry.java import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; static class ExtensionHolder { private final String entitySetName; private final Extension.Method type; private final Method method; private final Object instance; public ExtensionHolder(String entitySetName, Extension.Method type, Object instance, Method method) { this.entitySetName = entitySetName; this.type = type; this.instance = instance; this.method = method; } public String getEntitySetName() { return entitySetName; } public Extension.Method getType() { return type; } public Object getInstance() { return instance; } public Method getMethod() { return method; } public Object process(ExtensionProcessor extProcessor) throws InvocationTargetException, IllegalAccessException {
ExtensionContext context = extProcessor.createContext();
mibo/janos
janos-ref/src/main/java/org/apache/olingo/odata2/janos/processor/ref/model/RefExtensions.java
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // }
import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.api.uri.UriInfo; import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.Extension.Method; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.apache.olingo.odata2.janos.processor.ref.model; /** * Created by mibo on 21.02.16. */ public class RefExtensions { private static final Logger LOG = LoggerFactory.getLogger(RefExtensions.class); private static final String EXTENSION_TEST = "ExtensionTest"; @Extension(entitySetNames="Employees", methods={Method.GET})
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // } // Path: janos-ref/src/main/java/org/apache/olingo/odata2/janos/processor/ref/model/RefExtensions.java import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.api.uri.UriInfo; import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.Extension.Method; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.apache.olingo.odata2.janos.processor.ref.model; /** * Created by mibo on 21.02.16. */ public class RefExtensions { private static final Logger LOG = LoggerFactory.getLogger(RefExtensions.class); private static final String EXTENSION_TEST = "ExtensionTest"; @Extension(entitySetNames="Employees", methods={Method.GET})
public Object logReadAccess(ExtensionContext context) throws Exception {
mibo/janos
janos-jpa-ref/src/main/java/org/apache/olingo/odata2/janos/processor/ref/jpa/model/RefExtensions.java
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // }
import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.Extension.Method; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.apache.olingo.odata2.janos.processor.ref.jpa.model; /** * Created by mibo on 21.02.16. */ public class RefExtensions { private static final Logger LOG = LoggerFactory.getLogger(RefExtensions.class); @Extension(entitySetNames="Employees", methods={Method.GET, Method.POST, Method.PUT})
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // } // Path: janos-jpa-ref/src/main/java/org/apache/olingo/odata2/janos/processor/ref/jpa/model/RefExtensions.java import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.Extension.Method; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.apache.olingo.odata2.janos.processor.ref.jpa.model; /** * Created by mibo on 21.02.16. */ public class RefExtensions { private static final Logger LOG = LoggerFactory.getLogger(RefExtensions.class); @Extension(entitySetNames="Employees", methods={Method.GET, Method.POST, Method.PUT})
public Object logAllAccess(ExtensionContext context) throws Exception {
mibo/janos
janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/extension/ExtensionProcessor.java
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // } // // Path: janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/ODataProcessor.java // public interface ODataProcessor extends MetadataProcessor, ServiceDocumentProcessor, EntityProcessor, EntitySetProcessor, // EntityComplexPropertyProcessor, EntityLinkProcessor, EntityLinksProcessor, EntityMediaProcessor, EntitySimplePropertyProcessor, // EntitySimplePropertyValueProcessor, FunctionImportProcessor, FunctionImportValueProcessor, BatchProcessor, CustomContentType { // }
import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.processor.ODataContext; import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.api.processor.feature.ODataProcessorFeature; import org.apache.olingo.odata2.api.uri.UriInfo; import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import org.apache.olingo.odata2.janos.processor.core.ODataProcessor; import org.omg.CORBA.portable.InputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays;
return ext.process(this); } return handler.process(); } private Extension.Method mapMethod(String httpMethod) { switch (httpMethod) { case "GET": return Extension.Method.GET; case "POST": return Extension.Method.POST; case "PUT": return Extension.Method.PUT; case "DELETE": return Extension.Method.DELETE; } throw new RuntimeException("Not mappable/supported HTTP method: " + httpMethod); } /** * Proceed (process) to wrapped processor instance * * @return * @throws Exception */ public ODataResponse proceed() throws Exception { Object o = this.handler.process(); if(o instanceof ODataResponse) { return (ODataResponse) o; } // TODO: change with 'better/concrete' exception throw new RuntimeException("Could not cast to ODataResponse"); }
// Path: janos-api/src/main/java/org/apache/olingo/odata2/janos/processor/api/extension/ExtensionContext.java // public interface ExtensionContext { // String PARA_URI_INFO = "~uriinfo"; // String PARA_ACCEPT_HEADER = "~acceptheader"; // String PARA_REQUEST_BODY = "~requestbody"; // String PARA_REQUEST_TYPE = "~requesttype"; // // ExtensionContext addParameter(String name, Object value); // // Object getParameter(String name); // // UriInfo getUriInfo(); // // String getAcceptHeader(); // // InputStream getRequestBody(); // // Extension.Method getRequestType(); // // ODataResponse proceed() throws Exception; // } // // Path: janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/ODataProcessor.java // public interface ODataProcessor extends MetadataProcessor, ServiceDocumentProcessor, EntityProcessor, EntitySetProcessor, // EntityComplexPropertyProcessor, EntityLinkProcessor, EntityLinksProcessor, EntityMediaProcessor, EntitySimplePropertyProcessor, // EntitySimplePropertyValueProcessor, FunctionImportProcessor, FunctionImportValueProcessor, BatchProcessor, CustomContentType { // } // Path: janos-core/src/main/java/org/apache/olingo/odata2/janos/processor/core/extension/ExtensionProcessor.java import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.processor.ODataContext; import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.api.processor.feature.ODataProcessorFeature; import org.apache.olingo.odata2.api.uri.UriInfo; import org.apache.olingo.odata2.janos.processor.api.extension.Extension; import org.apache.olingo.odata2.janos.processor.api.extension.ExtensionContext; import org.apache.olingo.odata2.janos.processor.core.ODataProcessor; import org.omg.CORBA.portable.InputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; return ext.process(this); } return handler.process(); } private Extension.Method mapMethod(String httpMethod) { switch (httpMethod) { case "GET": return Extension.Method.GET; case "POST": return Extension.Method.POST; case "PUT": return Extension.Method.PUT; case "DELETE": return Extension.Method.DELETE; } throw new RuntimeException("Not mappable/supported HTTP method: " + httpMethod); } /** * Proceed (process) to wrapped processor instance * * @return * @throws Exception */ public ODataResponse proceed() throws Exception { Object o = this.handler.process(); if(o instanceof ODataResponse) { return (ODataResponse) o; } // TODO: change with 'better/concrete' exception throw new RuntimeException("Could not cast to ODataResponse"); }
public ExtensionContext createContext() {
colormine/colormine
demo/src/org/colormine/servlet/ServletOutput.java
// Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // }
import java.awt.Color; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.colormine.image.profile.Profile; import org.json.JSONException; import org.json.JSONObject;
package org.colormine.servlet; public class ServletOutput { static void write(HttpServletResponse response, double data, String key) throws IOException { write(response, createJsonData(data, key)); } static void write(HttpServletResponse response, String data, String key) throws IOException { write(response, createJsonData(data, key)); } static void write(HttpServletResponse response, Map<Color, Integer> data) throws IOException { Map<String, String> stringData = convertToSerializable(data); JSONObject json = new JSONObject(stringData); write(response, json); }
// Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // } // Path: demo/src/org/colormine/servlet/ServletOutput.java import java.awt.Color; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.colormine.image.profile.Profile; import org.json.JSONException; import org.json.JSONObject; package org.colormine.servlet; public class ServletOutput { static void write(HttpServletResponse response, double data, String key) throws IOException { write(response, createJsonData(data, key)); } static void write(HttpServletResponse response, String data, String key) throws IOException { write(response, createJsonData(data, key)); } static void write(HttpServletResponse response, Map<Color, Integer> data) throws IOException { Map<String, String> stringData = convertToSerializable(data); JSONObject json = new JSONObject(stringData); write(response, json); }
static void write(HttpServletResponse response, Profile<Color> profile) throws IOException {
colormine/colormine
colormine/src/test/org/colormine/image/profile/ColorProfileTest.java
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // }
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import org.colormine.image.Image; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
package org.colormine.image.profile; @Test public class ColorProfileTest {
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // Path: colormine/src/test/org/colormine/image/profile/ColorProfileTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import org.colormine.image.Image; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; package org.colormine.image.profile; @Test public class ColorProfileTest {
private Image _image;
colormine/colormine
colormine/src/main/org/colormine/image/profile/filter/OutlierFilter.java
// Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // }
import java.awt.Color; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile;
package org.colormine.image.profile.filter; /** * Removes colors that make up less than a given percentage of the image This is * best done after using something like the MapFilter to 'condense' the palette */ public final class OutlierFilter implements Filter<Profile<Color>> { private final int _percentage; public OutlierFilter(int threshHoldPercentage) { _percentage = threshHoldPercentage; } public FilterResult<Profile<Color>> apply(Profile<Color> colors) {
// Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // } // Path: colormine/src/main/org/colormine/image/profile/filter/OutlierFilter.java import java.awt.Color; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile; package org.colormine.image.profile.filter; /** * Removes colors that make up less than a given percentage of the image This is * best done after using something like the MapFilter to 'condense' the palette */ public final class OutlierFilter implements Filter<Profile<Color>> { private final int _percentage; public OutlierFilter(int threshHoldPercentage) { _percentage = threshHoldPercentage; } public FilterResult<Profile<Color>> apply(Profile<Color> colors) {
Profile<Color> result = new ColorProfile();
colormine/colormine
colormine/src/test/org/colormine/colorspace/LabComparerTest.java
// Path: colormine/src/main/org/colormine/colorspace/Lab.java // public class Lab extends ColorTuple { // public final double L; // public final double A; // public final double B; // // /** // * Create Lab from values // * // * @param l // * @param a // * @param b // */ // public Lab(double l, double a, double b) { // L = l; // A = a; // B = b; // } // // /** // * Provides access to the coordinates that make up this color space in a // * uniform way. // * // * @return array containing the lab coordinates // */ // @Override // public Double[] getTuple() { // return new Double[] { L, A, B }; // } // // }
import java.text.DecimalFormat; import org.colormine.colorspace.Lab; import org.testng.AssertJUnit; import org.testng.annotations.Test;
package org.colormine.colorspace; @Test public class LabComparerTest { public void noDistance() {
// Path: colormine/src/main/org/colormine/colorspace/Lab.java // public class Lab extends ColorTuple { // public final double L; // public final double A; // public final double B; // // /** // * Create Lab from values // * // * @param l // * @param a // * @param b // */ // public Lab(double l, double a, double b) { // L = l; // A = a; // B = b; // } // // /** // * Provides access to the coordinates that make up this color space in a // * uniform way. // * // * @return array containing the lab coordinates // */ // @Override // public Double[] getTuple() { // return new Double[] { L, A, B }; // } // // } // Path: colormine/src/test/org/colormine/colorspace/LabComparerTest.java import java.text.DecimalFormat; import org.colormine.colorspace.Lab; import org.testng.AssertJUnit; import org.testng.annotations.Test; package org.colormine.colorspace; @Test public class LabComparerTest { public void noDistance() {
equals(0.0, new Lab(1, 0, 0), new Lab(1, 0, 0));
colormine/colormine
colormine/src/main/org/colormine/image/profile/ColorProfile.java
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // }
import java.awt.Color; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.colormine.image.Image;
package org.colormine.image.profile; public class ColorProfile implements Profile<Color> { private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); private int _total = 0; public ColorProfile() { }
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java import java.awt.Color; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.colormine.image.Image; package org.colormine.image.profile; public class ColorProfile implements Profile<Color> { private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); private int _total = 0; public ColorProfile() { }
public ColorProfile(Image image) {
colormine/colormine
colormine/src/test/org/colormine/image/profile/filter/MapFilterTest.java
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // // Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // }
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import java.util.HashMap; import java.util.Map; import org.colormine.image.Image; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
package org.colormine.image.profile.filter; @Test public class MapFilterTest {
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // // Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // } // Path: colormine/src/test/org/colormine/image/profile/filter/MapFilterTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import java.util.HashMap; import java.util.Map; import org.colormine.image.Image; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; package org.colormine.image.profile.filter; @Test public class MapFilterTest {
private Image _image;
colormine/colormine
colormine/src/test/org/colormine/image/profile/filter/MapFilterTest.java
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // // Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // }
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import java.util.HashMap; import java.util.Map; import org.colormine.image.Image; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
package org.colormine.image.profile.filter; @Test public class MapFilterTest { private Image _image; @BeforeTest public void setup() { _image = mock(Image.class); when(_image.getHeight()).thenReturn(1); when(_image.getWidth()).thenReturn(1); when(_image.getRGB(0, 0)).thenReturn(0xFF0000); } @Test public void sanity() { // ARRANGE Map<Color, Integer> colors = new HashMap<Color, Integer>(); colors.put(new Color(255, 0, 0), 1);
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // // Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // } // Path: colormine/src/test/org/colormine/image/profile/filter/MapFilterTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import java.util.HashMap; import java.util.Map; import org.colormine.image.Image; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; package org.colormine.image.profile.filter; @Test public class MapFilterTest { private Image _image; @BeforeTest public void setup() { _image = mock(Image.class); when(_image.getHeight()).thenReturn(1); when(_image.getWidth()).thenReturn(1); when(_image.getRGB(0, 0)).thenReturn(0xFF0000); } @Test public void sanity() { // ARRANGE Map<Color, Integer> colors = new HashMap<Color, Integer>(); colors.put(new Color(255, 0, 0), 1);
Profile<Color> map = new ColorProfile(colors);
colormine/colormine
colormine/src/test/org/colormine/image/profile/filter/MapFilterTest.java
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // // Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // }
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import java.util.HashMap; import java.util.Map; import org.colormine.image.Image; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;
package org.colormine.image.profile.filter; @Test public class MapFilterTest { private Image _image; @BeforeTest public void setup() { _image = mock(Image.class); when(_image.getHeight()).thenReturn(1); when(_image.getWidth()).thenReturn(1); when(_image.getRGB(0, 0)).thenReturn(0xFF0000); } @Test public void sanity() { // ARRANGE Map<Color, Integer> colors = new HashMap<Color, Integer>(); colors.put(new Color(255, 0, 0), 1);
// Path: colormine/src/main/org/colormine/image/Image.java // public interface Image { // /** // * Gets image width // * // * @return image width // */ // int getWidth(); // // /** // * Gets image height // * // * @return image height // */ // int getHeight(); // // /** // * Get Rgbs value of the pixel located at the position specified by x, y // * // * @param x // * @param y // * @return integer representation of the rgb value // */ // int getRGB(int x, int y); // } // // Path: colormine/src/main/org/colormine/image/profile/ColorProfile.java // public class ColorProfile implements Profile<Color> { // // private Map<Color, Integer> _colors = new HashMap<Color, Integer>(); // private int _total = 0; // // public ColorProfile() { // } // // public ColorProfile(Image image) { // int width = image.getWidth(); // int height = image.getHeight(); // // for (int y = 0; y < height; y++) { // for (int x = 0; x < width; x++) { // Color color = new Color(image.getRGB(x, y)); // put(color); // } // } // } // // public ColorProfile(Map<Color, Integer> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // public ColorProfile(Profile<Color> colors) { // Iterator<Map.Entry<Color, Integer>> color = colors.entrySet().iterator(); // while (color.hasNext()) { // Map.Entry<Color, Integer> pairs = (Map.Entry<Color, Integer>) color.next(); // put(pairs.getKey(), pairs.getValue()); // } // } // // @Override // public void put(Color key) { // int count = get(key) + 1; // _colors.put(key, count); // _total += count; // } // // @Override // public void put(Color key, int count) { // _colors.put(key, count); // _total += count; // } // // @Override // public int get(Color key) { // return _colors.containsKey(key) ? _colors.get(key) : 0; // } // // @Override // public int getTotal() { // return _total; // } // // @Override // public int size() { // return _colors.size(); // } // // @Override // public Set<Entry<Color, Integer>> entrySet() { // return _colors.entrySet(); // } // // @Override // public Set<Color> keySet() { // return _colors.keySet(); // } // } // // Path: colormine/src/main/org/colormine/image/profile/Profile.java // public interface Profile<K> { // /* // * Tracks an item // */ // void put(K key); // // /* // * Tracks an item // */ // void put(K key, int count); // // /* // * Returns the number of times an item has been recorded // */ // int get(K key); // // /* // * Returns the sum of all items that have been recorded // */ // int getTotal(); // // /* // * Returns the count of all distinct items that have been recorded // */ // int size(); // // Set<Entry<K, Integer>> entrySet(); // // Set<K> keySet(); // // } // Path: colormine/src/test/org/colormine/image/profile/filter/MapFilterTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.awt.Color; import java.util.HashMap; import java.util.Map; import org.colormine.image.Image; import org.colormine.image.profile.ColorProfile; import org.colormine.image.profile.Profile; import org.testng.AssertJUnit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; package org.colormine.image.profile.filter; @Test public class MapFilterTest { private Image _image; @BeforeTest public void setup() { _image = mock(Image.class); when(_image.getHeight()).thenReturn(1); when(_image.getWidth()).thenReturn(1); when(_image.getRGB(0, 0)).thenReturn(0xFF0000); } @Test public void sanity() { // ARRANGE Map<Color, Integer> colors = new HashMap<Color, Integer>(); colors.put(new Color(255, 0, 0), 1);
Profile<Color> map = new ColorProfile(colors);
iipc/webarchive-commons
src/main/java/org/archive/util/StreamCopy.java
// Path: src/main/java/org/archive/util/io/PushBackOneByteInputStream.java // public interface PushBackOneByteInputStream { // public void pushback() throws IOException; // public int read() throws IOException; // }
import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import org.archive.util.io.PushBackOneByteInputStream;
total += amtRead; } } return total; } public static long readToEOF(InputStream i) throws IOException { return readToEOF(i,DEFAULT_READ_SIZE); } public static long readToEOF(InputStream i, int bufferSize) throws IOException { long numBytes = 0; byte buffer[] = new byte[bufferSize]; while(true) { int amt = i.read(buffer,0,bufferSize); if(amt == -1) { return numBytes; } numBytes += amt; } } public static long readToEOFSingle(InputStream i) throws IOException { long numBytes = 0; while(true) { int c = i.read(); if(c == -1) { return numBytes; } numBytes++; } }
// Path: src/main/java/org/archive/util/io/PushBackOneByteInputStream.java // public interface PushBackOneByteInputStream { // public void pushback() throws IOException; // public int read() throws IOException; // } // Path: src/main/java/org/archive/util/StreamCopy.java import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import org.archive.util.io.PushBackOneByteInputStream; total += amtRead; } } return total; } public static long readToEOF(InputStream i) throws IOException { return readToEOF(i,DEFAULT_READ_SIZE); } public static long readToEOF(InputStream i, int bufferSize) throws IOException { long numBytes = 0; byte buffer[] = new byte[bufferSize]; while(true) { int amt = i.read(buffer,0,bufferSize); if(amt == -1) { return numBytes; } numBytes += amt; } } public static long readToEOFSingle(InputStream i) throws IOException { long numBytes = 0; while(true) { int c = i.read(); if(c == -1) { return numBytes; } numBytes++; } }
public static long skipChars(PushBackOneByteInputStream i, int [] skips) throws IOException {
dflick-pivotal/sentimentr-release
src/sentimentr-service-broker/src/main/java/io/pivotal/fe/sentimentr/broker/config/BrokerConfig.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // }
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.context.annotation.Bean;
package io.pivotal.fe.sentimentr.broker.config; @Configuration @ComponentScan(basePackages = "io.pivotal.fe.sentimentr.broker") public class BrokerConfig { @Bean
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // Path: src/sentimentr-service-broker/src/main/java/io/pivotal/fe/sentimentr/broker/config/BrokerConfig.java import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.context.annotation.Bean; package io.pivotal.fe.sentimentr.broker.config; @Configuration @ComponentScan(basePackages = "io.pivotal.fe.sentimentr.broker") public class BrokerConfig { @Bean
public BrokerApiVersion brokerApiVersion() {
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // }
import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition;
package org.springframework.cloud.servicebroker.service; /** * This interface is implemented by service brokers to process requests to retrieve the service catalog. * * @author sgreenberg@pivotal.io */ public interface CatalogService { /** * Return the catalog of services provided by the service broker. * * @return the catalog of services */ Catalog getCatalog(); /** * Get a service definition from the catalog by ID. * * @param serviceId The ID of the service definition in the catalog * @return the service definition, or null if it doesn't exist */
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; package org.springframework.cloud.servicebroker.service; /** * This interface is implemented by service brokers to process requests to retrieve the service catalog. * * @author sgreenberg@pivotal.io */ public interface CatalogService { /** * Return the catalog of services provided by the service broker. * * @return the catalog of services */ Catalog getCatalog(); /** * Get a service definition from the catalog by ID. * * @param serviceId The ID of the service definition in the catalog * @return the service definition, or null if it doesn't exist */
ServiceDefinition getServiceDefinition(String serviceId);
dflick-pivotal/sentimentr-release
sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/domain/Sentiment.java // @JsonIgnoreProperties(ignoreUnknown = true) // // public class Sentiment { // // private String sentiment; // private String id; // // public String getSentiment() { // return sentiment; // } // public void setSentiment(String sentiment) { // this.sentiment = sentiment; // } // public String getId() { // return id; // } // public void setId(String id) { // this.id = id; // } // // }
import io.pivotal.fe.sentimentr.client.domain.Sentiment; import org.springframework.web.client.RestTemplate;
package io.pivotal.fe.sentimentr.client.facade; public class SentimentrFacade { private String sentimentrUri; public SentimentrFacade() { } public SentimentrFacade(String sentimentrUri) { this.sentimentrUri = sentimentrUri; }
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/domain/Sentiment.java // @JsonIgnoreProperties(ignoreUnknown = true) // // public class Sentiment { // // private String sentiment; // private String id; // // public String getSentiment() { // return sentiment; // } // public void setSentiment(String sentiment) { // this.sentiment = sentiment; // } // public String getId() { // return id; // } // public void setId(String id) { // this.id = id; // } // // } // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java import io.pivotal.fe.sentimentr.client.domain.Sentiment; import org.springframework.web.client.RestTemplate; package io.pivotal.fe.sentimentr.client.facade; public class SentimentrFacade { private String sentimentrUri; public SentimentrFacade() { } public SentimentrFacade(String sentimentrUri) { this.sentimentrUri = sentimentrUri; }
public Sentiment getSentiment(String text)
dflick-pivotal/sentimentr-release
sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/controller/InfoController.java
// Path: sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/domain/ApplicationInfo.java // public class ApplicationInfo { // private String[] profiles; // private String[] services; // private String ip; // private int port; // // public ApplicationInfo(String[] profiles, String[] services, String ip, int port) { // this.profiles = profiles; // this.services = services; // this.ip = ip; // this.port = port; // } // // public String[] getProfiles() { // return profiles; // } // // public void setProfiles(String[] profiles) { // this.profiles = profiles; // } // // public String[] getServices() { // return services; // } // // public void setServices(String[] services) { // this.services = services; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.Cloud; import org.springframework.cloud.service.ServiceInfo; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import io.pivotal.fe.sentimentr.client.domain.ApplicationInfo; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest;
package io.pivotal.fe.sentimentr.client.controller; @Controller public class InfoController { @Autowired(required = false) private Cloud cloud; private Environment springEnvironment; @Autowired public InfoController(Environment springEnvironment) { this.springEnvironment = springEnvironment; } @RequestMapping(value = "/appinfo")
// Path: sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/domain/ApplicationInfo.java // public class ApplicationInfo { // private String[] profiles; // private String[] services; // private String ip; // private int port; // // public ApplicationInfo(String[] profiles, String[] services, String ip, int port) { // this.profiles = profiles; // this.services = services; // this.ip = ip; // this.port = port; // } // // public String[] getProfiles() { // return profiles; // } // // public void setProfiles(String[] profiles) { // this.profiles = profiles; // } // // public String[] getServices() { // return services; // } // // public void setServices(String[] services) { // this.services = services; // } // // public String getIp() { // return ip; // } // // public void setIp(String ip) { // this.ip = ip; // } // // public int getPort() { // return port; // } // // public void setPort(int port) { // this.port = port; // } // } // Path: sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/controller/InfoController.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.Cloud; import org.springframework.cloud.service.ServiceInfo; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import io.pivotal.fe.sentimentr.client.domain.ApplicationInfo; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; package io.pivotal.fe.sentimentr.client.controller; @Controller public class InfoController { @Autowired(required = false) private Cloud cloud; private Environment springEnvironment; @Autowired public InfoController(Environment springEnvironment) { this.springEnvironment = springEnvironment; } @RequestMapping(value = "/appinfo")
public @ResponseBody ApplicationInfo info(HttpServletRequest request) {
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/exception/ServiceBrokerApiVersionException.java // public class ServiceBrokerApiVersionException extends RuntimeException { // // private static final long serialVersionUID = -6792404679608443775L; // // public ServiceBrokerApiVersionException(String expectedVersion, String providedVersion) { // super("The provided service broker API version is not supported: " // + "expected version=" + expectedVersion // + ", provided version = " + providedVersion); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // }
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.cloud.servicebroker.exception.ServiceBrokerApiVersionException; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.springframework.cloud.servicebroker.interceptor; public class BrokerApiVersionInterceptorTest { @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/exception/ServiceBrokerApiVersionException.java // public class ServiceBrokerApiVersionException extends RuntimeException { // // private static final long serialVersionUID = -6792404679608443775L; // // public ServiceBrokerApiVersionException(String expectedVersion, String providedVersion) { // super("The provided service broker API version is not supported: " // + "expected version=" + expectedVersion // + ", provided version = " + providedVersion); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorTest.java import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.cloud.servicebroker.exception.ServiceBrokerApiVersionException; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.springframework.cloud.servicebroker.interceptor; public class BrokerApiVersionInterceptorTest { @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock
private BrokerApiVersion brokerApiVersion;
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/exception/ServiceBrokerApiVersionException.java // public class ServiceBrokerApiVersionException extends RuntimeException { // // private static final long serialVersionUID = -6792404679608443775L; // // public ServiceBrokerApiVersionException(String expectedVersion, String providedVersion) { // super("The provided service broker API version is not supported: " // + "expected version=" + expectedVersion // + ", provided version = " + providedVersion); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // }
import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.cloud.servicebroker.exception.ServiceBrokerApiVersionException; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations;
package org.springframework.cloud.servicebroker.interceptor; public class BrokerApiVersionInterceptorTest { @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private BrokerApiVersion brokerApiVersion; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/exception/ServiceBrokerApiVersionException.java // public class ServiceBrokerApiVersionException extends RuntimeException { // // private static final long serialVersionUID = -6792404679608443775L; // // public ServiceBrokerApiVersionException(String expectedVersion, String providedVersion) { // super("The provided service broker API version is not supported: " // + "expected version=" + expectedVersion // + ", provided version = " + providedVersion); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorTest.java import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.cloud.servicebroker.exception.ServiceBrokerApiVersionException; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; package org.springframework.cloud.servicebroker.interceptor; public class BrokerApiVersionInterceptorTest { @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private BrokerApiVersion brokerApiVersion; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test
public void noBrokerApiVersionConfigured() throws IOException, ServletException, ServiceBrokerApiVersionException {
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/service/impl/BeanCatalogServiceTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.Collections; import java.util.List; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.junit.Before; import org.junit.Test;
package org.springframework.cloud.servicebroker.service.impl; public class BeanCatalogServiceTest { private BeanCatalogService service;
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/service/impl/BeanCatalogServiceTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.Collections; import java.util.List; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.junit.Before; import org.junit.Test; package org.springframework.cloud.servicebroker.service.impl; public class BeanCatalogServiceTest { private BeanCatalogService service;
private Catalog catalog;
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/service/impl/BeanCatalogServiceTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.Collections; import java.util.List; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.junit.Before; import org.junit.Test;
package org.springframework.cloud.servicebroker.service.impl; public class BeanCatalogServiceTest { private BeanCatalogService service; private Catalog catalog;
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/service/impl/BeanCatalogServiceTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.Collections; import java.util.List; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.junit.Before; import org.junit.Test; package org.springframework.cloud.servicebroker.service.impl; public class BeanCatalogServiceTest { private BeanCatalogService service; private Catalog catalog;
private ServiceDefinition serviceDefinition;
dflick-pivotal/sentimentr-release
sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/config/CloudConfiguration.java
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // }
import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile;
package io.pivotal.fe.sentimentr.client.config; @Configuration @Profile({"cloud","local"}) public class CloudConfiguration extends AbstractCloudConfig { @Bean
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // } // Path: sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/config/CloudConfiguration.java import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.cloud.config.java.AbstractCloudConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; package io.pivotal.fe.sentimentr.client.config; @Configuration @Profile({"cloud","local"}) public class CloudConfiguration extends AbstractCloudConfig { @Bean
public SentimentrFacade sentimentrFacade() {
dflick-pivotal/sentimentr-release
sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/controller/SentimentrClientController.java
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/domain/Sentiment.java // @JsonIgnoreProperties(ignoreUnknown = true) // // public class Sentiment { // // private String sentiment; // private String id; // // public String getSentiment() { // return sentiment; // } // public void setSentiment(String sentiment) { // this.sentiment = sentiment; // } // public String getId() { // return id; // } // public void setId(String id) { // this.id = id; // } // // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // }
import io.pivotal.fe.sentimentr.client.domain.Sentiment; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate;
package io.pivotal.fe.sentimentr.client.controller; @RestController public class SentimentrClientController {
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/domain/Sentiment.java // @JsonIgnoreProperties(ignoreUnknown = true) // // public class Sentiment { // // private String sentiment; // private String id; // // public String getSentiment() { // return sentiment; // } // public void setSentiment(String sentiment) { // this.sentiment = sentiment; // } // public String getId() { // return id; // } // public void setId(String id) { // this.id = id; // } // // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // } // Path: sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/controller/SentimentrClientController.java import io.pivotal.fe.sentimentr.client.domain.Sentiment; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; package io.pivotal.fe.sentimentr.client.controller; @RestController public class SentimentrClientController {
private SentimentrFacade sentimentrFacade;
dflick-pivotal/sentimentr-release
sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/controller/SentimentrClientController.java
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/domain/Sentiment.java // @JsonIgnoreProperties(ignoreUnknown = true) // // public class Sentiment { // // private String sentiment; // private String id; // // public String getSentiment() { // return sentiment; // } // public void setSentiment(String sentiment) { // this.sentiment = sentiment; // } // public String getId() { // return id; // } // public void setId(String id) { // this.id = id; // } // // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // }
import io.pivotal.fe.sentimentr.client.domain.Sentiment; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate;
package io.pivotal.fe.sentimentr.client.controller; @RestController public class SentimentrClientController { private SentimentrFacade sentimentrFacade; @Autowired public SentimentrClientController(SentimentrFacade sentimentrFacade) { this.sentimentrFacade = sentimentrFacade; } @RequestMapping("/sentiment/{text}")
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/domain/Sentiment.java // @JsonIgnoreProperties(ignoreUnknown = true) // // public class Sentiment { // // private String sentiment; // private String id; // // public String getSentiment() { // return sentiment; // } // public void setSentiment(String sentiment) { // this.sentiment = sentiment; // } // public String getId() { // return id; // } // public void setId(String id) { // this.id = id; // } // // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // } // Path: sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/controller/SentimentrClientController.java import io.pivotal.fe.sentimentr.client.domain.Sentiment; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; package io.pivotal.fe.sentimentr.client.controller; @RestController public class SentimentrClientController { private SentimentrFacade sentimentrFacade; @Autowired public SentimentrClientController(SentimentrFacade sentimentrFacade) { this.sentimentrFacade = sentimentrFacade; } @RequestMapping("/sentiment/{text}")
public Sentiment getSentiment(@PathVariable String text) {
dflick-pivotal/sentimentr-release
sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/config/DefaultConfiguration.java
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // }
import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile;
package io.pivotal.fe.sentimentr.client.config; @Configuration @Profile("default") public class DefaultConfiguration { @Bean
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // } // Path: sentimentr-client/sentimentr-ui/src/main/java/io/pivotal/fe/sentimentr/client/config/DefaultConfiguration.java import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; package io.pivotal.fe.sentimentr.client.config; @Configuration @Profile("default") public class DefaultConfiguration { @Bean
public SentimentrFacade sentimentrFacade() {
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/BrokerApiVersionConfig.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptor.java // public class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter { // // private final BrokerApiVersion version; // // public BrokerApiVersionInterceptor() { // this(null); // } // // public BrokerApiVersionInterceptor(BrokerApiVersion version) { // this.version = version; // } // // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, // Object handler) throws ServiceBrokerApiVersionException { // if (version != null && !anyVersionAllowed()) { // String apiVersion = request.getHeader(version.getBrokerApiVersionHeader()); // if (!version.getApiVersion().equals(apiVersion)) { // throw new ServiceBrokerApiVersionException(version.getApiVersion(), apiVersion); // } // } // return true; // } // // private boolean anyVersionAllowed() { // return BrokerApiVersion.API_VERSION_ANY.equals(version.getApiVersion()); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // }
import org.springframework.cloud.servicebroker.interceptor.BrokerApiVersionInterceptor; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
package org.springframework.cloud.servicebroker.config; @Configuration @EnableWebMvc public class BrokerApiVersionConfig extends WebMvcConfigurerAdapter { @Autowired
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptor.java // public class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter { // // private final BrokerApiVersion version; // // public BrokerApiVersionInterceptor() { // this(null); // } // // public BrokerApiVersionInterceptor(BrokerApiVersion version) { // this.version = version; // } // // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, // Object handler) throws ServiceBrokerApiVersionException { // if (version != null && !anyVersionAllowed()) { // String apiVersion = request.getHeader(version.getBrokerApiVersionHeader()); // if (!version.getApiVersion().equals(apiVersion)) { // throw new ServiceBrokerApiVersionException(version.getApiVersion(), apiVersion); // } // } // return true; // } // // private boolean anyVersionAllowed() { // return BrokerApiVersion.API_VERSION_ANY.equals(version.getApiVersion()); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/BrokerApiVersionConfig.java import org.springframework.cloud.servicebroker.interceptor.BrokerApiVersionInterceptor; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; package org.springframework.cloud.servicebroker.config; @Configuration @EnableWebMvc public class BrokerApiVersionConfig extends WebMvcConfigurerAdapter { @Autowired
private BrokerApiVersion brokerApiVersion;
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/BrokerApiVersionConfig.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptor.java // public class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter { // // private final BrokerApiVersion version; // // public BrokerApiVersionInterceptor() { // this(null); // } // // public BrokerApiVersionInterceptor(BrokerApiVersion version) { // this.version = version; // } // // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, // Object handler) throws ServiceBrokerApiVersionException { // if (version != null && !anyVersionAllowed()) { // String apiVersion = request.getHeader(version.getBrokerApiVersionHeader()); // if (!version.getApiVersion().equals(apiVersion)) { // throw new ServiceBrokerApiVersionException(version.getApiVersion(), apiVersion); // } // } // return true; // } // // private boolean anyVersionAllowed() { // return BrokerApiVersion.API_VERSION_ANY.equals(version.getApiVersion()); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // }
import org.springframework.cloud.servicebroker.interceptor.BrokerApiVersionInterceptor; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
package org.springframework.cloud.servicebroker.config; @Configuration @EnableWebMvc public class BrokerApiVersionConfig extends WebMvcConfigurerAdapter { @Autowired private BrokerApiVersion brokerApiVersion; @Override public void addInterceptors(InterceptorRegistry registry) {
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptor.java // public class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter { // // private final BrokerApiVersion version; // // public BrokerApiVersionInterceptor() { // this(null); // } // // public BrokerApiVersionInterceptor(BrokerApiVersion version) { // this.version = version; // } // // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, // Object handler) throws ServiceBrokerApiVersionException { // if (version != null && !anyVersionAllowed()) { // String apiVersion = request.getHeader(version.getBrokerApiVersionHeader()); // if (!version.getApiVersion().equals(apiVersion)) { // throw new ServiceBrokerApiVersionException(version.getApiVersion(), apiVersion); // } // } // return true; // } // // private boolean anyVersionAllowed() { // return BrokerApiVersion.API_VERSION_ANY.equals(version.getApiVersion()); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/BrokerApiVersionConfig.java import org.springframework.cloud.servicebroker.interceptor.BrokerApiVersionInterceptor; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; package org.springframework.cloud.servicebroker.config; @Configuration @EnableWebMvc public class BrokerApiVersionConfig extends WebMvcConfigurerAdapter { @Autowired private BrokerApiVersion brokerApiVersion; @Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BrokerApiVersionInterceptor(brokerApiVersion)).addPathPatterns("/v2/**");
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8";
import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT;
package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8"; // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT; package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean
@ConditionalOnMissingBean(BrokerApiVersion.class)
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8";
import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT;
package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() {
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8"; // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT; package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() {
return new BrokerApiVersion(API_VERSION_CURRENT);
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8";
import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT;
package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion(API_VERSION_CURRENT); } @Bean
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8"; // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT; package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion(API_VERSION_CURRENT); } @Bean
@ConditionalOnMissingBean(CatalogService.class)
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8";
import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT;
package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion(API_VERSION_CURRENT); } @Bean @ConditionalOnMissingBean(CatalogService.class)
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8"; // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT; package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion(API_VERSION_CURRENT); } @Bean @ConditionalOnMissingBean(CatalogService.class)
public CatalogService beanCatalogService(Catalog catalog) {
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8";
import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT;
package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion(API_VERSION_CURRENT); } @Bean @ConditionalOnMissingBean(CatalogService.class) public CatalogService beanCatalogService(Catalog catalog) {
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java // public class BeanCatalogService implements CatalogService { // // private Catalog catalog; // private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>(); // // @Autowired // public BeanCatalogService(Catalog catalog) { // this.catalog = catalog; // initializeMap(); // } // // private void initializeMap() { // for (ServiceDefinition def: catalog.getServiceDefinitions()) { // serviceDefs.put(def.getId(), def); // } // } // // @Override // public Catalog getCatalog() { // return catalog; // } // // @Override // public ServiceDefinition getServiceDefinition(String serviceId) { // return serviceDefs.get(serviceId); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // public final static String API_VERSION_CURRENT = "2.8"; // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/config/ServiceBrokerAutoConfiguration.java import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.BeanCatalogService; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import static org.springframework.cloud.servicebroker.model.BrokerApiVersion.API_VERSION_CURRENT; package org.springframework.cloud.servicebroker.config; @Configuration @ComponentScan(basePackages = {"org.springframework.cloud.servicebroker"}) @ConditionalOnWebApplication @AutoConfigureAfter(WebMvcAutoConfiguration.class) public class ServiceBrokerAutoConfiguration { @Bean @ConditionalOnMissingBean(BrokerApiVersion.class) public BrokerApiVersion brokerApiVersion() { return new BrokerApiVersion(API_VERSION_CURRENT); } @Bean @ConditionalOnMissingBean(CatalogService.class) public CatalogService beanCatalogService(Catalog catalog) {
return new BeanCatalogService(catalog);
dflick-pivotal/sentimentr-release
sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/cloud/connector/SentimentrConnectionCreator.java
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/cloud/SentimentrServiceInfo.java // public class SentimentrServiceInfo extends UriBasedServiceInfo { // public SentimentrServiceInfo(String id, String url) { // super(id, url); // } // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacadeFactory.java // public class SentimentrFacadeFactory { // public SentimentrFacade create(String url) { // return new SentimentrFacade(url); // } // // public SentimentrFacade create(URL url) { // return create(url.toString()); // } // }
import org.springframework.cloud.service.AbstractServiceConnectorCreator; import org.springframework.cloud.service.ServiceConnectorConfig; import io.pivotal.fe.sentimentr.client.cloud.SentimentrServiceInfo; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacadeFactory;
package io.pivotal.fe.sentimentr.client.cloud.connector; public class SentimentrConnectionCreator extends AbstractServiceConnectorCreator<SentimentrFacade, SentimentrServiceInfo> { @Override public SentimentrFacade create(SentimentrServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) {
// Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/cloud/SentimentrServiceInfo.java // public class SentimentrServiceInfo extends UriBasedServiceInfo { // public SentimentrServiceInfo(String id, String url) { // super(id, url); // } // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacade.java // public class SentimentrFacade { // // private String sentimentrUri; // // public SentimentrFacade() // { // } // public SentimentrFacade(String sentimentrUri) // { // this.sentimentrUri = sentimentrUri; // } // // public Sentiment getSentiment(String text) // { // RestTemplate restTemplate = new RestTemplate(); // Sentiment sentiment = restTemplate.getForObject(sentimentrUri+"/{text}", Sentiment.class, text); // return sentiment; // } // // } // // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/facade/SentimentrFacadeFactory.java // public class SentimentrFacadeFactory { // public SentimentrFacade create(String url) { // return new SentimentrFacade(url); // } // // public SentimentrFacade create(URL url) { // return create(url.toString()); // } // } // Path: sentimentr-client/sentimentr-connector/src/main/java/io/pivotal/fe/sentimentr/client/cloud/connector/SentimentrConnectionCreator.java import org.springframework.cloud.service.AbstractServiceConnectorCreator; import org.springframework.cloud.service.ServiceConnectorConfig; import io.pivotal.fe.sentimentr.client.cloud.SentimentrServiceInfo; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacade; import io.pivotal.fe.sentimentr.client.facade.SentimentrFacadeFactory; package io.pivotal.fe.sentimentr.client.cloud.connector; public class SentimentrConnectionCreator extends AbstractServiceConnectorCreator<SentimentrFacade, SentimentrServiceInfo> { @Override public SentimentrFacade create(SentimentrServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) {
return new SentimentrFacadeFactory().create(serviceInfo.getUri());
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/ServiceFixture.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinitionRequires.java // public enum ServiceDefinitionRequires { // /** // * Indicates that the service broker allows Cloud Foundry to stream logs from bound applications to a // * service instance. If this permission is provided in a service definition, the broker should provide a // * non-null value in the <code>CreateServiceInstanceBindingResponse.syslogDrainUrl</code> field in response // * to a bind request. // */ // SERVICE_REQUIRES_SYSLOG_DRAIN("syslog_drain"), // // /** // * Indicates that the service broker allows Cloud Foundry to bind routes to a service instance. If this permission // * is provided in a service definition, the broker may receive bind requests with a <code>route</code> value in // * the <code>bindResource</code> field of a <code>CreateServiceInstanceBindingRequest</code>. // */ // SERVICE_REQUIRES_ROUTE_FORWARDING("route_forwarding"); // // private final String value; // // ServiceDefinitionRequires(String value) { // this.value = value; // } // // @Override // public String toString() { // return value; // } // }
import java.util.Arrays; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.cloud.servicebroker.model.ServiceDefinitionRequires;
package org.springframework.cloud.servicebroker.model.fixture; public class ServiceFixture { public static ServiceDefinition getSimpleService() { return new ServiceDefinition( "service-one-id", "Service One", "Description for Service One", true, PlanFixture.getAllPlans()); } public static ServiceDefinition getServiceWithRequires() { return new ServiceDefinition( "service-one-id", "Service One", "Description for Service One", true, true, PlanFixture.getAllPlans(), null, null, Arrays.asList(
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinitionRequires.java // public enum ServiceDefinitionRequires { // /** // * Indicates that the service broker allows Cloud Foundry to stream logs from bound applications to a // * service instance. If this permission is provided in a service definition, the broker should provide a // * non-null value in the <code>CreateServiceInstanceBindingResponse.syslogDrainUrl</code> field in response // * to a bind request. // */ // SERVICE_REQUIRES_SYSLOG_DRAIN("syslog_drain"), // // /** // * Indicates that the service broker allows Cloud Foundry to bind routes to a service instance. If this permission // * is provided in a service definition, the broker may receive bind requests with a <code>route</code> value in // * the <code>bindResource</code> field of a <code>CreateServiceInstanceBindingRequest</code>. // */ // SERVICE_REQUIRES_ROUTE_FORWARDING("route_forwarding"); // // private final String value; // // ServiceDefinitionRequires(String value) { // this.value = value; // } // // @Override // public String toString() { // return value; // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/ServiceFixture.java import java.util.Arrays; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.cloud.servicebroker.model.ServiceDefinitionRequires; package org.springframework.cloud.servicebroker.model.fixture; public class ServiceFixture { public static ServiceDefinition getSimpleService() { return new ServiceDefinition( "service-one-id", "Service One", "Description for Service One", true, PlanFixture.getAllPlans()); } public static ServiceDefinition getServiceWithRequires() { return new ServiceDefinition( "service-one-id", "Service One", "Description for Service One", true, true, PlanFixture.getAllPlans(), null, null, Arrays.asList(
ServiceDefinitionRequires.SERVICE_REQUIRES_SYSLOG_DRAIN.toString(),
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorIntegrationTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java // @RestController // @Slf4j // public class CatalogController extends BaseController { // @Autowired // public CatalogController(CatalogService service) { // super(service); // } // // @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET) // public Catalog getCatalog() { // log.debug("getCatalog()"); // return catalogService.getCatalog(); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // }
import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.cloud.servicebroker.controller.CatalogController; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.service.CatalogService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
package org.springframework.cloud.servicebroker.interceptor; @RunWith(MockitoJUnitRunner.class) public class BrokerApiVersionInterceptorIntegrationTest { private final static String CATALOG_PATH = "/v2/catalog"; private MockMvc mockMvc; @InjectMocks
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java // @RestController // @Slf4j // public class CatalogController extends BaseController { // @Autowired // public CatalogController(CatalogService service) { // super(service); // } // // @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET) // public Catalog getCatalog() { // log.debug("getCatalog()"); // return catalogService.getCatalog(); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorIntegrationTest.java import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.cloud.servicebroker.controller.CatalogController; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.service.CatalogService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; package org.springframework.cloud.servicebroker.interceptor; @RunWith(MockitoJUnitRunner.class) public class BrokerApiVersionInterceptorIntegrationTest { private final static String CATALOG_PATH = "/v2/catalog"; private MockMvc mockMvc; @InjectMocks
private CatalogController controller;
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorIntegrationTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java // @RestController // @Slf4j // public class CatalogController extends BaseController { // @Autowired // public CatalogController(CatalogService service) { // super(service); // } // // @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET) // public Catalog getCatalog() { // log.debug("getCatalog()"); // return catalogService.getCatalog(); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // }
import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.cloud.servicebroker.controller.CatalogController; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.service.CatalogService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
package org.springframework.cloud.servicebroker.interceptor; @RunWith(MockitoJUnitRunner.class) public class BrokerApiVersionInterceptorIntegrationTest { private final static String CATALOG_PATH = "/v2/catalog"; private MockMvc mockMvc; @InjectMocks private CatalogController controller; @Mock
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java // @RestController // @Slf4j // public class CatalogController extends BaseController { // @Autowired // public CatalogController(CatalogService service) { // super(service); // } // // @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET) // public Catalog getCatalog() { // log.debug("getCatalog()"); // return catalogService.getCatalog(); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorIntegrationTest.java import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.cloud.servicebroker.controller.CatalogController; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.service.CatalogService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; package org.springframework.cloud.servicebroker.interceptor; @RunWith(MockitoJUnitRunner.class) public class BrokerApiVersionInterceptorIntegrationTest { private final static String CATALOG_PATH = "/v2/catalog"; private MockMvc mockMvc; @InjectMocks private CatalogController controller; @Mock
private CatalogService catalogService;
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorIntegrationTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java // @RestController // @Slf4j // public class CatalogController extends BaseController { // @Autowired // public CatalogController(CatalogService service) { // super(service); // } // // @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET) // public Catalog getCatalog() { // log.debug("getCatalog()"); // return catalogService.getCatalog(); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // }
import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.cloud.servicebroker.controller.CatalogController; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.service.CatalogService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
package org.springframework.cloud.servicebroker.interceptor; @RunWith(MockitoJUnitRunner.class) public class BrokerApiVersionInterceptorIntegrationTest { private final static String CATALOG_PATH = "/v2/catalog"; private MockMvc mockMvc; @InjectMocks private CatalogController controller; @Mock private CatalogService catalogService; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(controller)
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java // @RestController // @Slf4j // public class CatalogController extends BaseController { // @Autowired // public CatalogController(CatalogService service) { // super(service); // } // // @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET) // public Catalog getCatalog() { // log.debug("getCatalog()"); // return catalogService.getCatalog(); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptorIntegrationTest.java import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.springframework.cloud.servicebroker.controller.CatalogController; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.cloud.servicebroker.service.CatalogService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; package org.springframework.cloud.servicebroker.interceptor; @RunWith(MockitoJUnitRunner.class) public class BrokerApiVersionInterceptorIntegrationTest { private final static String CATALOG_PATH = "/v2/catalog"; private MockMvc mockMvc; @InjectMocks private CatalogController controller; @Mock private CatalogService catalogService; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(controller)
.addInterceptors(new BrokerApiVersionInterceptor(new BrokerApiVersion("header", "expected-version")))
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptor.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/exception/ServiceBrokerApiVersionException.java // public class ServiceBrokerApiVersionException extends RuntimeException { // // private static final long serialVersionUID = -6792404679608443775L; // // public ServiceBrokerApiVersionException(String expectedVersion, String providedVersion) { // super("The provided service broker API version is not supported: " // + "expected version=" + expectedVersion // + ", provided version = " + providedVersion); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.cloud.servicebroker.exception.ServiceBrokerApiVersionException; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
package org.springframework.cloud.servicebroker.interceptor; public class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter { private final BrokerApiVersion version; public BrokerApiVersionInterceptor() { this(null); } public BrokerApiVersionInterceptor(BrokerApiVersion version) { this.version = version; } public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/exception/ServiceBrokerApiVersionException.java // public class ServiceBrokerApiVersionException extends RuntimeException { // // private static final long serialVersionUID = -6792404679608443775L; // // public ServiceBrokerApiVersionException(String expectedVersion, String providedVersion) { // super("The provided service broker API version is not supported: " // + "expected version=" + expectedVersion // + ", provided version = " + providedVersion); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/BrokerApiVersion.java // @Getter // @ToString // @EqualsAndHashCode // public class BrokerApiVersion { // // public final static String DEFAULT_API_VERSION_HEADER = "X-Broker-Api-Version"; // public final static String API_VERSION_ANY = "*"; // public final static String API_VERSION_CURRENT = "2.8"; // // /** // * The name of the HTTP header field expected to contain the API version of the service broker client. // */ // private final String brokerApiVersionHeader; // // /** // * The version of the broker API supported by the broker. A value of <code>null</code> or // * <code>API_VERSION_ANY</code> will disable API version validation. // */ // private final String apiVersion; // // public BrokerApiVersion(String brokerApiVersionHeader, String apiVersion) { // this.brokerApiVersionHeader = brokerApiVersionHeader; // this.apiVersion = apiVersion; // } // // public BrokerApiVersion(String apiVersion) { // this(DEFAULT_API_VERSION_HEADER, apiVersion); // } // // public BrokerApiVersion() { // this(DEFAULT_API_VERSION_HEADER, API_VERSION_ANY); // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/interceptor/BrokerApiVersionInterceptor.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.cloud.servicebroker.exception.ServiceBrokerApiVersionException; import org.springframework.cloud.servicebroker.model.BrokerApiVersion; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; package org.springframework.cloud.servicebroker.interceptor; public class BrokerApiVersionInterceptor extends HandlerInterceptorAdapter { private final BrokerApiVersion version; public BrokerApiVersionInterceptor() { this(null); } public BrokerApiVersionInterceptor(BrokerApiVersion version) { this.version = version; } public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws ServiceBrokerApiVersionException {
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/controller/ControllerIntegrationTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/ServiceFixture.java // public class ServiceFixture { // // public static ServiceDefinition getSimpleService() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // PlanFixture.getAllPlans()); // } // // public static ServiceDefinition getServiceWithRequires() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // true, // PlanFixture.getAllPlans(), // null, // null, // Arrays.asList( // ServiceDefinitionRequires.SERVICE_REQUIRES_SYSLOG_DRAIN.toString(), // ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString() // ), // null); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // }
import org.springframework.cloud.servicebroker.model.fixture.ServiceFixture; import org.springframework.cloud.servicebroker.service.CatalogService; import org.mockito.Mock; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when;
package org.springframework.cloud.servicebroker.controller; public abstract class ControllerIntegrationTest { @Mock
// Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/ServiceFixture.java // public class ServiceFixture { // // public static ServiceDefinition getSimpleService() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // PlanFixture.getAllPlans()); // } // // public static ServiceDefinition getServiceWithRequires() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // true, // PlanFixture.getAllPlans(), // null, // null, // Arrays.asList( // ServiceDefinitionRequires.SERVICE_REQUIRES_SYSLOG_DRAIN.toString(), // ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString() // ), // null); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/controller/ControllerIntegrationTest.java import org.springframework.cloud.servicebroker.model.fixture.ServiceFixture; import org.springframework.cloud.servicebroker.service.CatalogService; import org.mockito.Mock; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; package org.springframework.cloud.servicebroker.controller; public abstract class ControllerIntegrationTest { @Mock
protected CatalogService catalogService;
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/controller/ControllerIntegrationTest.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/ServiceFixture.java // public class ServiceFixture { // // public static ServiceDefinition getSimpleService() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // PlanFixture.getAllPlans()); // } // // public static ServiceDefinition getServiceWithRequires() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // true, // PlanFixture.getAllPlans(), // null, // null, // Arrays.asList( // ServiceDefinitionRequires.SERVICE_REQUIRES_SYSLOG_DRAIN.toString(), // ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString() // ), // null); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // }
import org.springframework.cloud.servicebroker.model.fixture.ServiceFixture; import org.springframework.cloud.servicebroker.service.CatalogService; import org.mockito.Mock; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when;
package org.springframework.cloud.servicebroker.controller; public abstract class ControllerIntegrationTest { @Mock protected CatalogService catalogService; protected void setupCatalogService(String serviceDefinitionId) { when(catalogService.getServiceDefinition(eq(serviceDefinitionId)))
// Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/ServiceFixture.java // public class ServiceFixture { // // public static ServiceDefinition getSimpleService() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // PlanFixture.getAllPlans()); // } // // public static ServiceDefinition getServiceWithRequires() { // return new ServiceDefinition( // "service-one-id", // "Service One", // "Description for Service One", // true, // true, // PlanFixture.getAllPlans(), // null, // null, // Arrays.asList( // ServiceDefinitionRequires.SERVICE_REQUIRES_SYSLOG_DRAIN.toString(), // ServiceDefinitionRequires.SERVICE_REQUIRES_ROUTE_FORWARDING.toString() // ), // null); // } // // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/controller/ControllerIntegrationTest.java import org.springframework.cloud.servicebroker.model.fixture.ServiceFixture; import org.springframework.cloud.servicebroker.service.CatalogService; import org.mockito.Mock; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; package org.springframework.cloud.servicebroker.controller; public abstract class ControllerIntegrationTest { @Mock protected CatalogService catalogService; protected void setupCatalogService(String serviceDefinitionId) { when(catalogService.getServiceDefinition(eq(serviceDefinitionId)))
.thenReturn(ServiceFixture.getSimpleService());
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // }
import java.util.HashMap; import java.util.Map; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.beans.factory.annotation.Autowired;
package org.springframework.cloud.servicebroker.service; /** * An implementation of the CatalogService that allows the Catalog to be specified as a Spring Bean. * * @author sgreenberg@pivotal.io */ public class BeanCatalogService implements CatalogService { private Catalog catalog;
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/BeanCatalogService.java import java.util.HashMap; import java.util.Map; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import org.springframework.beans.factory.annotation.Autowired; package org.springframework.cloud.servicebroker.service; /** * An implementation of the CatalogService that allows the Catalog to be specified as a Spring Bean. * * @author sgreenberg@pivotal.io */ public class BeanCatalogService implements CatalogService { private Catalog catalog;
private Map<String,ServiceDefinition> serviceDefs = new HashMap<String,ServiceDefinition>();
dflick-pivotal/sentimentr-release
src/sentimentr-service/src/main/java/io/pivotal/fe/sentiment/SentimentAnayticsServiceApplication.java
// Path: src/sentimentr-service/src/main/java/io/pivotal/fe/sentiment/engine/NLP.java // public class NLP { // static StanfordCoreNLP pipeline; // // public static void init() { // pipeline = new StanfordCoreNLP("nlp.properties"); // } // // public static int findSentiment(String text) { // // int mainSentiment = 0; // if (text != null && text.length() > 0) { // int longest = 0; // Annotation annotation = pipeline.process(text); // for (CoreMap sentence : annotation // .get(CoreAnnotations.SentencesAnnotation.class)) { // Tree tree = sentence // .get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // String partText = sentence.toString(); // if (partText.length() > longest) { // mainSentiment = sentiment; // longest = partText.length(); // } // // } // } // return mainSentiment; // } // }
import io.pivotal.fe.sentiment.engine.NLP; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
package io.pivotal.fe.sentiment; @SpringBootApplication @RestController public class SentimentAnayticsServiceApplication { @RequestMapping("/env") public Map<String,Object> env(HttpServletRequest request) { Map<String,Object> model = new HashMap<String,Object>(); model.put("ip", request.getLocalAddr()); model.put("port", request.getLocalPort()); return model; } @RequestMapping("/sentiment/{text}") public Map<String,Object> sentiment(@PathVariable String text, HttpServletRequest request) {
// Path: src/sentimentr-service/src/main/java/io/pivotal/fe/sentiment/engine/NLP.java // public class NLP { // static StanfordCoreNLP pipeline; // // public static void init() { // pipeline = new StanfordCoreNLP("nlp.properties"); // } // // public static int findSentiment(String text) { // // int mainSentiment = 0; // if (text != null && text.length() > 0) { // int longest = 0; // Annotation annotation = pipeline.process(text); // for (CoreMap sentence : annotation // .get(CoreAnnotations.SentencesAnnotation.class)) { // Tree tree = sentence // .get(SentimentCoreAnnotations.AnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // String partText = sentence.toString(); // if (partText.length() > longest) { // mainSentiment = sentiment; // longest = partText.length(); // } // // } // } // return mainSentiment; // } // } // Path: src/sentimentr-service/src/main/java/io/pivotal/fe/sentiment/SentimentAnayticsServiceApplication.java import io.pivotal.fe.sentiment.engine.NLP; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; package io.pivotal.fe.sentiment; @SpringBootApplication @RestController public class SentimentAnayticsServiceApplication { @RequestMapping("/env") public Map<String,Object> env(HttpServletRequest request) { Map<String,Object> model = new HashMap<String,Object>(); model.put("ip", request.getLocalAddr()); model.put("port", request.getLocalPort()); return model; } @RequestMapping("/sentiment/{text}") public Map<String,Object> sentiment(@PathVariable String text, HttpServletRequest request) {
int sentiment = NLP.findSentiment(text);
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/CatalogFixture.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // }
import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import java.util.Collections; import java.util.List;
package org.springframework.cloud.servicebroker.model.fixture; public class CatalogFixture { public static Catalog getCatalog() {
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/ServiceDefinition.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class ServiceDefinition { // /** // * An identifier used to correlate this service in future requests to the catalog. This must be unique within // * a Cloud Foundry deployment. Using a GUID is recommended. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("id") // private String id; // // /** // * A CLI-friendly name of the service that will appear in the catalog. The value should be all lowercase, // * with no spaces. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("name") // private String name; // // /** // * A user-friendly short description of the service that will appear in the catalog. // */ // @NotEmpty // @JsonSerialize // @JsonProperty("description") // private String description; // // /** // * Indicates whether the service can be bound to applications. // */ // @JsonSerialize // @JsonProperty("bindable") // private boolean bindable; // // /** // * Indicates whether the service supports requests to update instances to use a different plan from the one // * used to provision a service instance. // */ // @JsonSerialize // @JsonProperty("plan_updateable") // private boolean planUpdateable; // // /** // * A list of plans for this service. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("plans") // private List<Plan> plans; // // /** // * A list of tags to aid in categorizing and classifying services with similar characteristics. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("tags") // private List<String> tags; // // /** // * A map of metadata to further describe a service offering. // */ // @JsonSerialize(nullsUsing = EmptyMapSerializer.class) // @JsonProperty("metadata") // private Map<String, Object> metadata; // // /** // * A list of permissions that the user would have to give the service, if they provision it. See // * {@link ServiceDefinitionRequires} for supported permissions. // */ // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("requires") // private List<String> requires; // // /** // * Data necessary to activate the Dashboard SSO feature for this service. // */ // @JsonSerialize // @JsonProperty("dashboard_client") // private DashboardClient dashboardClient; // // public ServiceDefinition() { // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, List<Plan> plans) { // this.id = id; // this.name = name; // this.description = description; // this.bindable = bindable; // this.plans = plans; // } // // public ServiceDefinition(String id, String name, String description, boolean bindable, boolean planUpdateable, // List<Plan> plans, List<String> tags, Map<String, Object> metadata, List<String> requires, // DashboardClient dashboardClient) { // this(id, name, description, bindable, plans); // this.tags = tags; // this.metadata = metadata; // this.requires = requires; // this.planUpdateable = planUpdateable; // this.dashboardClient = dashboardClient; // } // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/test/java/org/springframework/cloud/servicebroker/model/fixture/CatalogFixture.java import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.model.ServiceDefinition; import java.util.Collections; import java.util.List; package org.springframework.cloud.servicebroker.model.fixture; public class CatalogFixture { public static Catalog getCatalog() {
List<ServiceDefinition> services = Collections.singletonList(ServiceFixture.getSimpleService());
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // }
import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
package org.springframework.cloud.servicebroker.controller; /** * See: http://docs.cloudfoundry.org/services/api.html * * @author sgreenberg@pivotal.io * @author Scott Frederick */ @RestController @Slf4j public class CatalogController extends BaseController { @Autowired
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; package org.springframework.cloud.servicebroker.controller; /** * See: http://docs.cloudfoundry.org/services/api.html * * @author sgreenberg@pivotal.io * @author Scott Frederick */ @RestController @Slf4j public class CatalogController extends BaseController { @Autowired
public CatalogController(CatalogService service) {
dflick-pivotal/sentimentr-release
src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // }
import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;
package org.springframework.cloud.servicebroker.controller; /** * See: http://docs.cloudfoundry.org/services/api.html * * @author sgreenberg@pivotal.io * @author Scott Frederick */ @RestController @Slf4j public class CatalogController extends BaseController { @Autowired public CatalogController(CatalogService service) { super(service); } @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET)
// Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/model/Catalog.java // @Getter // @ToString // @EqualsAndHashCode // @JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE) // @JsonIgnoreProperties(ignoreUnknown = true) // public class Catalog { // // /** // * A list of service offerings provided by the service broker. // */ // @NotEmpty // @JsonSerialize(nullsUsing = EmptyListSerializer.class) // @JsonProperty("services") // private final List<ServiceDefinition> serviceDefinitions; // // public Catalog() { // this.serviceDefinitions = null; // } // // public Catalog(List<ServiceDefinition> serviceDefinitions) { // this.serviceDefinitions = serviceDefinitions; // } // } // // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/service/CatalogService.java // public interface CatalogService { // // /** // * Return the catalog of services provided by the service broker. // * // * @return the catalog of services // */ // Catalog getCatalog(); // // /** // * Get a service definition from the catalog by ID. // * // * @param serviceId The ID of the service definition in the catalog // * @return the service definition, or null if it doesn't exist // */ // ServiceDefinition getServiceDefinition(String serviceId); // // } // Path: src/spring-cloud-cloudfoundry-service-broker/src/main/java/org/springframework/cloud/servicebroker/controller/CatalogController.java import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.servicebroker.model.Catalog; import org.springframework.cloud.servicebroker.service.CatalogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; package org.springframework.cloud.servicebroker.controller; /** * See: http://docs.cloudfoundry.org/services/api.html * * @author sgreenberg@pivotal.io * @author Scott Frederick */ @RestController @Slf4j public class CatalogController extends BaseController { @Autowired public CatalogController(CatalogService service) { super(service); } @RequestMapping(value = "/v2/catalog", method = RequestMethod.GET)
public Catalog getCatalog() {
guardianproject/gnupg-for-android
src/info/guardianproject/gpg/KeyserverLoader.java
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class InsufficientQuery extends Exception { // private static final long serialVersionUID = 2703768928624654514L; // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class QueryException extends Exception { // private static final long serialVersionUID = 2703768928624654512L; // // public QueryException(String message) { // super(message); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class TooManyResponses extends Exception { // private static final long serialVersionUID = 2703768928624654513L; // }
import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.openintents.openpgp.keyserver.HkpKeyServer; import org.openintents.openpgp.keyserver.KeyServer.InsufficientQuery; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import org.openintents.openpgp.keyserver.KeyServer.QueryException; import org.openintents.openpgp.keyserver.KeyServer.TooManyResponses; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.AsyncTaskLoader; import android.text.TextUtils;
@Override public int compare(KeyInfo object1, KeyInfo object2) { return sCollator.compare(object1.userIds.get(0), object2.userIds.get(0)); } }; public KeyserverLoader(Context context) { super(context); mContext = context; } @Override public void onStartLoading() { mSearchString = MainActivity.mCurrentSearchString; } @Override public KeyserverResult<List<KeyInfo>> loadInBackground() { KeyserverResult<List<KeyInfo>> result = new KeyserverResult<List<KeyInfo>>(); try { if(TextUtils.isEmpty(mSearchString)) return result; // nothing to do... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER, "ipv4.pool.sks-keyservers.net"); HkpKeyServer keyserver = new HkpKeyServer(host); ArrayList<KeyInfo> data = keyserver.search(mSearchString); Collections.sort(data, ALPHA_COMPARATOR); result.setData(data);
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class InsufficientQuery extends Exception { // private static final long serialVersionUID = 2703768928624654514L; // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class QueryException extends Exception { // private static final long serialVersionUID = 2703768928624654512L; // // public QueryException(String message) { // super(message); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class TooManyResponses extends Exception { // private static final long serialVersionUID = 2703768928624654513L; // } // Path: src/info/guardianproject/gpg/KeyserverLoader.java import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.openintents.openpgp.keyserver.HkpKeyServer; import org.openintents.openpgp.keyserver.KeyServer.InsufficientQuery; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import org.openintents.openpgp.keyserver.KeyServer.QueryException; import org.openintents.openpgp.keyserver.KeyServer.TooManyResponses; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.AsyncTaskLoader; import android.text.TextUtils; @Override public int compare(KeyInfo object1, KeyInfo object2) { return sCollator.compare(object1.userIds.get(0), object2.userIds.get(0)); } }; public KeyserverLoader(Context context) { super(context); mContext = context; } @Override public void onStartLoading() { mSearchString = MainActivity.mCurrentSearchString; } @Override public KeyserverResult<List<KeyInfo>> loadInBackground() { KeyserverResult<List<KeyInfo>> result = new KeyserverResult<List<KeyInfo>>(); try { if(TextUtils.isEmpty(mSearchString)) return result; // nothing to do... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER, "ipv4.pool.sks-keyservers.net"); HkpKeyServer keyserver = new HkpKeyServer(host); ArrayList<KeyInfo> data = keyserver.search(mSearchString); Collections.sort(data, ALPHA_COMPARATOR); result.setData(data);
} catch (QueryException e) {
guardianproject/gnupg-for-android
src/info/guardianproject/gpg/KeyserverLoader.java
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class InsufficientQuery extends Exception { // private static final long serialVersionUID = 2703768928624654514L; // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class QueryException extends Exception { // private static final long serialVersionUID = 2703768928624654512L; // // public QueryException(String message) { // super(message); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class TooManyResponses extends Exception { // private static final long serialVersionUID = 2703768928624654513L; // }
import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.openintents.openpgp.keyserver.HkpKeyServer; import org.openintents.openpgp.keyserver.KeyServer.InsufficientQuery; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import org.openintents.openpgp.keyserver.KeyServer.QueryException; import org.openintents.openpgp.keyserver.KeyServer.TooManyResponses; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.AsyncTaskLoader; import android.text.TextUtils;
return sCollator.compare(object1.userIds.get(0), object2.userIds.get(0)); } }; public KeyserverLoader(Context context) { super(context); mContext = context; } @Override public void onStartLoading() { mSearchString = MainActivity.mCurrentSearchString; } @Override public KeyserverResult<List<KeyInfo>> loadInBackground() { KeyserverResult<List<KeyInfo>> result = new KeyserverResult<List<KeyInfo>>(); try { if(TextUtils.isEmpty(mSearchString)) return result; // nothing to do... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER, "ipv4.pool.sks-keyservers.net"); HkpKeyServer keyserver = new HkpKeyServer(host); ArrayList<KeyInfo> data = keyserver.search(mSearchString); Collections.sort(data, ALPHA_COMPARATOR); result.setData(data); } catch (QueryException e) { result.setErrorResid(R.string.error_query_failed); e.printStackTrace();
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class InsufficientQuery extends Exception { // private static final long serialVersionUID = 2703768928624654514L; // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class QueryException extends Exception { // private static final long serialVersionUID = 2703768928624654512L; // // public QueryException(String message) { // super(message); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class TooManyResponses extends Exception { // private static final long serialVersionUID = 2703768928624654513L; // } // Path: src/info/guardianproject/gpg/KeyserverLoader.java import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.openintents.openpgp.keyserver.HkpKeyServer; import org.openintents.openpgp.keyserver.KeyServer.InsufficientQuery; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import org.openintents.openpgp.keyserver.KeyServer.QueryException; import org.openintents.openpgp.keyserver.KeyServer.TooManyResponses; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.AsyncTaskLoader; import android.text.TextUtils; return sCollator.compare(object1.userIds.get(0), object2.userIds.get(0)); } }; public KeyserverLoader(Context context) { super(context); mContext = context; } @Override public void onStartLoading() { mSearchString = MainActivity.mCurrentSearchString; } @Override public KeyserverResult<List<KeyInfo>> loadInBackground() { KeyserverResult<List<KeyInfo>> result = new KeyserverResult<List<KeyInfo>>(); try { if(TextUtils.isEmpty(mSearchString)) return result; // nothing to do... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER, "ipv4.pool.sks-keyservers.net"); HkpKeyServer keyserver = new HkpKeyServer(host); ArrayList<KeyInfo> data = keyserver.search(mSearchString); Collections.sort(data, ALPHA_COMPARATOR); result.setData(data); } catch (QueryException e) { result.setErrorResid(R.string.error_query_failed); e.printStackTrace();
} catch (TooManyResponses e) {
guardianproject/gnupg-for-android
src/info/guardianproject/gpg/KeyserverLoader.java
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class InsufficientQuery extends Exception { // private static final long serialVersionUID = 2703768928624654514L; // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class QueryException extends Exception { // private static final long serialVersionUID = 2703768928624654512L; // // public QueryException(String message) { // super(message); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class TooManyResponses extends Exception { // private static final long serialVersionUID = 2703768928624654513L; // }
import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.openintents.openpgp.keyserver.HkpKeyServer; import org.openintents.openpgp.keyserver.KeyServer.InsufficientQuery; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import org.openintents.openpgp.keyserver.KeyServer.QueryException; import org.openintents.openpgp.keyserver.KeyServer.TooManyResponses; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.AsyncTaskLoader; import android.text.TextUtils;
public KeyserverLoader(Context context) { super(context); mContext = context; } @Override public void onStartLoading() { mSearchString = MainActivity.mCurrentSearchString; } @Override public KeyserverResult<List<KeyInfo>> loadInBackground() { KeyserverResult<List<KeyInfo>> result = new KeyserverResult<List<KeyInfo>>(); try { if(TextUtils.isEmpty(mSearchString)) return result; // nothing to do... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER, "ipv4.pool.sks-keyservers.net"); HkpKeyServer keyserver = new HkpKeyServer(host); ArrayList<KeyInfo> data = keyserver.search(mSearchString); Collections.sort(data, ALPHA_COMPARATOR); result.setData(data); } catch (QueryException e) { result.setErrorResid(R.string.error_query_failed); e.printStackTrace(); } catch (TooManyResponses e) { result.setErrorResid(R.string.error_too_many_responses); e.printStackTrace();
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class InsufficientQuery extends Exception { // private static final long serialVersionUID = 2703768928624654514L; // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class QueryException extends Exception { // private static final long serialVersionUID = 2703768928624654512L; // // public QueryException(String message) { // super(message); // } // } // // Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class TooManyResponses extends Exception { // private static final long serialVersionUID = 2703768928624654513L; // } // Path: src/info/guardianproject/gpg/KeyserverLoader.java import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.openintents.openpgp.keyserver.HkpKeyServer; import org.openintents.openpgp.keyserver.KeyServer.InsufficientQuery; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import org.openintents.openpgp.keyserver.KeyServer.QueryException; import org.openintents.openpgp.keyserver.KeyServer.TooManyResponses; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.AsyncTaskLoader; import android.text.TextUtils; public KeyserverLoader(Context context) { super(context); mContext = context; } @Override public void onStartLoading() { mSearchString = MainActivity.mCurrentSearchString; } @Override public KeyserverResult<List<KeyInfo>> loadInBackground() { KeyserverResult<List<KeyInfo>> result = new KeyserverResult<List<KeyInfo>>(); try { if(TextUtils.isEmpty(mSearchString)) return result; // nothing to do... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); String host = prefs.getString(GpgPreferenceActivity.PREF_KEYSERVER, "ipv4.pool.sks-keyservers.net"); HkpKeyServer keyserver = new HkpKeyServer(host); ArrayList<KeyInfo> data = keyserver.search(mSearchString); Collections.sort(data, ALPHA_COMPARATOR); result.setData(data); } catch (QueryException e) { result.setErrorResid(R.string.error_query_failed); e.printStackTrace(); } catch (TooManyResponses e) { result.setErrorResid(R.string.error_too_many_responses); e.printStackTrace();
} catch (InsufficientQuery e) {
guardianproject/gnupg-for-android
tests/src/info/guardianproject/gpg/test/RawGpgContactTests.java
// Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public class RawGpgContact { // // public final String name; // public final String email; // public final String comment; // public final String keyID; // public final String fingerprint; // public final int flags; // public final boolean canEncrypt; // public final boolean canSign; // public final boolean hasSecretKey; // public final boolean isDisabled; // public final boolean isExpired; // public final boolean isInvalid; // public final boolean isQualified; // public final boolean isRevoked; // public final boolean isSecret; // public final long rawContactId; // public final boolean deleted; // // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // // public static List<RawGpgContact> fromPublicKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listKeys()); // } // // public static List<RawGpgContact> fromSecretKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listSecretKeys()); // } // // private static List<RawGpgContact> getGnuPGKeysAsRawGpgContacts(GnuPGKey[] keys) { // if (keys == null) // return new ArrayList<RawGpgContact>(); // ArrayList<RawGpgContact> list = new ArrayList<RawGpgContact>(keys.length); // for (GnuPGKey key : keys) { // list.add(new RawGpgContact(key)); // } // return list; // } // // public RawGpgContact(GnuPGKey key) { // super(); // this.name = key.getName(); // this.email = key.getEmail(); // this.comment = key.getComment(); // this.fingerprint = key.getFingerprint(); // this.keyID = key.getKeyID(); // this.canEncrypt = key.canEncrypt(); // this.canSign = key.canSign(); // this.hasSecretKey = key.hasSecretKey(); // this.isDisabled = key.isDisabled(); // this.isExpired = key.isExpired(); // this.isInvalid = key.isInvalid(); // this.isQualified = key.isQualified(); // this.isRevoked = key.isRevoked(); // this.isSecret = key.isSecret(); // this.flags = (this.canEncrypt ? 1 << KeyFlags.canEncrypt : 0) // + (this.canSign ? 1 << KeyFlags.canSign : 0) // + (this.hasSecretKey ? 1 << KeyFlags.hasSecretKey : 0) // + (this.isDisabled ? 1 << KeyFlags.isDisabled : 0) // + (this.isExpired ? 1 << KeyFlags.isExpired : 0) // + (this.isInvalid ? 1 << KeyFlags.isInvalid : 0) // + (this.isQualified ? 1 << KeyFlags.isQualified : 0) // + (this.isRevoked ? 1 << KeyFlags.isRevoked : 0) // + (this.isSecret ? 1 << KeyFlags.isSecret : 0); // this.rawContactId = 0; // this.deleted = false; // } // // public RawGpgContact(String name, String email, String comment, String fingerprint, // int flags, long rawContactId, boolean deleted) { // super(); // this.name = name; // this.email = email; // this.comment = comment; // this.fingerprint = fingerprint; // this.keyID = fingerprint.substring(fingerprint.length() - 16); // this.flags = flags; // this.canEncrypt = (flags >> KeyFlags.canEncrypt & 1) != 0; // this.canSign = (flags >> KeyFlags.canSign & 1) != 0; // this.hasSecretKey = (flags >> KeyFlags.hasSecretKey & 1) != 0; // this.isDisabled = (flags >> KeyFlags.isDisabled & 1) != 0; // this.isExpired = (flags >> KeyFlags.isExpired & 1) != 0; // this.isInvalid = (flags >> KeyFlags.isInvalid & 1) != 0; // this.isQualified = (flags >> KeyFlags.isQualified & 1) != 0; // this.isRevoked = (flags >> KeyFlags.isRevoked & 1) != 0; // this.isSecret = (flags >> KeyFlags.isSecret & 1) != 0; // this.rawContactId = rawContactId; // this.deleted = deleted; // } // } // // Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // }
import info.guardianproject.gpg.NativeHelper; import info.guardianproject.gpg.sync.RawGpgContact; import info.guardianproject.gpg.sync.RawGpgContact.KeyFlags; import android.test.AndroidTestCase; import android.util.Log;
package info.guardianproject.gpg.test; public class RawGpgContactTests extends AndroidTestCase { public static final String TAG = "RawGpgContactTests"; protected void setUp() throws Exception { Log.i(TAG, "setUp"); super.setUp(); NativeHelper.setup(getContext()); } protected void tearDown() throws Exception { Log.i(TAG, "tearDown"); super.tearDown(); } public void testFlags() {
// Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public class RawGpgContact { // // public final String name; // public final String email; // public final String comment; // public final String keyID; // public final String fingerprint; // public final int flags; // public final boolean canEncrypt; // public final boolean canSign; // public final boolean hasSecretKey; // public final boolean isDisabled; // public final boolean isExpired; // public final boolean isInvalid; // public final boolean isQualified; // public final boolean isRevoked; // public final boolean isSecret; // public final long rawContactId; // public final boolean deleted; // // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // // public static List<RawGpgContact> fromPublicKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listKeys()); // } // // public static List<RawGpgContact> fromSecretKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listSecretKeys()); // } // // private static List<RawGpgContact> getGnuPGKeysAsRawGpgContacts(GnuPGKey[] keys) { // if (keys == null) // return new ArrayList<RawGpgContact>(); // ArrayList<RawGpgContact> list = new ArrayList<RawGpgContact>(keys.length); // for (GnuPGKey key : keys) { // list.add(new RawGpgContact(key)); // } // return list; // } // // public RawGpgContact(GnuPGKey key) { // super(); // this.name = key.getName(); // this.email = key.getEmail(); // this.comment = key.getComment(); // this.fingerprint = key.getFingerprint(); // this.keyID = key.getKeyID(); // this.canEncrypt = key.canEncrypt(); // this.canSign = key.canSign(); // this.hasSecretKey = key.hasSecretKey(); // this.isDisabled = key.isDisabled(); // this.isExpired = key.isExpired(); // this.isInvalid = key.isInvalid(); // this.isQualified = key.isQualified(); // this.isRevoked = key.isRevoked(); // this.isSecret = key.isSecret(); // this.flags = (this.canEncrypt ? 1 << KeyFlags.canEncrypt : 0) // + (this.canSign ? 1 << KeyFlags.canSign : 0) // + (this.hasSecretKey ? 1 << KeyFlags.hasSecretKey : 0) // + (this.isDisabled ? 1 << KeyFlags.isDisabled : 0) // + (this.isExpired ? 1 << KeyFlags.isExpired : 0) // + (this.isInvalid ? 1 << KeyFlags.isInvalid : 0) // + (this.isQualified ? 1 << KeyFlags.isQualified : 0) // + (this.isRevoked ? 1 << KeyFlags.isRevoked : 0) // + (this.isSecret ? 1 << KeyFlags.isSecret : 0); // this.rawContactId = 0; // this.deleted = false; // } // // public RawGpgContact(String name, String email, String comment, String fingerprint, // int flags, long rawContactId, boolean deleted) { // super(); // this.name = name; // this.email = email; // this.comment = comment; // this.fingerprint = fingerprint; // this.keyID = fingerprint.substring(fingerprint.length() - 16); // this.flags = flags; // this.canEncrypt = (flags >> KeyFlags.canEncrypt & 1) != 0; // this.canSign = (flags >> KeyFlags.canSign & 1) != 0; // this.hasSecretKey = (flags >> KeyFlags.hasSecretKey & 1) != 0; // this.isDisabled = (flags >> KeyFlags.isDisabled & 1) != 0; // this.isExpired = (flags >> KeyFlags.isExpired & 1) != 0; // this.isInvalid = (flags >> KeyFlags.isInvalid & 1) != 0; // this.isQualified = (flags >> KeyFlags.isQualified & 1) != 0; // this.isRevoked = (flags >> KeyFlags.isRevoked & 1) != 0; // this.isSecret = (flags >> KeyFlags.isSecret & 1) != 0; // this.rawContactId = rawContactId; // this.deleted = deleted; // } // } // // Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // Path: tests/src/info/guardianproject/gpg/test/RawGpgContactTests.java import info.guardianproject.gpg.NativeHelper; import info.guardianproject.gpg.sync.RawGpgContact; import info.guardianproject.gpg.sync.RawGpgContact.KeyFlags; import android.test.AndroidTestCase; import android.util.Log; package info.guardianproject.gpg.test; public class RawGpgContactTests extends AndroidTestCase { public static final String TAG = "RawGpgContactTests"; protected void setUp() throws Exception { Log.i(TAG, "setUp"); super.setUp(); NativeHelper.setup(getContext()); } protected void tearDown() throws Exception { Log.i(TAG, "tearDown"); super.tearDown(); } public void testFlags() {
RawGpgContact first, second;
guardianproject/gnupg-for-android
tests/src/info/guardianproject/gpg/test/RawGpgContactTests.java
// Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public class RawGpgContact { // // public final String name; // public final String email; // public final String comment; // public final String keyID; // public final String fingerprint; // public final int flags; // public final boolean canEncrypt; // public final boolean canSign; // public final boolean hasSecretKey; // public final boolean isDisabled; // public final boolean isExpired; // public final boolean isInvalid; // public final boolean isQualified; // public final boolean isRevoked; // public final boolean isSecret; // public final long rawContactId; // public final boolean deleted; // // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // // public static List<RawGpgContact> fromPublicKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listKeys()); // } // // public static List<RawGpgContact> fromSecretKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listSecretKeys()); // } // // private static List<RawGpgContact> getGnuPGKeysAsRawGpgContacts(GnuPGKey[] keys) { // if (keys == null) // return new ArrayList<RawGpgContact>(); // ArrayList<RawGpgContact> list = new ArrayList<RawGpgContact>(keys.length); // for (GnuPGKey key : keys) { // list.add(new RawGpgContact(key)); // } // return list; // } // // public RawGpgContact(GnuPGKey key) { // super(); // this.name = key.getName(); // this.email = key.getEmail(); // this.comment = key.getComment(); // this.fingerprint = key.getFingerprint(); // this.keyID = key.getKeyID(); // this.canEncrypt = key.canEncrypt(); // this.canSign = key.canSign(); // this.hasSecretKey = key.hasSecretKey(); // this.isDisabled = key.isDisabled(); // this.isExpired = key.isExpired(); // this.isInvalid = key.isInvalid(); // this.isQualified = key.isQualified(); // this.isRevoked = key.isRevoked(); // this.isSecret = key.isSecret(); // this.flags = (this.canEncrypt ? 1 << KeyFlags.canEncrypt : 0) // + (this.canSign ? 1 << KeyFlags.canSign : 0) // + (this.hasSecretKey ? 1 << KeyFlags.hasSecretKey : 0) // + (this.isDisabled ? 1 << KeyFlags.isDisabled : 0) // + (this.isExpired ? 1 << KeyFlags.isExpired : 0) // + (this.isInvalid ? 1 << KeyFlags.isInvalid : 0) // + (this.isQualified ? 1 << KeyFlags.isQualified : 0) // + (this.isRevoked ? 1 << KeyFlags.isRevoked : 0) // + (this.isSecret ? 1 << KeyFlags.isSecret : 0); // this.rawContactId = 0; // this.deleted = false; // } // // public RawGpgContact(String name, String email, String comment, String fingerprint, // int flags, long rawContactId, boolean deleted) { // super(); // this.name = name; // this.email = email; // this.comment = comment; // this.fingerprint = fingerprint; // this.keyID = fingerprint.substring(fingerprint.length() - 16); // this.flags = flags; // this.canEncrypt = (flags >> KeyFlags.canEncrypt & 1) != 0; // this.canSign = (flags >> KeyFlags.canSign & 1) != 0; // this.hasSecretKey = (flags >> KeyFlags.hasSecretKey & 1) != 0; // this.isDisabled = (flags >> KeyFlags.isDisabled & 1) != 0; // this.isExpired = (flags >> KeyFlags.isExpired & 1) != 0; // this.isInvalid = (flags >> KeyFlags.isInvalid & 1) != 0; // this.isQualified = (flags >> KeyFlags.isQualified & 1) != 0; // this.isRevoked = (flags >> KeyFlags.isRevoked & 1) != 0; // this.isSecret = (flags >> KeyFlags.isSecret & 1) != 0; // this.rawContactId = rawContactId; // this.deleted = deleted; // } // } // // Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // }
import info.guardianproject.gpg.NativeHelper; import info.guardianproject.gpg.sync.RawGpgContact; import info.guardianproject.gpg.sync.RawGpgContact.KeyFlags; import android.test.AndroidTestCase; import android.util.Log;
package info.guardianproject.gpg.test; public class RawGpgContactTests extends AndroidTestCase { public static final String TAG = "RawGpgContactTests"; protected void setUp() throws Exception { Log.i(TAG, "setUp"); super.setUp(); NativeHelper.setup(getContext()); } protected void tearDown() throws Exception { Log.i(TAG, "tearDown"); super.tearDown(); } public void testFlags() { RawGpgContact first, second; for (int i = 0; i < 512; i++) { Log.v(TAG, "i = " + i); first = new RawGpgContact("Testy McTest", "test@test.com", "nothing to see here", "5E61C8780F86295CE17D86779F0FE587374BBE81", i, 0, false);
// Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public class RawGpgContact { // // public final String name; // public final String email; // public final String comment; // public final String keyID; // public final String fingerprint; // public final int flags; // public final boolean canEncrypt; // public final boolean canSign; // public final boolean hasSecretKey; // public final boolean isDisabled; // public final boolean isExpired; // public final boolean isInvalid; // public final boolean isQualified; // public final boolean isRevoked; // public final boolean isSecret; // public final long rawContactId; // public final boolean deleted; // // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // // public static List<RawGpgContact> fromPublicKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listKeys()); // } // // public static List<RawGpgContact> fromSecretKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listSecretKeys()); // } // // private static List<RawGpgContact> getGnuPGKeysAsRawGpgContacts(GnuPGKey[] keys) { // if (keys == null) // return new ArrayList<RawGpgContact>(); // ArrayList<RawGpgContact> list = new ArrayList<RawGpgContact>(keys.length); // for (GnuPGKey key : keys) { // list.add(new RawGpgContact(key)); // } // return list; // } // // public RawGpgContact(GnuPGKey key) { // super(); // this.name = key.getName(); // this.email = key.getEmail(); // this.comment = key.getComment(); // this.fingerprint = key.getFingerprint(); // this.keyID = key.getKeyID(); // this.canEncrypt = key.canEncrypt(); // this.canSign = key.canSign(); // this.hasSecretKey = key.hasSecretKey(); // this.isDisabled = key.isDisabled(); // this.isExpired = key.isExpired(); // this.isInvalid = key.isInvalid(); // this.isQualified = key.isQualified(); // this.isRevoked = key.isRevoked(); // this.isSecret = key.isSecret(); // this.flags = (this.canEncrypt ? 1 << KeyFlags.canEncrypt : 0) // + (this.canSign ? 1 << KeyFlags.canSign : 0) // + (this.hasSecretKey ? 1 << KeyFlags.hasSecretKey : 0) // + (this.isDisabled ? 1 << KeyFlags.isDisabled : 0) // + (this.isExpired ? 1 << KeyFlags.isExpired : 0) // + (this.isInvalid ? 1 << KeyFlags.isInvalid : 0) // + (this.isQualified ? 1 << KeyFlags.isQualified : 0) // + (this.isRevoked ? 1 << KeyFlags.isRevoked : 0) // + (this.isSecret ? 1 << KeyFlags.isSecret : 0); // this.rawContactId = 0; // this.deleted = false; // } // // public RawGpgContact(String name, String email, String comment, String fingerprint, // int flags, long rawContactId, boolean deleted) { // super(); // this.name = name; // this.email = email; // this.comment = comment; // this.fingerprint = fingerprint; // this.keyID = fingerprint.substring(fingerprint.length() - 16); // this.flags = flags; // this.canEncrypt = (flags >> KeyFlags.canEncrypt & 1) != 0; // this.canSign = (flags >> KeyFlags.canSign & 1) != 0; // this.hasSecretKey = (flags >> KeyFlags.hasSecretKey & 1) != 0; // this.isDisabled = (flags >> KeyFlags.isDisabled & 1) != 0; // this.isExpired = (flags >> KeyFlags.isExpired & 1) != 0; // this.isInvalid = (flags >> KeyFlags.isInvalid & 1) != 0; // this.isQualified = (flags >> KeyFlags.isQualified & 1) != 0; // this.isRevoked = (flags >> KeyFlags.isRevoked & 1) != 0; // this.isSecret = (flags >> KeyFlags.isSecret & 1) != 0; // this.rawContactId = rawContactId; // this.deleted = deleted; // } // } // // Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // Path: tests/src/info/guardianproject/gpg/test/RawGpgContactTests.java import info.guardianproject.gpg.NativeHelper; import info.guardianproject.gpg.sync.RawGpgContact; import info.guardianproject.gpg.sync.RawGpgContact.KeyFlags; import android.test.AndroidTestCase; import android.util.Log; package info.guardianproject.gpg.test; public class RawGpgContactTests extends AndroidTestCase { public static final String TAG = "RawGpgContactTests"; protected void setUp() throws Exception { Log.i(TAG, "setUp"); super.setUp(); NativeHelper.setup(getContext()); } protected void tearDown() throws Exception { Log.i(TAG, "tearDown"); super.tearDown(); } public void testFlags() { RawGpgContact first, second; for (int i = 0; i < 512; i++) { Log.v(TAG, "i = " + i); first = new RawGpgContact("Testy McTest", "test@test.com", "nothing to see here", "5E61C8780F86295CE17D86779F0FE587374BBE81", i, 0, false);
int flags = (first.canEncrypt ? 1 << KeyFlags.canEncrypt : 0)
guardianproject/gnupg-for-android
src/info/guardianproject/gpg/KeyListContactsAdapter.java
// Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public class RawGpgContact { // // public final String name; // public final String email; // public final String comment; // public final String keyID; // public final String fingerprint; // public final int flags; // public final boolean canEncrypt; // public final boolean canSign; // public final boolean hasSecretKey; // public final boolean isDisabled; // public final boolean isExpired; // public final boolean isInvalid; // public final boolean isQualified; // public final boolean isRevoked; // public final boolean isSecret; // public final long rawContactId; // public final boolean deleted; // // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // // public static List<RawGpgContact> fromPublicKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listKeys()); // } // // public static List<RawGpgContact> fromSecretKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listSecretKeys()); // } // // private static List<RawGpgContact> getGnuPGKeysAsRawGpgContacts(GnuPGKey[] keys) { // if (keys == null) // return new ArrayList<RawGpgContact>(); // ArrayList<RawGpgContact> list = new ArrayList<RawGpgContact>(keys.length); // for (GnuPGKey key : keys) { // list.add(new RawGpgContact(key)); // } // return list; // } // // public RawGpgContact(GnuPGKey key) { // super(); // this.name = key.getName(); // this.email = key.getEmail(); // this.comment = key.getComment(); // this.fingerprint = key.getFingerprint(); // this.keyID = key.getKeyID(); // this.canEncrypt = key.canEncrypt(); // this.canSign = key.canSign(); // this.hasSecretKey = key.hasSecretKey(); // this.isDisabled = key.isDisabled(); // this.isExpired = key.isExpired(); // this.isInvalid = key.isInvalid(); // this.isQualified = key.isQualified(); // this.isRevoked = key.isRevoked(); // this.isSecret = key.isSecret(); // this.flags = (this.canEncrypt ? 1 << KeyFlags.canEncrypt : 0) // + (this.canSign ? 1 << KeyFlags.canSign : 0) // + (this.hasSecretKey ? 1 << KeyFlags.hasSecretKey : 0) // + (this.isDisabled ? 1 << KeyFlags.isDisabled : 0) // + (this.isExpired ? 1 << KeyFlags.isExpired : 0) // + (this.isInvalid ? 1 << KeyFlags.isInvalid : 0) // + (this.isQualified ? 1 << KeyFlags.isQualified : 0) // + (this.isRevoked ? 1 << KeyFlags.isRevoked : 0) // + (this.isSecret ? 1 << KeyFlags.isSecret : 0); // this.rawContactId = 0; // this.deleted = false; // } // // public RawGpgContact(String name, String email, String comment, String fingerprint, // int flags, long rawContactId, boolean deleted) { // super(); // this.name = name; // this.email = email; // this.comment = comment; // this.fingerprint = fingerprint; // this.keyID = fingerprint.substring(fingerprint.length() - 16); // this.flags = flags; // this.canEncrypt = (flags >> KeyFlags.canEncrypt & 1) != 0; // this.canSign = (flags >> KeyFlags.canSign & 1) != 0; // this.hasSecretKey = (flags >> KeyFlags.hasSecretKey & 1) != 0; // this.isDisabled = (flags >> KeyFlags.isDisabled & 1) != 0; // this.isExpired = (flags >> KeyFlags.isExpired & 1) != 0; // this.isInvalid = (flags >> KeyFlags.isInvalid & 1) != 0; // this.isQualified = (flags >> KeyFlags.isQualified & 1) != 0; // this.isRevoked = (flags >> KeyFlags.isRevoked & 1) != 0; // this.isSecret = (flags >> KeyFlags.isSecret & 1) != 0; // this.rawContactId = rawContactId; // this.deleted = deleted; // } // }
import android.widget.Filter; import android.widget.Filterable; import android.widget.ListView; import android.widget.TextView; import info.guardianproject.gpg.GpgApplication.Action; import info.guardianproject.gpg.sync.GpgContactManager; import info.guardianproject.gpg.sync.RawGpgContact; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter;
/* * Copyright (C) 2010 Thialfihar <thi@thialfihar.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package info.guardianproject.gpg; public class KeyListContactsAdapter extends BaseAdapter implements Filterable { public static final String TAG = "KeyListContactsAdapter"; protected LayoutInflater mInflater; protected ListView mParent; protected String mSearchString; protected long mSelectedKeyIds[];
// Path: src/info/guardianproject/gpg/sync/RawGpgContact.java // public class RawGpgContact { // // public final String name; // public final String email; // public final String comment; // public final String keyID; // public final String fingerprint; // public final int flags; // public final boolean canEncrypt; // public final boolean canSign; // public final boolean hasSecretKey; // public final boolean isDisabled; // public final boolean isExpired; // public final boolean isInvalid; // public final boolean isQualified; // public final boolean isRevoked; // public final boolean isSecret; // public final long rawContactId; // public final boolean deleted; // // public static class KeyFlags { // public static int canEncrypt = 0; // public static int canSign = 1; // public static int hasSecretKey = 2; // public static int isDisabled = 3; // public static int isExpired = 4; // public static int isInvalid = 5; // public static int isQualified = 6; // public static int isRevoked = 7; // public static int isSecret = 8; // } // // public static List<RawGpgContact> fromPublicKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listKeys()); // } // // public static List<RawGpgContact> fromSecretKeys() { // return getGnuPGKeysAsRawGpgContacts(GnuPG.context.listSecretKeys()); // } // // private static List<RawGpgContact> getGnuPGKeysAsRawGpgContacts(GnuPGKey[] keys) { // if (keys == null) // return new ArrayList<RawGpgContact>(); // ArrayList<RawGpgContact> list = new ArrayList<RawGpgContact>(keys.length); // for (GnuPGKey key : keys) { // list.add(new RawGpgContact(key)); // } // return list; // } // // public RawGpgContact(GnuPGKey key) { // super(); // this.name = key.getName(); // this.email = key.getEmail(); // this.comment = key.getComment(); // this.fingerprint = key.getFingerprint(); // this.keyID = key.getKeyID(); // this.canEncrypt = key.canEncrypt(); // this.canSign = key.canSign(); // this.hasSecretKey = key.hasSecretKey(); // this.isDisabled = key.isDisabled(); // this.isExpired = key.isExpired(); // this.isInvalid = key.isInvalid(); // this.isQualified = key.isQualified(); // this.isRevoked = key.isRevoked(); // this.isSecret = key.isSecret(); // this.flags = (this.canEncrypt ? 1 << KeyFlags.canEncrypt : 0) // + (this.canSign ? 1 << KeyFlags.canSign : 0) // + (this.hasSecretKey ? 1 << KeyFlags.hasSecretKey : 0) // + (this.isDisabled ? 1 << KeyFlags.isDisabled : 0) // + (this.isExpired ? 1 << KeyFlags.isExpired : 0) // + (this.isInvalid ? 1 << KeyFlags.isInvalid : 0) // + (this.isQualified ? 1 << KeyFlags.isQualified : 0) // + (this.isRevoked ? 1 << KeyFlags.isRevoked : 0) // + (this.isSecret ? 1 << KeyFlags.isSecret : 0); // this.rawContactId = 0; // this.deleted = false; // } // // public RawGpgContact(String name, String email, String comment, String fingerprint, // int flags, long rawContactId, boolean deleted) { // super(); // this.name = name; // this.email = email; // this.comment = comment; // this.fingerprint = fingerprint; // this.keyID = fingerprint.substring(fingerprint.length() - 16); // this.flags = flags; // this.canEncrypt = (flags >> KeyFlags.canEncrypt & 1) != 0; // this.canSign = (flags >> KeyFlags.canSign & 1) != 0; // this.hasSecretKey = (flags >> KeyFlags.hasSecretKey & 1) != 0; // this.isDisabled = (flags >> KeyFlags.isDisabled & 1) != 0; // this.isExpired = (flags >> KeyFlags.isExpired & 1) != 0; // this.isInvalid = (flags >> KeyFlags.isInvalid & 1) != 0; // this.isQualified = (flags >> KeyFlags.isQualified & 1) != 0; // this.isRevoked = (flags >> KeyFlags.isRevoked & 1) != 0; // this.isSecret = (flags >> KeyFlags.isSecret & 1) != 0; // this.rawContactId = rawContactId; // this.deleted = deleted; // } // } // Path: src/info/guardianproject/gpg/KeyListContactsAdapter.java import android.widget.Filter; import android.widget.Filterable; import android.widget.ListView; import android.widget.TextView; import info.guardianproject.gpg.GpgApplication.Action; import info.guardianproject.gpg.sync.GpgContactManager; import info.guardianproject.gpg.sync.RawGpgContact; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; /* * Copyright (C) 2010 Thialfihar <thi@thialfihar.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package info.guardianproject.gpg; public class KeyListContactsAdapter extends BaseAdapter implements Filterable { public static final String TAG = "KeyListContactsAdapter"; protected LayoutInflater mInflater; protected ListView mParent; protected String mSearchString; protected long mSelectedKeyIds[];
private RawGpgContact[] mContacts;
guardianproject/gnupg-for-android
src/info/guardianproject/gpg/apg_compat/DecryptActivity.java
// Path: src/info/guardianproject/gpg/GnuPG.java // public class GnuPG { // public static GnuPGContext context = null; // // private static Pattern PGP_MESSAGE = null; // private static Pattern PGP_PRIVATE_KEY_BLOCK = null; // private static Pattern PGP_PUBLIC_KEY_BLOCK = null; // private static Pattern PGP_SIGNATURE = null; // private static Pattern PGP_SIGNED_MESSAGE = null; // // public static void createContext() { // context = new GnuPGContext(); // // set the homeDir option to our custom home location // context.setEngineInfo(context.getProtocol(), context.getFilename(), // NativeHelper.app_home.getAbsolutePath()); // } // // public static int gpg2(String args) { // final String TAG = "gpg2"; // String command = NativeHelper.gpg2 + " " + args; // Log.i(TAG, command); // try { // Process sh = Runtime.getRuntime().exec("/system/bin/sh", // NativeHelper.envp, NativeHelper.app_home); // OutputStream stdin = sh.getOutputStream(); // InputStream stdout = sh.getInputStream(); // InputStream stderr = sh.getErrorStream(); // // stdin.write((command + "\nexit\n").getBytes("ASCII")); // sh.waitFor(); // // Log.i("stdout", readResult(stdout)); // Log.w("stderr", readResult(stderr)); // Log.i(TAG, "finished: " + command + " exit value: " + sh.exitValue()); // return sh.exitValue(); // } catch (Exception e) { // Log.e(TAG, "FAILED: " + command, e); // } // return 1; // } // // private static String readResult(InputStream i) { // String ret = ""; // try { // byte[] readBuffer = new byte[512]; // int readCount = -1; // while ((readCount = i.read(readBuffer)) > 0) { // ret += new String(readBuffer, 0, readCount); // } // } catch (IOException e) { // Log.e("GnuPG", "readResult", e); // } // return ret; // } // // public static Matcher getPgpMessageMatcher(CharSequence input) { // if (PGP_MESSAGE == null) // PGP_MESSAGE = Pattern // .compile( // ".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*", // Pattern.DOTALL); // return PGP_MESSAGE.matcher(input); // } // // public static Matcher getPgpSignatureMatcher(CharSequence input) { // if (PGP_SIGNATURE == null) // PGP_SIGNATURE = Pattern // .compile( // ".*?(-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*", // Pattern.DOTALL); // return PGP_SIGNATURE.matcher(input); // } // // public static Matcher getPgpSignedMessageMatcher(CharSequence input) { // if (PGP_SIGNED_MESSAGE == null) // PGP_SIGNED_MESSAGE = Pattern // .compile( // ".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*", // Pattern.DOTALL); // return PGP_SIGNED_MESSAGE.matcher(input); // } // // public static Matcher getPgpPrivateKeyBlockMatcher(CharSequence input) { // if (PGP_PRIVATE_KEY_BLOCK == null) // PGP_PRIVATE_KEY_BLOCK = Pattern // .compile( // ".*?(-----BEGIN PGP PRIVATE KEY BLOCK-----.*?-----END PGP PRIVATE KEY BLOCK-----).*", // Pattern.DOTALL); // return PGP_PRIVATE_KEY_BLOCK.matcher(input); // } // // public static Matcher getPgpPublicKeyBlockMatcher(CharSequence input) { // if (PGP_PUBLIC_KEY_BLOCK == null) // PGP_PUBLIC_KEY_BLOCK = Pattern // .compile( // ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*", // Pattern.DOTALL); // return PGP_PUBLIC_KEY_BLOCK.matcher(input); // } // }
import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.freiheit.gnupg.GnuPGData; import info.guardianproject.gpg.GnuPG; import info.guardianproject.gpg.R; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException;
package info.guardianproject.gpg.apg_compat; public class DecryptActivity extends Activity { public static final String TAG = "DecryptActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String action = intent.getAction(); if (action.equals(Apg.Intent.DECRYPT_AND_RETURN)) { if (intent.getData() != null) Log.w(TAG, Apg.Intent.DECRYPT_AND_RETURN + " " + getString(R.string.error_files_not_supported)); Bundle extras = intent.getExtras(); // add empty content so we don't have to check for null again if (extras == null) extras = new Bundle(); boolean asciiArmor = extras.getBoolean(Apg.EXTRA_ASCII_ARMOUR, true);
// Path: src/info/guardianproject/gpg/GnuPG.java // public class GnuPG { // public static GnuPGContext context = null; // // private static Pattern PGP_MESSAGE = null; // private static Pattern PGP_PRIVATE_KEY_BLOCK = null; // private static Pattern PGP_PUBLIC_KEY_BLOCK = null; // private static Pattern PGP_SIGNATURE = null; // private static Pattern PGP_SIGNED_MESSAGE = null; // // public static void createContext() { // context = new GnuPGContext(); // // set the homeDir option to our custom home location // context.setEngineInfo(context.getProtocol(), context.getFilename(), // NativeHelper.app_home.getAbsolutePath()); // } // // public static int gpg2(String args) { // final String TAG = "gpg2"; // String command = NativeHelper.gpg2 + " " + args; // Log.i(TAG, command); // try { // Process sh = Runtime.getRuntime().exec("/system/bin/sh", // NativeHelper.envp, NativeHelper.app_home); // OutputStream stdin = sh.getOutputStream(); // InputStream stdout = sh.getInputStream(); // InputStream stderr = sh.getErrorStream(); // // stdin.write((command + "\nexit\n").getBytes("ASCII")); // sh.waitFor(); // // Log.i("stdout", readResult(stdout)); // Log.w("stderr", readResult(stderr)); // Log.i(TAG, "finished: " + command + " exit value: " + sh.exitValue()); // return sh.exitValue(); // } catch (Exception e) { // Log.e(TAG, "FAILED: " + command, e); // } // return 1; // } // // private static String readResult(InputStream i) { // String ret = ""; // try { // byte[] readBuffer = new byte[512]; // int readCount = -1; // while ((readCount = i.read(readBuffer)) > 0) { // ret += new String(readBuffer, 0, readCount); // } // } catch (IOException e) { // Log.e("GnuPG", "readResult", e); // } // return ret; // } // // public static Matcher getPgpMessageMatcher(CharSequence input) { // if (PGP_MESSAGE == null) // PGP_MESSAGE = Pattern // .compile( // ".*?(-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----).*", // Pattern.DOTALL); // return PGP_MESSAGE.matcher(input); // } // // public static Matcher getPgpSignatureMatcher(CharSequence input) { // if (PGP_SIGNATURE == null) // PGP_SIGNATURE = Pattern // .compile( // ".*?(-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*", // Pattern.DOTALL); // return PGP_SIGNATURE.matcher(input); // } // // public static Matcher getPgpSignedMessageMatcher(CharSequence input) { // if (PGP_SIGNED_MESSAGE == null) // PGP_SIGNED_MESSAGE = Pattern // .compile( // ".*?(-----BEGIN PGP SIGNED MESSAGE-----.*?-----BEGIN PGP SIGNATURE-----.*?-----END PGP SIGNATURE-----).*", // Pattern.DOTALL); // return PGP_SIGNED_MESSAGE.matcher(input); // } // // public static Matcher getPgpPrivateKeyBlockMatcher(CharSequence input) { // if (PGP_PRIVATE_KEY_BLOCK == null) // PGP_PRIVATE_KEY_BLOCK = Pattern // .compile( // ".*?(-----BEGIN PGP PRIVATE KEY BLOCK-----.*?-----END PGP PRIVATE KEY BLOCK-----).*", // Pattern.DOTALL); // return PGP_PRIVATE_KEY_BLOCK.matcher(input); // } // // public static Matcher getPgpPublicKeyBlockMatcher(CharSequence input) { // if (PGP_PUBLIC_KEY_BLOCK == null) // PGP_PUBLIC_KEY_BLOCK = Pattern // .compile( // ".*?(-----BEGIN PGP PUBLIC KEY BLOCK-----.*?-----END PGP PUBLIC KEY BLOCK-----).*", // Pattern.DOTALL); // return PGP_PUBLIC_KEY_BLOCK.matcher(input); // } // } // Path: src/info/guardianproject/gpg/apg_compat/DecryptActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.freiheit.gnupg.GnuPGData; import info.guardianproject.gpg.GnuPG; import info.guardianproject.gpg.R; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; package info.guardianproject.gpg.apg_compat; public class DecryptActivity extends Activity { public static final String TAG = "DecryptActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String action = intent.getAction(); if (action.equals(Apg.Intent.DECRYPT_AND_RETURN)) { if (intent.getData() != null) Log.w(TAG, Apg.Intent.DECRYPT_AND_RETURN + " " + getString(R.string.error_files_not_supported)); Bundle extras = intent.getExtras(); // add empty content so we don't have to check for null again if (extras == null) extras = new Bundle(); boolean asciiArmor = extras.getBoolean(Apg.EXTRA_ASCII_ARMOUR, true);
GnuPG.context.setArmor(asciiArmor);
guardianproject/gnupg-for-android
src/info/guardianproject/gpg/CreateKeyActivity.java
// Path: src/com/freiheit/gnupg/GnuPGGenkeyResult.java // public class GnuPGGenkeyResult { // // private String _fpr; // private boolean _primary; // private boolean _sub; // // protected GnuPGGenkeyResult() { // } // // /** // * This is the fingerprint of the key that was created. If both a primary // * and a sub key were generated, the fingerprint of the primary key will be // * returned. If the crypto engine does not provide the fingerprint, `it will // * return a null pointer. // * // * @return fingerprint of the created key // */ // public String getFpr() { // return _fpr; // } // // /** // * This is a flag that is set to true if a primary key was created and to // * false if not. // * // * @return flag, if a primary key was created // */ // public boolean isPrimary() { // return _primary; // } // // /** // * This is a flag that is set to true if a subkey was created and to false // * if not. // * // * @return flag, if a subkey was created // */ // public boolean isSub() { // return _sub; // } // }
import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.freiheit.gnupg.GnuPGGenkeyResult;
Toast.makeText(this, getString(R.string.error_gen_key_failed), Toast.LENGTH_LONG) .show(); finish(); } public class CreateKeyTask extends AsyncTask<String, String, Integer> { private ProgressDialog dialog; private Context context; public CreateKeyTask(Context c) { context = c; dialog = new ProgressDialog(context); dialog.setCancelable(false); dialog.setIndeterminate(true); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setTitle(R.string.dialog_generating_new_key_title); dialog.setMessage(getString(R.string.generating_new_key_message)); } @Override protected void onPreExecute() { super.onPreExecute(); dialog.show(); } @Override protected Integer doInBackground(String... params) { Log.i(TAG, "doInBackground: " + params[0]); try { GnuPG.context.genPgpKey(params[0]);
// Path: src/com/freiheit/gnupg/GnuPGGenkeyResult.java // public class GnuPGGenkeyResult { // // private String _fpr; // private boolean _primary; // private boolean _sub; // // protected GnuPGGenkeyResult() { // } // // /** // * This is the fingerprint of the key that was created. If both a primary // * and a sub key were generated, the fingerprint of the primary key will be // * returned. If the crypto engine does not provide the fingerprint, `it will // * return a null pointer. // * // * @return fingerprint of the created key // */ // public String getFpr() { // return _fpr; // } // // /** // * This is a flag that is set to true if a primary key was created and to // * false if not. // * // * @return flag, if a primary key was created // */ // public boolean isPrimary() { // return _primary; // } // // /** // * This is a flag that is set to true if a subkey was created and to false // * if not. // * // * @return flag, if a subkey was created // */ // public boolean isSub() { // return _sub; // } // } // Path: src/info/guardianproject/gpg/CreateKeyActivity.java import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.Contacts; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.freiheit.gnupg.GnuPGGenkeyResult; Toast.makeText(this, getString(R.string.error_gen_key_failed), Toast.LENGTH_LONG) .show(); finish(); } public class CreateKeyTask extends AsyncTask<String, String, Integer> { private ProgressDialog dialog; private Context context; public CreateKeyTask(Context c) { context = c; dialog = new ProgressDialog(context); dialog.setCancelable(false); dialog.setIndeterminate(true); dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); dialog.setTitle(R.string.dialog_generating_new_key_title); dialog.setMessage(getString(R.string.generating_new_key_message)); } @Override protected void onPreExecute() { super.onPreExecute(); dialog.show(); } @Override protected Integer doInBackground(String... params) { Log.i(TAG, "doInBackground: " + params[0]); try { GnuPG.context.genPgpKey(params[0]);
GnuPGGenkeyResult result = GnuPG.context.getGenkeyResult();
guardianproject/gnupg-for-android
src/info/guardianproject/gpg/KeyListKeyserverAdapter.java
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // }
import java.util.List; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import android.content.Context; import android.text.format.DateFormat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView;
/* * Copyright (C) 2010 Thialfihar <thi@thialfihar.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package info.guardianproject.gpg; public class KeyListKeyserverAdapter extends BaseAdapter { public static final String TAG = "KeyListKeyserverAdapter"; protected LayoutInflater mInflater; protected ListView mParent; protected String mSearchString;
// Path: src/org/openintents/openpgp/keyserver/KeyServer.java // static public class KeyInfo implements Serializable, Parcelable { // private static final long serialVersionUID = -7797972113284992662L; // public ArrayList<String> userIds; // public boolean isRevoked; // public Date creationDate; // public String fingerprint = null; // public long keyId = 0; // public int size; // public String algorithm; // // public static long keyIdFromFingerprint(String fingerprint) { // return new BigInteger(fingerprint, 16).longValue(); // } // // public static String hexFromKeyId(long keyId) { // return String.format("%016x", keyId).toLowerCase(Locale.ENGLISH); // } // // public KeyInfo() { // userIds = new ArrayList<String>(); // } // // public KeyInfo(Parcel in) { // this(); // // in.readStringList(this.userIds); // this.isRevoked = in.readByte() != 0; // this.creationDate = (Date) in.readSerializable(); // this.fingerprint = in.readString(); // this.keyId = in.readLong(); // this.size = in.readInt(); // this.algorithm = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeStringList(userIds); // dest.writeByte((byte) (isRevoked ? 1 : 0)); // dest.writeSerializable(creationDate); // dest.writeString(fingerprint); // dest.writeLong(keyId); // dest.writeInt(size); // dest.writeString(algorithm); // } // // public void setFingerprint(String fingerprint) { // this.fingerprint = fingerprint.toLowerCase(Locale.ENGLISH); // this.keyId = keyIdFromFingerprint(fingerprint); // } // } // Path: src/info/guardianproject/gpg/KeyListKeyserverAdapter.java import java.util.List; import org.openintents.openpgp.keyserver.KeyServer.KeyInfo; import android.content.Context; import android.text.format.DateFormat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; /* * Copyright (C) 2010 Thialfihar <thi@thialfihar.org> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package info.guardianproject.gpg; public class KeyListKeyserverAdapter extends BaseAdapter { public static final String TAG = "KeyListKeyserverAdapter"; protected LayoutInflater mInflater; protected ListView mParent; protected String mSearchString;
private KeyInfo[] mKeyArray;
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/controller/profile/ProfileController.java
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/profile/ProfileRepository.java // public interface ProfileRepository extends MongoRepository<Profile, String> { // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/profile/Profile.java // @Document // public class Profile extends AbstractAuditableEntity { // // @NotNull // private String forename; // // @NotNull // private String surname; // // @NotNull // private String email; // // public Profile() { // } // // public String getForename() { // return forename; // } // // public void setForename(String forename) { // this.forename = forename; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public String toString() { // return toStringHelper() // .add("forename", forename) // .add("surname", surname) // .add("email", email) // .toString(); // } // // } // // Path: src/main/java/uk/co/caprica/bootlace/security/domain/UserWithId.java // public final class UserWithId extends User { // // /** // * The database user identifier. // */ // private final String id; // // /** // * Create a user. // * // * @param id database user identifier // */ // public UserWithId(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String id) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // this.id = id; // } // // /** // * Get the database identifier for the user. // * // * @return unique user identifier // */ // public String getId() { // return id; // } // // }
import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.data.mongo.profile.ProfileRepository; import uk.co.caprica.bootlace.domain.profile.Profile; import uk.co.caprica.bootlace.security.domain.UserWithId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;
/* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.profile; /** * Web-service controller for Profile resources. * <p> * A profile is basic personal data associated with an application user. * <p> * Semantically a user profile (for a valid user) always "exists" even if it has not been created * in the repository yet. * <p> * This is <em>not</em> typical. * <p> * The security constraints are such that a profile will be returned only for the currently * authenticated user, i.e. this service does not allow for a particular profile to be retrieved * even if its unique identifier is known. * <p> * This is <em>not</em> typical either. * <p> * The profile information could just be kept with the user account information, but they are kept * separate so as not to blur responsibilities - i.e. the user account data is deemed "system" * data, whereas the profile is more like "application" data. * <p> * To simplify this a little bit, the profile used the same unique identifier as the user account. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("profile") public class ProfileController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ProfileController.class); /** * Repository containing Profile resources. */ @Autowired
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/profile/ProfileRepository.java // public interface ProfileRepository extends MongoRepository<Profile, String> { // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/profile/Profile.java // @Document // public class Profile extends AbstractAuditableEntity { // // @NotNull // private String forename; // // @NotNull // private String surname; // // @NotNull // private String email; // // public Profile() { // } // // public String getForename() { // return forename; // } // // public void setForename(String forename) { // this.forename = forename; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public String toString() { // return toStringHelper() // .add("forename", forename) // .add("surname", surname) // .add("email", email) // .toString(); // } // // } // // Path: src/main/java/uk/co/caprica/bootlace/security/domain/UserWithId.java // public final class UserWithId extends User { // // /** // * The database user identifier. // */ // private final String id; // // /** // * Create a user. // * // * @param id database user identifier // */ // public UserWithId(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String id) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // this.id = id; // } // // /** // * Get the database identifier for the user. // * // * @return unique user identifier // */ // public String getId() { // return id; // } // // } // Path: src/main/java/uk/co/caprica/bootlace/controller/profile/ProfileController.java import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.data.mongo.profile.ProfileRepository; import uk.co.caprica.bootlace.domain.profile.Profile; import uk.co.caprica.bootlace.security.domain.UserWithId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.profile; /** * Web-service controller for Profile resources. * <p> * A profile is basic personal data associated with an application user. * <p> * Semantically a user profile (for a valid user) always "exists" even if it has not been created * in the repository yet. * <p> * This is <em>not</em> typical. * <p> * The security constraints are such that a profile will be returned only for the currently * authenticated user, i.e. this service does not allow for a particular profile to be retrieved * even if its unique identifier is known. * <p> * This is <em>not</em> typical either. * <p> * The profile information could just be kept with the user account information, but they are kept * separate so as not to blur responsibilities - i.e. the user account data is deemed "system" * data, whereas the profile is more like "application" data. * <p> * To simplify this a little bit, the profile used the same unique identifier as the user account. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("profile") public class ProfileController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ProfileController.class); /** * Repository containing Profile resources. */ @Autowired
private ProfileRepository profileRepository;
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/controller/profile/ProfileController.java
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/profile/ProfileRepository.java // public interface ProfileRepository extends MongoRepository<Profile, String> { // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/profile/Profile.java // @Document // public class Profile extends AbstractAuditableEntity { // // @NotNull // private String forename; // // @NotNull // private String surname; // // @NotNull // private String email; // // public Profile() { // } // // public String getForename() { // return forename; // } // // public void setForename(String forename) { // this.forename = forename; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public String toString() { // return toStringHelper() // .add("forename", forename) // .add("surname", surname) // .add("email", email) // .toString(); // } // // } // // Path: src/main/java/uk/co/caprica/bootlace/security/domain/UserWithId.java // public final class UserWithId extends User { // // /** // * The database user identifier. // */ // private final String id; // // /** // * Create a user. // * // * @param id database user identifier // */ // public UserWithId(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String id) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // this.id = id; // } // // /** // * Get the database identifier for the user. // * // * @return unique user identifier // */ // public String getId() { // return id; // } // // }
import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.data.mongo.profile.ProfileRepository; import uk.co.caprica.bootlace.domain.profile.Profile; import uk.co.caprica.bootlace.security.domain.UserWithId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;
/* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.profile; /** * Web-service controller for Profile resources. * <p> * A profile is basic personal data associated with an application user. * <p> * Semantically a user profile (for a valid user) always "exists" even if it has not been created * in the repository yet. * <p> * This is <em>not</em> typical. * <p> * The security constraints are such that a profile will be returned only for the currently * authenticated user, i.e. this service does not allow for a particular profile to be retrieved * even if its unique identifier is known. * <p> * This is <em>not</em> typical either. * <p> * The profile information could just be kept with the user account information, but they are kept * separate so as not to blur responsibilities - i.e. the user account data is deemed "system" * data, whereas the profile is more like "application" data. * <p> * To simplify this a little bit, the profile used the same unique identifier as the user account. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("profile") public class ProfileController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ProfileController.class); /** * Repository containing Profile resources. */ @Autowired private ProfileRepository profileRepository; /** * Get the currently authenticated user profile resource. * * @param user currently authenticated user * @return profile */ @RequestMapping(method=RequestMethod.GET)
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/profile/ProfileRepository.java // public interface ProfileRepository extends MongoRepository<Profile, String> { // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/profile/Profile.java // @Document // public class Profile extends AbstractAuditableEntity { // // @NotNull // private String forename; // // @NotNull // private String surname; // // @NotNull // private String email; // // public Profile() { // } // // public String getForename() { // return forename; // } // // public void setForename(String forename) { // this.forename = forename; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public String toString() { // return toStringHelper() // .add("forename", forename) // .add("surname", surname) // .add("email", email) // .toString(); // } // // } // // Path: src/main/java/uk/co/caprica/bootlace/security/domain/UserWithId.java // public final class UserWithId extends User { // // /** // * The database user identifier. // */ // private final String id; // // /** // * Create a user. // * // * @param id database user identifier // */ // public UserWithId(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String id) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // this.id = id; // } // // /** // * Get the database identifier for the user. // * // * @return unique user identifier // */ // public String getId() { // return id; // } // // } // Path: src/main/java/uk/co/caprica/bootlace/controller/profile/ProfileController.java import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.data.mongo.profile.ProfileRepository; import uk.co.caprica.bootlace.domain.profile.Profile; import uk.co.caprica.bootlace.security.domain.UserWithId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.profile; /** * Web-service controller for Profile resources. * <p> * A profile is basic personal data associated with an application user. * <p> * Semantically a user profile (for a valid user) always "exists" even if it has not been created * in the repository yet. * <p> * This is <em>not</em> typical. * <p> * The security constraints are such that a profile will be returned only for the currently * authenticated user, i.e. this service does not allow for a particular profile to be retrieved * even if its unique identifier is known. * <p> * This is <em>not</em> typical either. * <p> * The profile information could just be kept with the user account information, but they are kept * separate so as not to blur responsibilities - i.e. the user account data is deemed "system" * data, whereas the profile is more like "application" data. * <p> * To simplify this a little bit, the profile used the same unique identifier as the user account. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("profile") public class ProfileController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ProfileController.class); /** * Repository containing Profile resources. */ @Autowired private ProfileRepository profileRepository; /** * Get the currently authenticated user profile resource. * * @param user currently authenticated user * @return profile */ @RequestMapping(method=RequestMethod.GET)
public Profile getProfile(@AuthenticationPrincipal UserWithId user) {
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/controller/profile/ProfileController.java
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/profile/ProfileRepository.java // public interface ProfileRepository extends MongoRepository<Profile, String> { // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/profile/Profile.java // @Document // public class Profile extends AbstractAuditableEntity { // // @NotNull // private String forename; // // @NotNull // private String surname; // // @NotNull // private String email; // // public Profile() { // } // // public String getForename() { // return forename; // } // // public void setForename(String forename) { // this.forename = forename; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public String toString() { // return toStringHelper() // .add("forename", forename) // .add("surname", surname) // .add("email", email) // .toString(); // } // // } // // Path: src/main/java/uk/co/caprica/bootlace/security/domain/UserWithId.java // public final class UserWithId extends User { // // /** // * The database user identifier. // */ // private final String id; // // /** // * Create a user. // * // * @param id database user identifier // */ // public UserWithId(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String id) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // this.id = id; // } // // /** // * Get the database identifier for the user. // * // * @return unique user identifier // */ // public String getId() { // return id; // } // // }
import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.data.mongo.profile.ProfileRepository; import uk.co.caprica.bootlace.domain.profile.Profile; import uk.co.caprica.bootlace.security.domain.UserWithId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;
/* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.profile; /** * Web-service controller for Profile resources. * <p> * A profile is basic personal data associated with an application user. * <p> * Semantically a user profile (for a valid user) always "exists" even if it has not been created * in the repository yet. * <p> * This is <em>not</em> typical. * <p> * The security constraints are such that a profile will be returned only for the currently * authenticated user, i.e. this service does not allow for a particular profile to be retrieved * even if its unique identifier is known. * <p> * This is <em>not</em> typical either. * <p> * The profile information could just be kept with the user account information, but they are kept * separate so as not to blur responsibilities - i.e. the user account data is deemed "system" * data, whereas the profile is more like "application" data. * <p> * To simplify this a little bit, the profile used the same unique identifier as the user account. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("profile") public class ProfileController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ProfileController.class); /** * Repository containing Profile resources. */ @Autowired private ProfileRepository profileRepository; /** * Get the currently authenticated user profile resource. * * @param user currently authenticated user * @return profile */ @RequestMapping(method=RequestMethod.GET)
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/profile/ProfileRepository.java // public interface ProfileRepository extends MongoRepository<Profile, String> { // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/profile/Profile.java // @Document // public class Profile extends AbstractAuditableEntity { // // @NotNull // private String forename; // // @NotNull // private String surname; // // @NotNull // private String email; // // public Profile() { // } // // public String getForename() { // return forename; // } // // public void setForename(String forename) { // this.forename = forename; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // @Override // public String toString() { // return toStringHelper() // .add("forename", forename) // .add("surname", surname) // .add("email", email) // .toString(); // } // // } // // Path: src/main/java/uk/co/caprica/bootlace/security/domain/UserWithId.java // public final class UserWithId extends User { // // /** // * The database user identifier. // */ // private final String id; // // /** // * Create a user. // * // * @param id database user identifier // */ // public UserWithId(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String id) { // super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); // this.id = id; // } // // /** // * Get the database identifier for the user. // * // * @return unique user identifier // */ // public String getId() { // return id; // } // // } // Path: src/main/java/uk/co/caprica/bootlace/controller/profile/ProfileController.java import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.data.mongo.profile.ProfileRepository; import uk.co.caprica.bootlace.domain.profile.Profile; import uk.co.caprica.bootlace.security.domain.UserWithId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.profile; /** * Web-service controller for Profile resources. * <p> * A profile is basic personal data associated with an application user. * <p> * Semantically a user profile (for a valid user) always "exists" even if it has not been created * in the repository yet. * <p> * This is <em>not</em> typical. * <p> * The security constraints are such that a profile will be returned only for the currently * authenticated user, i.e. this service does not allow for a particular profile to be retrieved * even if its unique identifier is known. * <p> * This is <em>not</em> typical either. * <p> * The profile information could just be kept with the user account information, but they are kept * separate so as not to blur responsibilities - i.e. the user account data is deemed "system" * data, whereas the profile is more like "application" data. * <p> * To simplify this a little bit, the profile used the same unique identifier as the user account. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("profile") public class ProfileController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ProfileController.class); /** * Repository containing Profile resources. */ @Autowired private ProfileRepository profileRepository; /** * Get the currently authenticated user profile resource. * * @param user currently authenticated user * @return profile */ @RequestMapping(method=RequestMethod.GET)
public Profile getProfile(@AuthenticationPrincipal UserWithId user) {
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/startup/ApplicationStartup.java
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // }
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexDefinitionBuilder;
/* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.startup; /** * Component containing operations to execute on application startup. * <p> * This component initialises the configured database with seed data. * <p> * <em>This component only exists for purposes of this reference application and would not * ordinarily be used in a Production application.</em> */ @Component public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ApplicationStartup.class); /** * Lower-level interface to the database, used e.g. to create collections and indexes. */ @Autowired private MongoOperations mongoOperations; /** * Repository for account entities. */ @Autowired
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // } // Path: src/main/java/uk/co/caprica/bootlace/startup/ApplicationStartup.java import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexDefinitionBuilder; /* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.startup; /** * Component containing operations to execute on application startup. * <p> * This component initialises the configured database with seed data. * <p> * <em>This component only exists for purposes of this reference application and would not * ordinarily be used in a Production application.</em> */ @Component public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(ApplicationStartup.class); /** * Lower-level interface to the database, used e.g. to create collections and indexes. */ @Autowired private MongoOperations mongoOperations; /** * Repository for account entities. */ @Autowired
private AccountRepository accountRepository;
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/startup/ApplicationStartup.java
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // }
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexDefinitionBuilder;
*/ private void createDatabase() { logger.debug("createDatabase()"); try { mongoOperations.createCollection("account"); mongoOperations.indexOps("account") .ensureIndex(new TextIndexDefinitionBuilder() .named("username") .onField("username") .build()); } catch (Exception e) { logger.debug("Exception creating database, assuming database already exists"); // This is most likely because the collection already exists, so ignore the error and // carry on } } /** * Populate the database with seed data, in particular some demo accounts are created so that * application logins and role-based authorisations will work. */ private void seedDatabase() { logger.debug("seedDatabase()"); List<String> adminRoles = new ArrayList<>(); adminRoles.add("ROLE_ADMIN"); adminRoles.add("ROLE_USER"); List<String> userRoles = new ArrayList<>(); userRoles.add("ROLE_USER"); if (accountRepository.findByUsername("mark") == null) {
// Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // } // Path: src/main/java/uk/co/caprica/bootlace/startup/ApplicationStartup.java import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.index.TextIndexDefinition.TextIndexDefinitionBuilder; */ private void createDatabase() { logger.debug("createDatabase()"); try { mongoOperations.createCollection("account"); mongoOperations.indexOps("account") .ensureIndex(new TextIndexDefinitionBuilder() .named("username") .onField("username") .build()); } catch (Exception e) { logger.debug("Exception creating database, assuming database already exists"); // This is most likely because the collection already exists, so ignore the error and // carry on } } /** * Populate the database with seed data, in particular some demo accounts are created so that * application logins and role-based authorisations will work. */ private void seedDatabase() { logger.debug("seedDatabase()"); List<String> adminRoles = new ArrayList<>(); adminRoles.add("ROLE_ADMIN"); adminRoles.add("ROLE_USER"); List<String> userRoles = new ArrayList<>(); userRoles.add("ROLE_USER"); if (accountRepository.findByUsername("mark") == null) {
Account markAdminAccount = new Account();
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/controller/account/AccountController.java
// Path: src/main/java/uk/co/caprica/bootlace/controller/ResourceNotFoundException.java // @ResponseStatus(value=HttpStatus.NOT_FOUND) // public class ResourceNotFoundException extends RuntimeException { // // } // // Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // }
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.controller.ResourceNotFoundException; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
/* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.account; /** * Web-service controller for Account resources. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("accounts") public class AccountController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(AccountController.class); /** * Repository containing Account resources. */ @Autowired
// Path: src/main/java/uk/co/caprica/bootlace/controller/ResourceNotFoundException.java // @ResponseStatus(value=HttpStatus.NOT_FOUND) // public class ResourceNotFoundException extends RuntimeException { // // } // // Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // } // Path: src/main/java/uk/co/caprica/bootlace/controller/account/AccountController.java import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.controller.ResourceNotFoundException; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.account; /** * Web-service controller for Account resources. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("accounts") public class AccountController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(AccountController.class); /** * Repository containing Account resources. */ @Autowired
private AccountRepository accountRepository;
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/controller/account/AccountController.java
// Path: src/main/java/uk/co/caprica/bootlace/controller/ResourceNotFoundException.java // @ResponseStatus(value=HttpStatus.NOT_FOUND) // public class ResourceNotFoundException extends RuntimeException { // // } // // Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // }
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.controller.ResourceNotFoundException; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
/* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.account; /** * Web-service controller for Account resources. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("accounts") public class AccountController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(AccountController.class); /** * Repository containing Account resources. */ @Autowired private AccountRepository accountRepository; /** * * * @return */ @RequestMapping(method=RequestMethod.GET) @Secured("ROLE_ADMIN")
// Path: src/main/java/uk/co/caprica/bootlace/controller/ResourceNotFoundException.java // @ResponseStatus(value=HttpStatus.NOT_FOUND) // public class ResourceNotFoundException extends RuntimeException { // // } // // Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // } // Path: src/main/java/uk/co/caprica/bootlace/controller/account/AccountController.java import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.controller.ResourceNotFoundException; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.account; /** * Web-service controller for Account resources. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("accounts") public class AccountController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(AccountController.class); /** * Repository containing Account resources. */ @Autowired private AccountRepository accountRepository; /** * * * @return */ @RequestMapping(method=RequestMethod.GET) @Secured("ROLE_ADMIN")
public List<Account> getAllAccounts() {
caprica/bootlace
src/main/java/uk/co/caprica/bootlace/controller/account/AccountController.java
// Path: src/main/java/uk/co/caprica/bootlace/controller/ResourceNotFoundException.java // @ResponseStatus(value=HttpStatus.NOT_FOUND) // public class ResourceNotFoundException extends RuntimeException { // // } // // Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // }
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.controller.ResourceNotFoundException; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
/* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.account; /** * Web-service controller for Account resources. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("accounts") public class AccountController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(AccountController.class); /** * Repository containing Account resources. */ @Autowired private AccountRepository accountRepository; /** * * * @return */ @RequestMapping(method=RequestMethod.GET) @Secured("ROLE_ADMIN") public List<Account> getAllAccounts() { logger.debug("getAllAccounts()"); List<Account> result = accountRepository.findAll(); logger.debug("result={}", result); return result; } /** * * * @param id * @return */ @RequestMapping(method=RequestMethod.GET, value="{id}") @Secured("ROLE_ADMIN") public Account getAccount(@PathVariable("id") String id) { logger.debug("getAccount(id={})", id); Account result = accountRepository.findOne(id); logger.debug("result={}", result); if (result != null) { return result; } else {
// Path: src/main/java/uk/co/caprica/bootlace/controller/ResourceNotFoundException.java // @ResponseStatus(value=HttpStatus.NOT_FOUND) // public class ResourceNotFoundException extends RuntimeException { // // } // // Path: src/main/java/uk/co/caprica/bootlace/data/mongo/account/AccountRepository.java // public interface AccountRepository extends MongoRepository<Account, String> { // // /** // * Find an account for a given username. // * // * @param username username to search for // * @return account; or <code>null</code> if no account found for the give username // */ // Account findByUsername(String username); // // } // // Path: src/main/java/uk/co/caprica/bootlace/domain/account/Account.java // @Document // public class Account extends AbstractEntity { // // /** // * Username. // */ // @NotNull // private String username; // // /** // * Encrypted password. // * // * Using {@link JsonIgnore} prevents the password being returned by a web-service. // */ // @JsonIgnore // @NotNull // private String password; // // /** // * List of role authorisations. // */ // private List<String> roles; // // public Account() { // } // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // // public List<String> getRoles() { // return roles; // } // // public void setRoles(List<String> roles) { // this.roles = roles; // } // // @Override // public String toString() { // return toStringHelper() // .add("username", username) // .add("roles", roles) // .toString(); // } // // } // Path: src/main/java/uk/co/caprica/bootlace/controller/account/AccountController.java import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import uk.co.caprica.bootlace.controller.ResourceNotFoundException; import uk.co.caprica.bootlace.data.mongo.account.AccountRepository; import uk.co.caprica.bootlace.domain.account.Account; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /* * This file is part of Bootlace. * * Copyright (C) 2015 * Caprica Software Limited (capricasoftware.co.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.caprica.bootlace.controller.account; /** * Web-service controller for Account resources. * <p> * {@link RestController} adds {@link Controller} and {@link ResponseBody} by default. */ @RestController @RequestMapping("accounts") public class AccountController { /** * Log. */ private final Logger logger = LoggerFactory.getLogger(AccountController.class); /** * Repository containing Account resources. */ @Autowired private AccountRepository accountRepository; /** * * * @return */ @RequestMapping(method=RequestMethod.GET) @Secured("ROLE_ADMIN") public List<Account> getAllAccounts() { logger.debug("getAllAccounts()"); List<Account> result = accountRepository.findAll(); logger.debug("result={}", result); return result; } /** * * * @param id * @return */ @RequestMapping(method=RequestMethod.GET, value="{id}") @Secured("ROLE_ADMIN") public Account getAccount(@PathVariable("id") String id) { logger.debug("getAccount(id={})", id); Account result = accountRepository.findOne(id); logger.debug("result={}", result); if (result != null) { return result; } else {
throw new ResourceNotFoundException();
NiceSystems/hrider
src/main/java/hrider/converters/TypeConverter.java
// Path: src/main/java/hrider/io/Log.java // public class Log { // // //region Variables // private Logger logger; // //endregion // // //region Constructor // private Log(Class<?> clazz) { // logger = Logger.getLogger(clazz); // } // //endregion // // //region Public Methods // public static Log getLogger(Class<?> clazz) { // return new Log(clazz); // } // // public void info(String format, Object... args) { // logger.info(String.format(format, args)); // } // // public void debug(String format, Object... args) { // logger.debug(String.format(format, args)); // } // // public void warn(Throwable t, String format, Object... args) { // logger.warn(String.format(format, args), t); // } // // public void error(Throwable t, String format, Object... args) { // logger.error(String.format(format, args), t); // } // //endregion // }
import hrider.io.Log; import java.awt.*; import java.io.Serializable; import java.util.Map; import java.util.regex.Pattern;
package hrider.converters; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class is a base class for type converters. */ @SuppressWarnings("CallToSimpleGetterFromWithinClass") public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { //region Constants
// Path: src/main/java/hrider/io/Log.java // public class Log { // // //region Variables // private Logger logger; // //endregion // // //region Constructor // private Log(Class<?> clazz) { // logger = Logger.getLogger(clazz); // } // //endregion // // //region Public Methods // public static Log getLogger(Class<?> clazz) { // return new Log(clazz); // } // // public void info(String format, Object... args) { // logger.info(String.format(format, args)); // } // // public void debug(String format, Object... args) { // logger.debug(String.format(format, args)); // } // // public void warn(Throwable t, String format, Object... args) { // logger.warn(String.format(format, args), t); // } // // public void error(Throwable t, String format, Object... args) { // logger.error(String.format(format, args), t); // } // //endregion // } // Path: src/main/java/hrider/converters/TypeConverter.java import hrider.io.Log; import java.awt.*; import java.io.Serializable; import java.util.Map; import java.util.regex.Pattern; package hrider.converters; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class is a base class for type converters. */ @SuppressWarnings("CallToSimpleGetterFromWithinClass") public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { //region Constants
protected static final Log logger = Log.getLogger(TypeConverter.class);
NiceSystems/hrider
src/main/java/hrider/config/GlobalConfig.java
// Path: src/main/java/hrider/io/PathHelper.java // public class PathHelper { // // //region Constants // public final static String FILE_SEPARATOR = System.getProperty("file.separator"); // public final static String LINE_SEPARATOR = System.getProperty("line.separator"); // // private final static Log logger = Log.getLogger(PathHelper.class); // private final static Pattern ENV_VAR = Pattern.compile("((?<=\\$\\{)[a-zA-Z_0-9]*(?=\\}))"); // //endregion // // //region Constructor // private PathHelper() { // } // //endregion // // //region Public Methods // // /** // * Gets current folder of the executing process. // * // * @return A path to the current folder. // */ // public static String getCurrentFolder() { // return normalise("."); // } // // /** // * Removes extension from the file path. // * // * @param path The path to remove extension. // * @return A new path if the provided path contained extension or an original path otherwise. // */ // public static String getPathWithoutExtension(String path) { // String normalisedPath = expand(path); // // int index = normalisedPath.lastIndexOf('.'); // if (index != -1) { // normalisedPath = normalisedPath.substring(0, index); // } // // return normalisedPath; // } // // public static String getFileNameWithoutExtension(String path) { // String leaf = getLeaf(path); // // int index = leaf.lastIndexOf('.'); // if (index != -1) { // leaf = leaf.substring(0, index); // } // // return leaf; // } // // public static String getFileExtension(String path) { // int index = path.lastIndexOf('.'); // if (index != -1) { // return path.substring(index); // } // return null; // } // // /** // * Removes media from the provided path. For example D://some_path/some_folder -> some_path/some_folder // * // * @param path The path to remove the media. // * @return A new path if the provided path contained media or an original path otherwise. // */ // public static String getPathWithoutMedia(String path) { // String normalisedPath = expand(path); // // int index = normalisedPath.indexOf(':' + FILE_SEPARATOR); // if (index != -1) { // normalisedPath = normalisedPath.substring(index + 1 + FILE_SEPARATOR.length()); // } // // return normalisedPath; // } // // public static String expand(String path) { // String expandedPath = path; // if (expandedPath != null) { // Matcher matcher = ENV_VAR.matcher(expandedPath); // while (matcher.find()) { // String envVar = matcher.group(); // // String expVar = System.getenv(envVar); // if (expVar != null) { // expandedPath = expandedPath.replace(String.format("${%s}", envVar), expVar); // } // // expVar = System.getProperty(envVar); // if (expVar != null) { // expandedPath = expandedPath.replace(String.format("${%s}", envVar), expVar); // } // } // } // return normalise(expandedPath); // } // // public static String append(String path1, String path2) { // StringBuilder path = new StringBuilder(); // // if (path1 != null) { // path.append(path1); // path.append(FILE_SEPARATOR); // } // // if (path2 != null) { // path.append(path2); // } // // return expand(path.toString()); // } // // public static String getParent(String path) { // if (path != null) { // String normalisedPath = expand(path); // if (normalisedPath.endsWith(FILE_SEPARATOR)) { // normalisedPath = normalisedPath.substring(0, normalisedPath.length() - FILE_SEPARATOR.length()); // } // // int index = normalisedPath.lastIndexOf(FILE_SEPARATOR); // if (index != -1) { // return normalisedPath.substring(0, index); // } // } // return path; // } // // public static String getLeaf(String path) { // if (path != null) { // String normalisedPath = expand(path); // if (normalisedPath.endsWith(FILE_SEPARATOR)) { // normalisedPath = normalisedPath.substring(0, normalisedPath.length() - FILE_SEPARATOR.length()); // } // // int index = normalisedPath.lastIndexOf(FILE_SEPARATOR); // if (index != -1) { // return normalisedPath.substring(index + 1); // } // } // return path; // } // // public static String normalise(String path) { // try { // return new File(path).getCanonicalPath(); // } // catch (IOException e) { // logger.warn(e, "Failed to canonicalize the path: '%s'", path); // return path; // } // } // //endregion // }
import hrider.io.PathHelper;
* @return A size of the batch. */ public int getBatchSizeForWrite() { return get(Integer.class, KEY_BATCH_WRITE_SIZE, DEFAULT_BATCH_WRITE_SIZE); } /** * Gets an amount of time to wait for hbase connection during check. * * @return An amount of time to wait. */ public long getConnectionCheckTimeout() { return get(Long.class, KEY_CONNECTION_CHECK_TIMEOUT, DEFAULT_CONNECTION_CHECK_TIMEOUT); } /** * Gets an amount of time to wait before stopping row count operation. * * @return An amount of time to wait. */ public long getRowCountTimeout() { return get(Long.class, KEY_ROW_COUNT_OPERATION_TIMEOUT, DEFAULT_ROW_COUNT_OPERATION_TIMEOUT); } /** * Gets a folder where the compiled classes of the custom converters should be located. * * @return A path to the folder. */ public String getConvertersClassesFolder() {
// Path: src/main/java/hrider/io/PathHelper.java // public class PathHelper { // // //region Constants // public final static String FILE_SEPARATOR = System.getProperty("file.separator"); // public final static String LINE_SEPARATOR = System.getProperty("line.separator"); // // private final static Log logger = Log.getLogger(PathHelper.class); // private final static Pattern ENV_VAR = Pattern.compile("((?<=\\$\\{)[a-zA-Z_0-9]*(?=\\}))"); // //endregion // // //region Constructor // private PathHelper() { // } // //endregion // // //region Public Methods // // /** // * Gets current folder of the executing process. // * // * @return A path to the current folder. // */ // public static String getCurrentFolder() { // return normalise("."); // } // // /** // * Removes extension from the file path. // * // * @param path The path to remove extension. // * @return A new path if the provided path contained extension or an original path otherwise. // */ // public static String getPathWithoutExtension(String path) { // String normalisedPath = expand(path); // // int index = normalisedPath.lastIndexOf('.'); // if (index != -1) { // normalisedPath = normalisedPath.substring(0, index); // } // // return normalisedPath; // } // // public static String getFileNameWithoutExtension(String path) { // String leaf = getLeaf(path); // // int index = leaf.lastIndexOf('.'); // if (index != -1) { // leaf = leaf.substring(0, index); // } // // return leaf; // } // // public static String getFileExtension(String path) { // int index = path.lastIndexOf('.'); // if (index != -1) { // return path.substring(index); // } // return null; // } // // /** // * Removes media from the provided path. For example D://some_path/some_folder -> some_path/some_folder // * // * @param path The path to remove the media. // * @return A new path if the provided path contained media or an original path otherwise. // */ // public static String getPathWithoutMedia(String path) { // String normalisedPath = expand(path); // // int index = normalisedPath.indexOf(':' + FILE_SEPARATOR); // if (index != -1) { // normalisedPath = normalisedPath.substring(index + 1 + FILE_SEPARATOR.length()); // } // // return normalisedPath; // } // // public static String expand(String path) { // String expandedPath = path; // if (expandedPath != null) { // Matcher matcher = ENV_VAR.matcher(expandedPath); // while (matcher.find()) { // String envVar = matcher.group(); // // String expVar = System.getenv(envVar); // if (expVar != null) { // expandedPath = expandedPath.replace(String.format("${%s}", envVar), expVar); // } // // expVar = System.getProperty(envVar); // if (expVar != null) { // expandedPath = expandedPath.replace(String.format("${%s}", envVar), expVar); // } // } // } // return normalise(expandedPath); // } // // public static String append(String path1, String path2) { // StringBuilder path = new StringBuilder(); // // if (path1 != null) { // path.append(path1); // path.append(FILE_SEPARATOR); // } // // if (path2 != null) { // path.append(path2); // } // // return expand(path.toString()); // } // // public static String getParent(String path) { // if (path != null) { // String normalisedPath = expand(path); // if (normalisedPath.endsWith(FILE_SEPARATOR)) { // normalisedPath = normalisedPath.substring(0, normalisedPath.length() - FILE_SEPARATOR.length()); // } // // int index = normalisedPath.lastIndexOf(FILE_SEPARATOR); // if (index != -1) { // return normalisedPath.substring(0, index); // } // } // return path; // } // // public static String getLeaf(String path) { // if (path != null) { // String normalisedPath = expand(path); // if (normalisedPath.endsWith(FILE_SEPARATOR)) { // normalisedPath = normalisedPath.substring(0, normalisedPath.length() - FILE_SEPARATOR.length()); // } // // int index = normalisedPath.lastIndexOf(FILE_SEPARATOR); // if (index != -1) { // return normalisedPath.substring(index + 1); // } // } // return path; // } // // public static String normalise(String path) { // try { // return new File(path).getCanonicalPath(); // } // catch (IOException e) { // logger.warn(e, "Failed to canonicalize the path: '%s'", path); // return path; // } // } // //endregion // } // Path: src/main/java/hrider/config/GlobalConfig.java import hrider.io.PathHelper; * @return A size of the batch. */ public int getBatchSizeForWrite() { return get(Integer.class, KEY_BATCH_WRITE_SIZE, DEFAULT_BATCH_WRITE_SIZE); } /** * Gets an amount of time to wait for hbase connection during check. * * @return An amount of time to wait. */ public long getConnectionCheckTimeout() { return get(Long.class, KEY_CONNECTION_CHECK_TIMEOUT, DEFAULT_CONNECTION_CHECK_TIMEOUT); } /** * Gets an amount of time to wait before stopping row count operation. * * @return An amount of time to wait. */ public long getRowCountTimeout() { return get(Long.class, KEY_ROW_COUNT_OPERATION_TIMEOUT, DEFAULT_ROW_COUNT_OPERATION_TIMEOUT); } /** * Gets a folder where the compiled classes of the custom converters should be located. * * @return A path to the folder. */ public String getConvertersClassesFolder() {
return PathHelper.append(PathHelper.getCurrentFolder(), get(String.class, KEY_CONVERTERS_CLASSES_FOLDER, DEFAULT_CONVERTERS_CLASSES_FOLDER));
NiceSystems/hrider
src/main/java/hrider/ui/controls/format/FormatEditor.java
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // }
import hrider.converters.TypeConverter; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
*/ public String getText() { return textPane.getText(); } /** * Sets the new text into the editor. * * @param text The new text to set. */ public void setText(String text) { textField.setText(text); textPane.setText(text); } /** * Sets the value indicating if the text can be edited. * * @param editable The value to set. */ public void setEditable(Boolean editable) { textPane.setEditable(editable); saveButton.setEnabled(editable); } /** * Sets the type converter to format the data. * * @param typeConverter The type converter to set. */
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // } // Path: src/main/java/hrider/ui/controls/format/FormatEditor.java import hrider.converters.TypeConverter; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; */ public String getText() { return textPane.getText(); } /** * Sets the new text into the editor. * * @param text The new text to set. */ public void setText(String text) { textField.setText(text); textPane.setText(text); } /** * Sets the value indicating if the text can be edited. * * @param editable The value to set. */ public void setEditable(Boolean editable) { textPane.setEditable(editable); saveButton.setEnabled(editable); } /** * Sets the type converter to format the data. * * @param typeConverter The type converter to set. */
public void setTypeConverter(TypeConverter typeConverter) {
NiceSystems/hrider
src/main/java/hrider/data/ColumnQualifier.java
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // } // // Path: src/main/java/hrider/io/Log.java // public class Log { // // //region Variables // private Logger logger; // //endregion // // //region Constructor // private Log(Class<?> clazz) { // logger = Logger.getLogger(clazz); // } // //endregion // // //region Public Methods // public static Log getLogger(Class<?> clazz) { // return new Log(clazz); // } // // public void info(String format, Object... args) { // logger.info(String.format(format, args)); // } // // public void debug(String format, Object... args) { // logger.debug(String.format(format, args)); // } // // public void warn(Throwable t, String format, Object... args) { // logger.warn(String.format(format, args), t); // } // // public void error(Throwable t, String format, Object... args) { // logger.error(String.format(format, args), t); // } // //endregion // }
import hrider.converters.TypeConverter; import hrider.io.Log; import java.io.Serializable; import java.util.Arrays;
package hrider.data; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a column qualifier. */ public class ColumnQualifier implements Serializable { //region Constants public final static ColumnQualifier KEY = new ColumnQualifier("key", ColumnType.BinaryString.getConverter()); //endregion //region Variables
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // } // // Path: src/main/java/hrider/io/Log.java // public class Log { // // //region Variables // private Logger logger; // //endregion // // //region Constructor // private Log(Class<?> clazz) { // logger = Logger.getLogger(clazz); // } // //endregion // // //region Public Methods // public static Log getLogger(Class<?> clazz) { // return new Log(clazz); // } // // public void info(String format, Object... args) { // logger.info(String.format(format, args)); // } // // public void debug(String format, Object... args) { // logger.debug(String.format(format, args)); // } // // public void warn(Throwable t, String format, Object... args) { // logger.warn(String.format(format, args), t); // } // // public void error(Throwable t, String format, Object... args) { // logger.error(String.format(format, args), t); // } // //endregion // } // Path: src/main/java/hrider/data/ColumnQualifier.java import hrider.converters.TypeConverter; import hrider.io.Log; import java.io.Serializable; import java.util.Arrays; package hrider.data; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a column qualifier. */ public class ColumnQualifier implements Serializable { //region Constants public final static ColumnQualifier KEY = new ColumnQualifier("key", ColumnType.BinaryString.getConverter()); //endregion //region Variables
private static final Log logger = Log.getLogger(ColumnQualifier.class);
NiceSystems/hrider
src/main/java/hrider/data/DataCell.java
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // }
import hrider.converters.TypeConverter; import java.io.Serializable;
* @param type The type to check. * @return True if the value can be converted to the specified type or False otherwise. */ public boolean isOfType(ColumnType type) { return this.convertibleValue.isOfType(type); } /** * Gets cell's type. * * @return The cell's type. */ public ColumnType getType() { return this.convertibleValue.getType(); } /** * Sets a new object type for the cell. * * @param type A new object type. */ public void setType(ColumnType type) { this.convertibleValue.setType(type); } /** * Sets new converter for column name. * * @param converter A new converter to set. */
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // } // Path: src/main/java/hrider/data/DataCell.java import hrider.converters.TypeConverter; import java.io.Serializable; * @param type The type to check. * @return True if the value can be converted to the specified type or False otherwise. */ public boolean isOfType(ColumnType type) { return this.convertibleValue.isOfType(type); } /** * Gets cell's type. * * @return The cell's type. */ public ColumnType getType() { return this.convertibleValue.getType(); } /** * Sets a new object type for the cell. * * @param type A new object type. */ public void setType(ColumnType type) { this.convertibleValue.setType(type); } /** * Sets new converter for column name. * * @param converter A new converter to set. */
public void setColumnNameConverter(TypeConverter converter) {
NiceSystems/hrider
src/main/java/hrider/converters/DateAsLongConverter.java
// Path: src/main/java/hrider/format/DateUtils.java // public class DateUtils { // // private static final Log logger = Log.getLogger(DateUtils.class); // private static final DateFormat df; // // static { // df = new SimpleDateFormat(GlobalConfig.instance().getDateFormat(), Locale.ENGLISH); // df.setTimeZone(TimeZone.getTimeZone(GlobalConfig.instance().getDateTimeZone())); // } // // private DateUtils() { // } // // public static DateFormat getDefaultDateFormat() { // return df; // } // // public static String format(Date date) { // return df.format(date); // } // // public static Date parse(String date) { // try { // return df.parse(date); // } // catch (ParseException e) { // logger.error(e, "Failed to convert Date from string '%s'.", date); // return null; // } // } // }
import hrider.format.DateUtils; import org.apache.hadoop.hbase.util.Bytes; import java.util.Date;
package hrider.converters; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class is responsible for converting data from byte[] to Date represented as Long and vice versa. */ public class DateAsLongConverter extends TypeConverter { private static final long serialVersionUID = 7524770450006316409L; @Override public String toString(byte[] value) { if (value == null) { return null; }
// Path: src/main/java/hrider/format/DateUtils.java // public class DateUtils { // // private static final Log logger = Log.getLogger(DateUtils.class); // private static final DateFormat df; // // static { // df = new SimpleDateFormat(GlobalConfig.instance().getDateFormat(), Locale.ENGLISH); // df.setTimeZone(TimeZone.getTimeZone(GlobalConfig.instance().getDateTimeZone())); // } // // private DateUtils() { // } // // public static DateFormat getDefaultDateFormat() { // return df; // } // // public static String format(Date date) { // return df.format(date); // } // // public static Date parse(String date) { // try { // return df.parse(date); // } // catch (ParseException e) { // logger.error(e, "Failed to convert Date from string '%s'.", date); // return null; // } // } // } // Path: src/main/java/hrider/converters/DateAsLongConverter.java import hrider.format.DateUtils; import org.apache.hadoop.hbase.util.Bytes; import java.util.Date; package hrider.converters; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class is responsible for converting data from byte[] to Date represented as Long and vice versa. */ public class DateAsLongConverter extends TypeConverter { private static final long serialVersionUID = 7524770450006316409L; @Override public String toString(byte[] value) { if (value == null) { return null; }
return DateUtils.format(new Date(Bytes.toLong(value)));
NiceSystems/hrider
src/main/java/hrider/config/ConnectionDetails.java
// Path: src/main/java/hrider/actions/Action.java // public abstract class Action<R> { // // /** // * Executes the action. // * // * @throws Exception Any error. // */ // public abstract R run() throws Exception; // // /** // * The method is called when the error occurred. // * // * @param ex The error. // */ // @SuppressWarnings("NoopMethodInAbstractClass") // public void onError(Exception ex) { // // } // } // // Path: src/main/java/hrider/actions/RunnableAction.java // public class RunnableAction<R> implements Runnable { // // //region Constants // private final static Log logger = Log.getLogger(RunnableAction.class); // //endregion // // //region Variables // private String name; // private Action<R> action; // private Thread thread; // private boolean isRunning; // private boolean interrupted; // private R result; // //endregion // // //region Constructor // public RunnableAction(String name, Action<R> action) { // this.name = name; // this.action = action; // } // //endregion // // //region Public Properties // public R getResult() { // return result; // } // // public boolean isCompleted() { // return !isRunning && !interrupted; // } // // public boolean isRunning() { // return isRunning; // } // //endregion // // //region Public Methods // public static <R> RunnableAction<R> run(String name, Action<R> action) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // return runnableAction; // } // // public static <R> R runAndWait(String name, Action<R> action, long timeout) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // runnableAction.waitOrAbort(timeout); // return runnableAction.result; // } // // public void start() { // if (this.thread == null) { // this.thread = new Thread(this); // this.thread.setName(this.name); // this.thread.setDaemon(true); // this.thread.start(); // // this.isRunning = true; // // logger.info("Action '%s' started.", this.name); // } // } // // public void abort() { // if (this.isRunning) { // this.interrupted = true; // // this.thread.interrupt(); // this.thread = null; // } // } // // public void waitUntil(long timeout) { // StopWatch stopWatch = new StopWatch(); // stopWatch.start(); // // long localTimeout = timeout / 10; // // while (this.isRunning) { // try { // Thread.sleep(localTimeout); // // if (stopWatch.getTime() > timeout) { // break; // } // } // catch (InterruptedException ignore) { // } // } // // stopWatch.stop(); // } // // public void waitOrAbort(long timeout) { // waitUntil(timeout); // // if (this.isRunning) { // abort(); // } // } // // @Override // public void run() { // try { // this.result = action.run(); // this.isRunning = false; // // logger.info("Action '%s' completed.", this.name); // } // catch (Exception e) { // this.isRunning = false; // // if (this.interrupted) { // logger.info("Action '%s' aborted.", this.name); // } // else { // logger.info("Action '%s' failed.", this.name); // this.action.onError(e); // } // } // } // //endregion // } // // Path: src/main/java/hrider/hbase/ConnectionManager.java // public class ConnectionManager { // // private static Map<ConnectionDetails, Connection> connections; // // private ConnectionManager() { // } // // static { // connections = new HashMap<ConnectionDetails, Connection>(); // } // // public static Connection create(ConnectionDetails details) throws IOException { // Connection connection = connections.get(details); // if (connection == null) { // connection = new Connection(details); // connections.put(details, connection); // } // return connection; // } // // public static void release(ConnectionDetails details) { // connections.remove(details); // } // }
import hrider.actions.Action; import hrider.actions.RunnableAction; import hrider.hbase.ConnectionManager; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import java.io.IOException; import java.io.Serializable;
package hrider.config; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a data to be used to connect to the hbase and zookeeper nodes. */ public class ConnectionDetails implements Serializable { //region Constants private static final long serialVersionUID = -5808921673890223877L; //endregion //region Variables private ServerDetails zookeeper; //endregion //region Public Properties public ServerDetails getZookeeper() { return this.zookeeper; } public void setZookeeper(ServerDetails zookeeper) { this.zookeeper = zookeeper; } //endregion //region Public Methods public boolean canConnect() {
// Path: src/main/java/hrider/actions/Action.java // public abstract class Action<R> { // // /** // * Executes the action. // * // * @throws Exception Any error. // */ // public abstract R run() throws Exception; // // /** // * The method is called when the error occurred. // * // * @param ex The error. // */ // @SuppressWarnings("NoopMethodInAbstractClass") // public void onError(Exception ex) { // // } // } // // Path: src/main/java/hrider/actions/RunnableAction.java // public class RunnableAction<R> implements Runnable { // // //region Constants // private final static Log logger = Log.getLogger(RunnableAction.class); // //endregion // // //region Variables // private String name; // private Action<R> action; // private Thread thread; // private boolean isRunning; // private boolean interrupted; // private R result; // //endregion // // //region Constructor // public RunnableAction(String name, Action<R> action) { // this.name = name; // this.action = action; // } // //endregion // // //region Public Properties // public R getResult() { // return result; // } // // public boolean isCompleted() { // return !isRunning && !interrupted; // } // // public boolean isRunning() { // return isRunning; // } // //endregion // // //region Public Methods // public static <R> RunnableAction<R> run(String name, Action<R> action) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // return runnableAction; // } // // public static <R> R runAndWait(String name, Action<R> action, long timeout) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // runnableAction.waitOrAbort(timeout); // return runnableAction.result; // } // // public void start() { // if (this.thread == null) { // this.thread = new Thread(this); // this.thread.setName(this.name); // this.thread.setDaemon(true); // this.thread.start(); // // this.isRunning = true; // // logger.info("Action '%s' started.", this.name); // } // } // // public void abort() { // if (this.isRunning) { // this.interrupted = true; // // this.thread.interrupt(); // this.thread = null; // } // } // // public void waitUntil(long timeout) { // StopWatch stopWatch = new StopWatch(); // stopWatch.start(); // // long localTimeout = timeout / 10; // // while (this.isRunning) { // try { // Thread.sleep(localTimeout); // // if (stopWatch.getTime() > timeout) { // break; // } // } // catch (InterruptedException ignore) { // } // } // // stopWatch.stop(); // } // // public void waitOrAbort(long timeout) { // waitUntil(timeout); // // if (this.isRunning) { // abort(); // } // } // // @Override // public void run() { // try { // this.result = action.run(); // this.isRunning = false; // // logger.info("Action '%s' completed.", this.name); // } // catch (Exception e) { // this.isRunning = false; // // if (this.interrupted) { // logger.info("Action '%s' aborted.", this.name); // } // else { // logger.info("Action '%s' failed.", this.name); // this.action.onError(e); // } // } // } // //endregion // } // // Path: src/main/java/hrider/hbase/ConnectionManager.java // public class ConnectionManager { // // private static Map<ConnectionDetails, Connection> connections; // // private ConnectionManager() { // } // // static { // connections = new HashMap<ConnectionDetails, Connection>(); // } // // public static Connection create(ConnectionDetails details) throws IOException { // Connection connection = connections.get(details); // if (connection == null) { // connection = new Connection(details); // connections.put(details, connection); // } // return connection; // } // // public static void release(ConnectionDetails details) { // connections.remove(details); // } // } // Path: src/main/java/hrider/config/ConnectionDetails.java import hrider.actions.Action; import hrider.actions.RunnableAction; import hrider.hbase.ConnectionManager; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import java.io.IOException; import java.io.Serializable; package hrider.config; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a data to be used to connect to the hbase and zookeeper nodes. */ public class ConnectionDetails implements Serializable { //region Constants private static final long serialVersionUID = -5808921673890223877L; //endregion //region Variables private ServerDetails zookeeper; //endregion //region Public Properties public ServerDetails getZookeeper() { return this.zookeeper; } public void setZookeeper(ServerDetails zookeeper) { this.zookeeper = zookeeper; } //endregion //region Public Methods public boolean canConnect() {
Boolean result = RunnableAction.runAndWait(
NiceSystems/hrider
src/main/java/hrider/config/ConnectionDetails.java
// Path: src/main/java/hrider/actions/Action.java // public abstract class Action<R> { // // /** // * Executes the action. // * // * @throws Exception Any error. // */ // public abstract R run() throws Exception; // // /** // * The method is called when the error occurred. // * // * @param ex The error. // */ // @SuppressWarnings("NoopMethodInAbstractClass") // public void onError(Exception ex) { // // } // } // // Path: src/main/java/hrider/actions/RunnableAction.java // public class RunnableAction<R> implements Runnable { // // //region Constants // private final static Log logger = Log.getLogger(RunnableAction.class); // //endregion // // //region Variables // private String name; // private Action<R> action; // private Thread thread; // private boolean isRunning; // private boolean interrupted; // private R result; // //endregion // // //region Constructor // public RunnableAction(String name, Action<R> action) { // this.name = name; // this.action = action; // } // //endregion // // //region Public Properties // public R getResult() { // return result; // } // // public boolean isCompleted() { // return !isRunning && !interrupted; // } // // public boolean isRunning() { // return isRunning; // } // //endregion // // //region Public Methods // public static <R> RunnableAction<R> run(String name, Action<R> action) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // return runnableAction; // } // // public static <R> R runAndWait(String name, Action<R> action, long timeout) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // runnableAction.waitOrAbort(timeout); // return runnableAction.result; // } // // public void start() { // if (this.thread == null) { // this.thread = new Thread(this); // this.thread.setName(this.name); // this.thread.setDaemon(true); // this.thread.start(); // // this.isRunning = true; // // logger.info("Action '%s' started.", this.name); // } // } // // public void abort() { // if (this.isRunning) { // this.interrupted = true; // // this.thread.interrupt(); // this.thread = null; // } // } // // public void waitUntil(long timeout) { // StopWatch stopWatch = new StopWatch(); // stopWatch.start(); // // long localTimeout = timeout / 10; // // while (this.isRunning) { // try { // Thread.sleep(localTimeout); // // if (stopWatch.getTime() > timeout) { // break; // } // } // catch (InterruptedException ignore) { // } // } // // stopWatch.stop(); // } // // public void waitOrAbort(long timeout) { // waitUntil(timeout); // // if (this.isRunning) { // abort(); // } // } // // @Override // public void run() { // try { // this.result = action.run(); // this.isRunning = false; // // logger.info("Action '%s' completed.", this.name); // } // catch (Exception e) { // this.isRunning = false; // // if (this.interrupted) { // logger.info("Action '%s' aborted.", this.name); // } // else { // logger.info("Action '%s' failed.", this.name); // this.action.onError(e); // } // } // } // //endregion // } // // Path: src/main/java/hrider/hbase/ConnectionManager.java // public class ConnectionManager { // // private static Map<ConnectionDetails, Connection> connections; // // private ConnectionManager() { // } // // static { // connections = new HashMap<ConnectionDetails, Connection>(); // } // // public static Connection create(ConnectionDetails details) throws IOException { // Connection connection = connections.get(details); // if (connection == null) { // connection = new Connection(details); // connections.put(details, connection); // } // return connection; // } // // public static void release(ConnectionDetails details) { // connections.remove(details); // } // }
import hrider.actions.Action; import hrider.actions.RunnableAction; import hrider.hbase.ConnectionManager; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import java.io.IOException; import java.io.Serializable;
package hrider.config; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a data to be used to connect to the hbase and zookeeper nodes. */ public class ConnectionDetails implements Serializable { //region Constants private static final long serialVersionUID = -5808921673890223877L; //endregion //region Variables private ServerDetails zookeeper; //endregion //region Public Properties public ServerDetails getZookeeper() { return this.zookeeper; } public void setZookeeper(ServerDetails zookeeper) { this.zookeeper = zookeeper; } //endregion //region Public Methods public boolean canConnect() { Boolean result = RunnableAction.runAndWait(
// Path: src/main/java/hrider/actions/Action.java // public abstract class Action<R> { // // /** // * Executes the action. // * // * @throws Exception Any error. // */ // public abstract R run() throws Exception; // // /** // * The method is called when the error occurred. // * // * @param ex The error. // */ // @SuppressWarnings("NoopMethodInAbstractClass") // public void onError(Exception ex) { // // } // } // // Path: src/main/java/hrider/actions/RunnableAction.java // public class RunnableAction<R> implements Runnable { // // //region Constants // private final static Log logger = Log.getLogger(RunnableAction.class); // //endregion // // //region Variables // private String name; // private Action<R> action; // private Thread thread; // private boolean isRunning; // private boolean interrupted; // private R result; // //endregion // // //region Constructor // public RunnableAction(String name, Action<R> action) { // this.name = name; // this.action = action; // } // //endregion // // //region Public Properties // public R getResult() { // return result; // } // // public boolean isCompleted() { // return !isRunning && !interrupted; // } // // public boolean isRunning() { // return isRunning; // } // //endregion // // //region Public Methods // public static <R> RunnableAction<R> run(String name, Action<R> action) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // return runnableAction; // } // // public static <R> R runAndWait(String name, Action<R> action, long timeout) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // runnableAction.waitOrAbort(timeout); // return runnableAction.result; // } // // public void start() { // if (this.thread == null) { // this.thread = new Thread(this); // this.thread.setName(this.name); // this.thread.setDaemon(true); // this.thread.start(); // // this.isRunning = true; // // logger.info("Action '%s' started.", this.name); // } // } // // public void abort() { // if (this.isRunning) { // this.interrupted = true; // // this.thread.interrupt(); // this.thread = null; // } // } // // public void waitUntil(long timeout) { // StopWatch stopWatch = new StopWatch(); // stopWatch.start(); // // long localTimeout = timeout / 10; // // while (this.isRunning) { // try { // Thread.sleep(localTimeout); // // if (stopWatch.getTime() > timeout) { // break; // } // } // catch (InterruptedException ignore) { // } // } // // stopWatch.stop(); // } // // public void waitOrAbort(long timeout) { // waitUntil(timeout); // // if (this.isRunning) { // abort(); // } // } // // @Override // public void run() { // try { // this.result = action.run(); // this.isRunning = false; // // logger.info("Action '%s' completed.", this.name); // } // catch (Exception e) { // this.isRunning = false; // // if (this.interrupted) { // logger.info("Action '%s' aborted.", this.name); // } // else { // logger.info("Action '%s' failed.", this.name); // this.action.onError(e); // } // } // } // //endregion // } // // Path: src/main/java/hrider/hbase/ConnectionManager.java // public class ConnectionManager { // // private static Map<ConnectionDetails, Connection> connections; // // private ConnectionManager() { // } // // static { // connections = new HashMap<ConnectionDetails, Connection>(); // } // // public static Connection create(ConnectionDetails details) throws IOException { // Connection connection = connections.get(details); // if (connection == null) { // connection = new Connection(details); // connections.put(details, connection); // } // return connection; // } // // public static void release(ConnectionDetails details) { // connections.remove(details); // } // } // Path: src/main/java/hrider/config/ConnectionDetails.java import hrider.actions.Action; import hrider.actions.RunnableAction; import hrider.hbase.ConnectionManager; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import java.io.IOException; import java.io.Serializable; package hrider.config; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a data to be used to connect to the hbase and zookeeper nodes. */ public class ConnectionDetails implements Serializable { //region Constants private static final long serialVersionUID = -5808921673890223877L; //endregion //region Variables private ServerDetails zookeeper; //endregion //region Public Properties public ServerDetails getZookeeper() { return this.zookeeper; } public void setZookeeper(ServerDetails zookeeper) { this.zookeeper = zookeeper; } //endregion //region Public Methods public boolean canConnect() { Boolean result = RunnableAction.runAndWait(
this.zookeeper.getHost(), new Action<Boolean>() {
NiceSystems/hrider
src/main/java/hrider/config/ConnectionDetails.java
// Path: src/main/java/hrider/actions/Action.java // public abstract class Action<R> { // // /** // * Executes the action. // * // * @throws Exception Any error. // */ // public abstract R run() throws Exception; // // /** // * The method is called when the error occurred. // * // * @param ex The error. // */ // @SuppressWarnings("NoopMethodInAbstractClass") // public void onError(Exception ex) { // // } // } // // Path: src/main/java/hrider/actions/RunnableAction.java // public class RunnableAction<R> implements Runnable { // // //region Constants // private final static Log logger = Log.getLogger(RunnableAction.class); // //endregion // // //region Variables // private String name; // private Action<R> action; // private Thread thread; // private boolean isRunning; // private boolean interrupted; // private R result; // //endregion // // //region Constructor // public RunnableAction(String name, Action<R> action) { // this.name = name; // this.action = action; // } // //endregion // // //region Public Properties // public R getResult() { // return result; // } // // public boolean isCompleted() { // return !isRunning && !interrupted; // } // // public boolean isRunning() { // return isRunning; // } // //endregion // // //region Public Methods // public static <R> RunnableAction<R> run(String name, Action<R> action) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // return runnableAction; // } // // public static <R> R runAndWait(String name, Action<R> action, long timeout) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // runnableAction.waitOrAbort(timeout); // return runnableAction.result; // } // // public void start() { // if (this.thread == null) { // this.thread = new Thread(this); // this.thread.setName(this.name); // this.thread.setDaemon(true); // this.thread.start(); // // this.isRunning = true; // // logger.info("Action '%s' started.", this.name); // } // } // // public void abort() { // if (this.isRunning) { // this.interrupted = true; // // this.thread.interrupt(); // this.thread = null; // } // } // // public void waitUntil(long timeout) { // StopWatch stopWatch = new StopWatch(); // stopWatch.start(); // // long localTimeout = timeout / 10; // // while (this.isRunning) { // try { // Thread.sleep(localTimeout); // // if (stopWatch.getTime() > timeout) { // break; // } // } // catch (InterruptedException ignore) { // } // } // // stopWatch.stop(); // } // // public void waitOrAbort(long timeout) { // waitUntil(timeout); // // if (this.isRunning) { // abort(); // } // } // // @Override // public void run() { // try { // this.result = action.run(); // this.isRunning = false; // // logger.info("Action '%s' completed.", this.name); // } // catch (Exception e) { // this.isRunning = false; // // if (this.interrupted) { // logger.info("Action '%s' aborted.", this.name); // } // else { // logger.info("Action '%s' failed.", this.name); // this.action.onError(e); // } // } // } // //endregion // } // // Path: src/main/java/hrider/hbase/ConnectionManager.java // public class ConnectionManager { // // private static Map<ConnectionDetails, Connection> connections; // // private ConnectionManager() { // } // // static { // connections = new HashMap<ConnectionDetails, Connection>(); // } // // public static Connection create(ConnectionDetails details) throws IOException { // Connection connection = connections.get(details); // if (connection == null) { // connection = new Connection(details); // connections.put(details, connection); // } // return connection; // } // // public static void release(ConnectionDetails details) { // connections.remove(details); // } // }
import hrider.actions.Action; import hrider.actions.RunnableAction; import hrider.hbase.ConnectionManager; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import java.io.IOException; import java.io.Serializable;
package hrider.config; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a data to be used to connect to the hbase and zookeeper nodes. */ public class ConnectionDetails implements Serializable { //region Constants private static final long serialVersionUID = -5808921673890223877L; //endregion //region Variables private ServerDetails zookeeper; //endregion //region Public Properties public ServerDetails getZookeeper() { return this.zookeeper; } public void setZookeeper(ServerDetails zookeeper) { this.zookeeper = zookeeper; } //endregion //region Public Methods public boolean canConnect() { Boolean result = RunnableAction.runAndWait( this.zookeeper.getHost(), new Action<Boolean>() { @Override public Boolean run() throws IOException {
// Path: src/main/java/hrider/actions/Action.java // public abstract class Action<R> { // // /** // * Executes the action. // * // * @throws Exception Any error. // */ // public abstract R run() throws Exception; // // /** // * The method is called when the error occurred. // * // * @param ex The error. // */ // @SuppressWarnings("NoopMethodInAbstractClass") // public void onError(Exception ex) { // // } // } // // Path: src/main/java/hrider/actions/RunnableAction.java // public class RunnableAction<R> implements Runnable { // // //region Constants // private final static Log logger = Log.getLogger(RunnableAction.class); // //endregion // // //region Variables // private String name; // private Action<R> action; // private Thread thread; // private boolean isRunning; // private boolean interrupted; // private R result; // //endregion // // //region Constructor // public RunnableAction(String name, Action<R> action) { // this.name = name; // this.action = action; // } // //endregion // // //region Public Properties // public R getResult() { // return result; // } // // public boolean isCompleted() { // return !isRunning && !interrupted; // } // // public boolean isRunning() { // return isRunning; // } // //endregion // // //region Public Methods // public static <R> RunnableAction<R> run(String name, Action<R> action) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // return runnableAction; // } // // public static <R> R runAndWait(String name, Action<R> action, long timeout) { // RunnableAction<R> runnableAction = new RunnableAction<R>(name, action); // runnableAction.start(); // // runnableAction.waitOrAbort(timeout); // return runnableAction.result; // } // // public void start() { // if (this.thread == null) { // this.thread = new Thread(this); // this.thread.setName(this.name); // this.thread.setDaemon(true); // this.thread.start(); // // this.isRunning = true; // // logger.info("Action '%s' started.", this.name); // } // } // // public void abort() { // if (this.isRunning) { // this.interrupted = true; // // this.thread.interrupt(); // this.thread = null; // } // } // // public void waitUntil(long timeout) { // StopWatch stopWatch = new StopWatch(); // stopWatch.start(); // // long localTimeout = timeout / 10; // // while (this.isRunning) { // try { // Thread.sleep(localTimeout); // // if (stopWatch.getTime() > timeout) { // break; // } // } // catch (InterruptedException ignore) { // } // } // // stopWatch.stop(); // } // // public void waitOrAbort(long timeout) { // waitUntil(timeout); // // if (this.isRunning) { // abort(); // } // } // // @Override // public void run() { // try { // this.result = action.run(); // this.isRunning = false; // // logger.info("Action '%s' completed.", this.name); // } // catch (Exception e) { // this.isRunning = false; // // if (this.interrupted) { // logger.info("Action '%s' aborted.", this.name); // } // else { // logger.info("Action '%s' failed.", this.name); // this.action.onError(e); // } // } // } // //endregion // } // // Path: src/main/java/hrider/hbase/ConnectionManager.java // public class ConnectionManager { // // private static Map<ConnectionDetails, Connection> connections; // // private ConnectionManager() { // } // // static { // connections = new HashMap<ConnectionDetails, Connection>(); // } // // public static Connection create(ConnectionDetails details) throws IOException { // Connection connection = connections.get(details); // if (connection == null) { // connection = new Connection(details); // connections.put(details, connection); // } // return connection; // } // // public static void release(ConnectionDetails details) { // connections.remove(details); // } // } // Path: src/main/java/hrider/config/ConnectionDetails.java import hrider.actions.Action; import hrider.actions.RunnableAction; import hrider.hbase.ConnectionManager; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import java.io.IOException; import java.io.Serializable; package hrider.config; /** * Copyright (C) 2012 NICE Systems ltd. * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Igor Cher * @version %I%, %G% * <p/> * This class represents a data to be used to connect to the hbase and zookeeper nodes. */ public class ConnectionDetails implements Serializable { //region Constants private static final long serialVersionUID = -5808921673890223877L; //endregion //region Variables private ServerDetails zookeeper; //endregion //region Public Properties public ServerDetails getZookeeper() { return this.zookeeper; } public void setZookeeper(ServerDetails zookeeper) { this.zookeeper = zookeeper; } //endregion //region Public Methods public boolean canConnect() { Boolean result = RunnableAction.runAndWait( this.zookeeper.getHost(), new Action<Boolean>() { @Override public Boolean run() throws IOException {
ConnectionManager.create(ConnectionDetails.this);
NiceSystems/hrider
src/main/java/hrider/data/DataRow.java
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // }
import hrider.converters.TypeConverter; import java.io.Serializable; import java.util.HashMap; import java.util.Map;
* * @param columnType The type to check. * @return True if the value can be converted to the specified type or False otherwise. */ public boolean isCellOfType(String columnName, ColumnType columnType) { DataCell cell = getCell(columnName); if (cell != null) { return cell.isOfType(columnType); } return true; } /** * Updates a column type for all cells that belong to the specified column. * * @param columnName The name of the column which type should be updated. * @param columnType The new column type. */ public void updateColumnType(String columnName, ColumnType columnType) { DataCell cell = getCell(columnName); if (cell != null) { cell.setType(columnType); } } /** * Updates converter for the column name. * * @param converter The new column name converter. */
// Path: src/main/java/hrider/converters/TypeConverter.java // @SuppressWarnings("CallToSimpleGetterFromWithinClass") // public abstract class TypeConverter implements Comparable<TypeConverter>, Serializable { // // //region Constants // protected static final Log logger = Log.getLogger(TypeConverter.class); // protected static final byte[] EMPTY_BYTES_ARRAY = new byte[0]; // // private static final long serialVersionUID = 1490434164342371320L; // //endregion // // //region Variables // private String name; // private String code; // //endregion // // //region Constructor // protected TypeConverter() { // this.name = this.getClass().getSimpleName().replace("Converter", ""); // } // //endregion // // //region Public Methods // // /** // * Gets the code of the type converter if available. // * // * @return The original code. // */ // public String getCode() { // return code; // } // // /** // * Sets the code for the type converter. // * // * @param code The code to set. // */ // public void setCode(String code) { // this.code = code; // } // // /** // * Gets the name of the converter to be presented as a column type. // * // * @return The name of the converter. // */ // public String getName() { // return this.name; // } // // /** // * Checks whether the type converter can be edited. // * // * @return True if the type converter can be edited or False otherwise. // */ // public boolean isEditable() { // return code != null; // } // // /** // * Indicates whether the type converter can be used for column name conversions. // * // * @return True if the type converter can be used for column name conversions or False otherwise. // */ // public boolean isValidForNameConversion() { // return false; // } // // /** // * Converts an {@link String} to an array of bytes. // * // * @param value An string to convert. // * @return A converted byte array. // */ // public abstract byte[] toBytes(String value); // // /** // * Converts an {@link byte[]} to a {@link String}. // * // * @param value An byte[] to convert. // * @return A converted string. // */ // public abstract String toString(byte[] value); // // /** // * Checks whether the provided value can be converted to the type supported by this converter. // * // * @param value The value to check. // * @return True if the value can be converted by the converter to the required type of False otherwise. // */ // public abstract boolean canConvert(byte[] value); // // /** // * Indicates whether the type converter supports formatting of the data. // * // * @return True if the type converter can be used to format the data or False otherwise. // */ // public abstract boolean supportsFormatting(); // // /** // * Gets the mapping between the regular expression and the color to be used for drawing the text. // * // * @return The color to regular expression mappings. // */ // public Map<Pattern, Color> getColorMappings() { // return null; // } // // /** // * Apply the custom formatting on the data. // * // * @param value The data to format. // * @return The formatted data. // */ // public String format(String value) { // return value; // } // // @Override // public int compareTo(TypeConverter o) { // return this.getName().compareTo(o.getName()); // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // // if (TypeConverter.class.isAssignableFrom(obj.getClass())) { // return getName().equals(((TypeConverter)obj).getName()); // } // // return false; // } // // @Override // public int hashCode() { // return getName().hashCode(); // } // // @Override // public String toString() { // return getName(); // } // //endregion // } // Path: src/main/java/hrider/data/DataRow.java import hrider.converters.TypeConverter; import java.io.Serializable; import java.util.HashMap; import java.util.Map; * * @param columnType The type to check. * @return True if the value can be converted to the specified type or False otherwise. */ public boolean isCellOfType(String columnName, ColumnType columnType) { DataCell cell = getCell(columnName); if (cell != null) { return cell.isOfType(columnType); } return true; } /** * Updates a column type for all cells that belong to the specified column. * * @param columnName The name of the column which type should be updated. * @param columnType The new column type. */ public void updateColumnType(String columnName, ColumnType columnType) { DataCell cell = getCell(columnName); if (cell != null) { cell.setType(columnType); } } /** * Updates converter for the column name. * * @param converter The new column name converter. */
public void updateColumnNameConverter(TypeConverter converter) {
Copyleaks/Java-Plagiarism-Checker
src/copyleaks/sdk/api/exceptions/SecurityTokenException.java
// Path: src/copyleaks/sdk/api/models/LoginToken.java // public class LoginToken implements Serializable // { // /** // * For Serializable implementation. // */ // private static final long serialVersionUID = 1L; // // public LoginToken(String token, Date issued, Date expire) // { // setTemporarySecurityCode(token); // setIssued(issued); // setExpire(expire); // } // // @SerializedName("access_token") // private String TemporarySecurityCode; // // public String getTemporarySecurityCode() // { // return TemporarySecurityCode; // } // // private void setTemporarySecurityCode(String token) // { // this.TemporarySecurityCode = token; // } // // @SerializedName(".issued") // private Date Issued; // // Date getIssued() // { // return Issued; // } // // private void setIssued(Date issued) // { // this.Issued = issued; // } // // @SerializedName(".expires") // private Date Expire; // // public Date getExpire() // { // return Expire; // } // // private void setExpire(Date expire) // { // this.Expire = expire; // } // // @SerializedName("userName") // private String UserName; // // public String getUserName() // { // return UserName; // } // // @SerializedName("token_type") // private String TokenType; // // public String getTokenType() // { // return TokenType; // } // // void setUsername(String tokenType) // { // this.TokenType = tokenType; // } // // /// <summary> // /// Validate that the token is valid. If isn't valid, throw // /// UnauthorizedAccessException. // /// </summary> // /// <exception cref="UnauthorizedAccessException">This token is // /// expired</exception> // private void Validate() // throws SecurityTokenException // { // /* // Date currentDate = new Date(); // if (currentDate.after(this.Expire)) // throw new SecurityTokenException(this); // */ // } // // public static void ValidateToken(LoginToken token) // { // if (token == null) // throw new SecurityTokenException(); // else // token.Validate(); // } // // @Override // public String toString() // { // return this.getTemporarySecurityCode(); // } // }
import java.security.AccessControlException; import copyleaks.sdk.api.models.LoginToken;
/******************************************************************************** The MIT License(MIT) Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************************/ package copyleaks.sdk.api.exceptions; public class SecurityTokenException extends AccessControlException { private static final long serialVersionUID = 1L; public SecurityTokenException() { super("Security token is missing!"); this.setToken(null); }
// Path: src/copyleaks/sdk/api/models/LoginToken.java // public class LoginToken implements Serializable // { // /** // * For Serializable implementation. // */ // private static final long serialVersionUID = 1L; // // public LoginToken(String token, Date issued, Date expire) // { // setTemporarySecurityCode(token); // setIssued(issued); // setExpire(expire); // } // // @SerializedName("access_token") // private String TemporarySecurityCode; // // public String getTemporarySecurityCode() // { // return TemporarySecurityCode; // } // // private void setTemporarySecurityCode(String token) // { // this.TemporarySecurityCode = token; // } // // @SerializedName(".issued") // private Date Issued; // // Date getIssued() // { // return Issued; // } // // private void setIssued(Date issued) // { // this.Issued = issued; // } // // @SerializedName(".expires") // private Date Expire; // // public Date getExpire() // { // return Expire; // } // // private void setExpire(Date expire) // { // this.Expire = expire; // } // // @SerializedName("userName") // private String UserName; // // public String getUserName() // { // return UserName; // } // // @SerializedName("token_type") // private String TokenType; // // public String getTokenType() // { // return TokenType; // } // // void setUsername(String tokenType) // { // this.TokenType = tokenType; // } // // /// <summary> // /// Validate that the token is valid. If isn't valid, throw // /// UnauthorizedAccessException. // /// </summary> // /// <exception cref="UnauthorizedAccessException">This token is // /// expired</exception> // private void Validate() // throws SecurityTokenException // { // /* // Date currentDate = new Date(); // if (currentDate.after(this.Expire)) // throw new SecurityTokenException(this); // */ // } // // public static void ValidateToken(LoginToken token) // { // if (token == null) // throw new SecurityTokenException(); // else // token.Validate(); // } // // @Override // public String toString() // { // return this.getTemporarySecurityCode(); // } // } // Path: src/copyleaks/sdk/api/exceptions/SecurityTokenException.java import java.security.AccessControlException; import copyleaks.sdk.api.models.LoginToken; /******************************************************************************** The MIT License(MIT) Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************************/ package copyleaks.sdk.api.exceptions; public class SecurityTokenException extends AccessControlException { private static final long serialVersionUID = 1L; public SecurityTokenException() { super("Security token is missing!"); this.setToken(null); }
public SecurityTokenException(LoginToken token)
Copyleaks/Java-Plagiarism-Checker
src/copyleaks/sdk/api/helpers/HttpURLConnection/HttpURLConnectionHelper.java
// Path: src/copyleaks/sdk/api/Settings.java // public class Settings // { // public static final String Encoding = "UTF-8"; // // public static final int NetworkReadTimeout = 30000; // public static final int NetworkConnectTimeout = 15000; // // public static final String ServiceEntryPoint = "https://api.copyleaks.com"; // Service URL. // // public static final String ServiceVersion = "v1"; // Current version of the // // API // // public static final String BusinessesServicePage = "businesses"; // public static final String AcademicServicePage = "academic"; // public static final String WebsitesServicePage = "websites"; // public static final String DownloadsServicePage = "downloads"; // // public static final String USER_AGENT = "CopyleaksJavaSDK/1.1";// User agent // public static final String DateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // }
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Scanner; import copyleaks.sdk.api.Settings;
/******************************************************************************** The MIT License(MIT) Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************************/ package copyleaks.sdk.api.helpers.HttpURLConnection; public final class HttpURLConnectionHelper { public static String getQuery(Map<String, String> dic) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String,String> entry : dic.entrySet()) { if (first) first = false; else result.append("&");
// Path: src/copyleaks/sdk/api/Settings.java // public class Settings // { // public static final String Encoding = "UTF-8"; // // public static final int NetworkReadTimeout = 30000; // public static final int NetworkConnectTimeout = 15000; // // public static final String ServiceEntryPoint = "https://api.copyleaks.com"; // Service URL. // // public static final String ServiceVersion = "v1"; // Current version of the // // API // // public static final String BusinessesServicePage = "businesses"; // public static final String AcademicServicePage = "academic"; // public static final String WebsitesServicePage = "websites"; // public static final String DownloadsServicePage = "downloads"; // // public static final String USER_AGENT = "CopyleaksJavaSDK/1.1";// User agent // public static final String DateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; // } // Path: src/copyleaks/sdk/api/helpers/HttpURLConnection/HttpURLConnectionHelper.java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Map; import java.util.Scanner; import copyleaks.sdk.api.Settings; /******************************************************************************** The MIT License(MIT) Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub-license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ********************************************************************************/ package copyleaks.sdk.api.helpers.HttpURLConnection; public final class HttpURLConnectionHelper { public static String getQuery(Map<String, String> dic) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry<String,String> entry : dic.entrySet()) { if (first) first = false; else result.append("&");
result.append(URLEncoder.encode(entry.getKey(), Settings.Encoding));
Copyleaks/Java-Plagiarism-Checker
src/copyleaks/sdk/api/models/LoginToken.java
// Path: src/copyleaks/sdk/api/exceptions/SecurityTokenException.java // public class SecurityTokenException // extends AccessControlException // { // private static final long serialVersionUID = 1L; // public SecurityTokenException() // { // super("Security token is missing!"); // this.setToken(null); // } // public SecurityTokenException(LoginToken token) // { // super(String.format("This token expired on '%1$s'!", token.getExpire())); // this.setToken(token); // } // // public LoginToken Token; // LoginToken getToken() { // return Token; // } // // private void setToken(LoginToken token) { // Token = token; // } // }
import java.io.Serializable; import java.util.Date; import com.google.gson.annotations.SerializedName; import copyleaks.sdk.api.exceptions.SecurityTokenException;
} @SerializedName("userName") private String UserName; public String getUserName() { return UserName; } @SerializedName("token_type") private String TokenType; public String getTokenType() { return TokenType; } void setUsername(String tokenType) { this.TokenType = tokenType; } /// <summary> /// Validate that the token is valid. If isn't valid, throw /// UnauthorizedAccessException. /// </summary> /// <exception cref="UnauthorizedAccessException">This token is /// expired</exception> private void Validate()
// Path: src/copyleaks/sdk/api/exceptions/SecurityTokenException.java // public class SecurityTokenException // extends AccessControlException // { // private static final long serialVersionUID = 1L; // public SecurityTokenException() // { // super("Security token is missing!"); // this.setToken(null); // } // public SecurityTokenException(LoginToken token) // { // super(String.format("This token expired on '%1$s'!", token.getExpire())); // this.setToken(token); // } // // public LoginToken Token; // LoginToken getToken() { // return Token; // } // // private void setToken(LoginToken token) { // Token = token; // } // } // Path: src/copyleaks/sdk/api/models/LoginToken.java import java.io.Serializable; import java.util.Date; import com.google.gson.annotations.SerializedName; import copyleaks.sdk.api.exceptions.SecurityTokenException; } @SerializedName("userName") private String UserName; public String getUserName() { return UserName; } @SerializedName("token_type") private String TokenType; public String getTokenType() { return TokenType; } void setUsername(String tokenType) { this.TokenType = tokenType; } /// <summary> /// Validate that the token is valid. If isn't valid, throw /// UnauthorizedAccessException. /// </summary> /// <exception cref="UnauthorizedAccessException">This token is /// expired</exception> private void Validate()
throws SecurityTokenException
Copyleaks/Java-Plagiarism-Checker
src/copyleaks/sdk/api/exceptions/CommandFailedException.java
// Path: src/copyleaks/sdk/api/helpers/HttpURLConnection/HttpURLConnectionHelper.java // public final class HttpURLConnectionHelper // { // public static String getQuery(Map<String, String> dic) throws UnsupportedEncodingException // { // StringBuilder result = new StringBuilder(); // boolean first = true; // // for (Map.Entry<String,String> entry : dic.entrySet()) // { // if (first) // first = false; // else // result.append("&"); // // result.append(URLEncoder.encode(entry.getKey(), Settings.Encoding)); // result.append("="); // result.append(URLEncoder.encode(entry.getValue(), Settings.Encoding)); // } // // return result.toString(); // } // // public static String convertStreamToString(java.io.InputStream is) // { // @SuppressWarnings("resource") // java.util.Scanner s = new Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // // } // } // // Path: src/copyleaks/sdk/api/models/responses/BadResponse.java // public class BadResponse { // // public String Message; // // public String getMessage() { // return Message; // } // // @Override // public String toString() // { // return this.getMessage(); // } // }
import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import copyleaks.sdk.api.helpers.HttpURLConnection.HttpURLConnectionHelper; import copyleaks.sdk.api.models.responses.BadResponse; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import com.google.gson.Gson;
return CopyleaksErrorCode; } private void setCopyleaksErrorCode(short errorCode) { CopyleaksErrorCode = errorCode; } public CommandFailedException(HttpURLConnection conn) { super(GetMessage(conn)); try { this.setHttpErrorCode(conn.getResponseCode()); } catch (IOException e) { this.setHttpErrorCode(UNDEFINED_HTTP_ERROR_CODE); } this.setCopyleaksErrorCode(GetCopyleaksErrorCode(conn)); } private static String GetMessage(HttpURLConnection conn) { Gson gson = new GsonBuilder().create(); String errorResponse; try (InputStream inputStream = new BufferedInputStream(conn.getErrorStream())) {
// Path: src/copyleaks/sdk/api/helpers/HttpURLConnection/HttpURLConnectionHelper.java // public final class HttpURLConnectionHelper // { // public static String getQuery(Map<String, String> dic) throws UnsupportedEncodingException // { // StringBuilder result = new StringBuilder(); // boolean first = true; // // for (Map.Entry<String,String> entry : dic.entrySet()) // { // if (first) // first = false; // else // result.append("&"); // // result.append(URLEncoder.encode(entry.getKey(), Settings.Encoding)); // result.append("="); // result.append(URLEncoder.encode(entry.getValue(), Settings.Encoding)); // } // // return result.toString(); // } // // public static String convertStreamToString(java.io.InputStream is) // { // @SuppressWarnings("resource") // java.util.Scanner s = new Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // // } // } // // Path: src/copyleaks/sdk/api/models/responses/BadResponse.java // public class BadResponse { // // public String Message; // // public String getMessage() { // return Message; // } // // @Override // public String toString() // { // return this.getMessage(); // } // } // Path: src/copyleaks/sdk/api/exceptions/CommandFailedException.java import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import copyleaks.sdk.api.helpers.HttpURLConnection.HttpURLConnectionHelper; import copyleaks.sdk.api.models.responses.BadResponse; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import com.google.gson.Gson; return CopyleaksErrorCode; } private void setCopyleaksErrorCode(short errorCode) { CopyleaksErrorCode = errorCode; } public CommandFailedException(HttpURLConnection conn) { super(GetMessage(conn)); try { this.setHttpErrorCode(conn.getResponseCode()); } catch (IOException e) { this.setHttpErrorCode(UNDEFINED_HTTP_ERROR_CODE); } this.setCopyleaksErrorCode(GetCopyleaksErrorCode(conn)); } private static String GetMessage(HttpURLConnection conn) { Gson gson = new GsonBuilder().create(); String errorResponse; try (InputStream inputStream = new BufferedInputStream(conn.getErrorStream())) {
errorResponse = HttpURLConnectionHelper.convertStreamToString(inputStream);
Copyleaks/Java-Plagiarism-Checker
src/copyleaks/sdk/api/exceptions/CommandFailedException.java
// Path: src/copyleaks/sdk/api/helpers/HttpURLConnection/HttpURLConnectionHelper.java // public final class HttpURLConnectionHelper // { // public static String getQuery(Map<String, String> dic) throws UnsupportedEncodingException // { // StringBuilder result = new StringBuilder(); // boolean first = true; // // for (Map.Entry<String,String> entry : dic.entrySet()) // { // if (first) // first = false; // else // result.append("&"); // // result.append(URLEncoder.encode(entry.getKey(), Settings.Encoding)); // result.append("="); // result.append(URLEncoder.encode(entry.getValue(), Settings.Encoding)); // } // // return result.toString(); // } // // public static String convertStreamToString(java.io.InputStream is) // { // @SuppressWarnings("resource") // java.util.Scanner s = new Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // // } // } // // Path: src/copyleaks/sdk/api/models/responses/BadResponse.java // public class BadResponse { // // public String Message; // // public String getMessage() { // return Message; // } // // @Override // public String toString() // { // return this.getMessage(); // } // }
import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import copyleaks.sdk.api.helpers.HttpURLConnection.HttpURLConnectionHelper; import copyleaks.sdk.api.models.responses.BadResponse; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import com.google.gson.Gson;
public CommandFailedException(HttpURLConnection conn) { super(GetMessage(conn)); try { this.setHttpErrorCode(conn.getResponseCode()); } catch (IOException e) { this.setHttpErrorCode(UNDEFINED_HTTP_ERROR_CODE); } this.setCopyleaksErrorCode(GetCopyleaksErrorCode(conn)); } private static String GetMessage(HttpURLConnection conn) { Gson gson = new GsonBuilder().create(); String errorResponse; try (InputStream inputStream = new BufferedInputStream(conn.getErrorStream())) { errorResponse = HttpURLConnectionHelper.convertStreamToString(inputStream); } catch (IOException e) { return e.getMessage(); }
// Path: src/copyleaks/sdk/api/helpers/HttpURLConnection/HttpURLConnectionHelper.java // public final class HttpURLConnectionHelper // { // public static String getQuery(Map<String, String> dic) throws UnsupportedEncodingException // { // StringBuilder result = new StringBuilder(); // boolean first = true; // // for (Map.Entry<String,String> entry : dic.entrySet()) // { // if (first) // first = false; // else // result.append("&"); // // result.append(URLEncoder.encode(entry.getKey(), Settings.Encoding)); // result.append("="); // result.append(URLEncoder.encode(entry.getValue(), Settings.Encoding)); // } // // return result.toString(); // } // // public static String convertStreamToString(java.io.InputStream is) // { // @SuppressWarnings("resource") // java.util.Scanner s = new Scanner(is).useDelimiter("\\A"); // return s.hasNext() ? s.next() : ""; // // } // } // // Path: src/copyleaks/sdk/api/models/responses/BadResponse.java // public class BadResponse { // // public String Message; // // public String getMessage() { // return Message; // } // // @Override // public String toString() // { // return this.getMessage(); // } // } // Path: src/copyleaks/sdk/api/exceptions/CommandFailedException.java import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import copyleaks.sdk.api.helpers.HttpURLConnection.HttpURLConnectionHelper; import copyleaks.sdk.api.models.responses.BadResponse; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import com.google.gson.Gson; public CommandFailedException(HttpURLConnection conn) { super(GetMessage(conn)); try { this.setHttpErrorCode(conn.getResponseCode()); } catch (IOException e) { this.setHttpErrorCode(UNDEFINED_HTTP_ERROR_CODE); } this.setCopyleaksErrorCode(GetCopyleaksErrorCode(conn)); } private static String GetMessage(HttpURLConnection conn) { Gson gson = new GsonBuilder().create(); String errorResponse; try (InputStream inputStream = new BufferedInputStream(conn.getErrorStream())) { errorResponse = HttpURLConnectionHelper.convertStreamToString(inputStream); } catch (IOException e) { return e.getMessage(); }
BadResponse model = null;
starqiu/RDMP1
src/main/java/ustc/sse/service/impl/UserServiceImpl.java
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // }
import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import ustc.sse.dao.UserDao; import ustc.sse.model.User; import ustc.sse.service.UserService;
/* * ============================================================ * The SSE USTC Software License * * UserServiceImpl.java * 2014-4-4 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.service.impl; /** * 实现功能: userService的实现类,为controller提供具体服务 * <p> * date author email notes<br /> * -------- --------------------------- ---------------<br /> *2014-4-4 邱星 starqiu@mail.ustc.edu.cn 新建类<br /></p> * */ /** * service层我用的注解的方式配的,所以没写在Spring配置文件里 * * */ @Service("userService") public class UserServiceImpl implements UserService { @Resource private UserDao userDao; @Override
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // } // Path: src/main/java/ustc/sse/service/impl/UserServiceImpl.java import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import ustc.sse.dao.UserDao; import ustc.sse.model.User; import ustc.sse.service.UserService; /* * ============================================================ * The SSE USTC Software License * * UserServiceImpl.java * 2014-4-4 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.service.impl; /** * 实现功能: userService的实现类,为controller提供具体服务 * <p> * date author email notes<br /> * -------- --------------------------- ---------------<br /> *2014-4-4 邱星 starqiu@mail.ustc.edu.cn 新建类<br /></p> * */ /** * service层我用的注解的方式配的,所以没写在Spring配置文件里 * * */ @Service("userService") public class UserServiceImpl implements UserService { @Resource private UserDao userDao; @Override
public List<User> selectAllUsers() {
starqiu/RDMP1
src/main/java/ustc/sse/service/UserService.java
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // }
import ustc.sse.model.User; import java.util.List; import org.springframework.stereotype.Service;
/* * ============================================================ * The SSE USTC Software License * * UserService.java * 2014-4-4 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.service; /** * 实现功能: 用户服务类,为controller提供服务 * <p> * date author email notes<br /> * -------- --------------------------- ---------------<br /> *2014-4-4 邱星 starqiu@mail.ustc.edu.cn 新建类<br /></p> * */ @Service public interface UserService { /** * 查询所有用户 * @return */
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // Path: src/main/java/ustc/sse/service/UserService.java import ustc.sse.model.User; import java.util.List; import org.springframework.stereotype.Service; /* * ============================================================ * The SSE USTC Software License * * UserService.java * 2014-4-4 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.service; /** * 实现功能: 用户服务类,为controller提供服务 * <p> * date author email notes<br /> * -------- --------------------------- ---------------<br /> *2014-4-4 邱星 starqiu@mail.ustc.edu.cn 新建类<br /></p> * */ @Service public interface UserService { /** * 查询所有用户 * @return */
List<User> selectAllUsers();
starqiu/RDMP1
ETL/source/java source/service/sqlldr.java
// Path: ETL/source/java source/common/Logger.java // public class Logger // { // private org.apache.log4j.Logger log4jLogger = null; // // private gcsFactory iGcsFactory; // // private gcs iGcs; // // public static Logger getLogger(String configPath, String arg) // { // Logger logger = new Logger(); // LoadConfigXml configXml = LoadConfigXml.getConfig(configPath); // // System.out.println(configXml.getBasePath()); // // System.out.println(configXml.getJavaLogFile()); // logger.log4jLogger = org.apache.log4j.Logger.getLogger(arg); // DOMConfigurator.configure(configXml.getJavaLogFile()); // return logger; // } // // public static Logger getLogger(String configPath,Class className) // { // return getLogger(configPath, className.getName()); // } // // public static Logger getLogger(String configPath,Object object) // { // return getLogger(configPath,object.getClass().getName()); // } // // public void log(Level l, Object message) // { // log4jLogger.log(l, message); // } // public void log(Level l, Object message, Throwable e) // { // log4jLogger.log(l, message, e); // } // // public void debug(Object message) // { // // System.out.println(message); // log4jLogger.debug(message); // } // public void debug(Object message, Throwable e) // { // log4jLogger.debug(message, e); // } // // public void info(Object message) // { // // System.out.println(message); // log4jLogger.info(message); // } // public void info(Object message, Throwable e) // { // log4jLogger.info(message, e); // } // // public void warn(Object message) // { // log4jLogger.warn(message); // } // public void warn(Object message, Throwable e) // { // log4jLogger.warn(message, e); // } // // public void error(Object message) // { // // System.err.println(message); // log4jLogger.error(message); // } // public void error(Object message, Throwable e) // { // // System.err.println(e); // //e.printStackTrace(); // log4jLogger.error(message, e); // } // // public void fatal(Object message) // { // log4jLogger.fatal(message); // } // public void fatal(Object message, Throwable e) // { // log4jLogger.fatal(message, e); // } // // public boolean isDebugEnabled() // { // return log4jLogger.isDebugEnabled(); // } // // public boolean isInfoEnabled() // { // return log4jLogger.isInfoEnabled(); // } // // }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.dbs.sg.DTE12.common.AESManager; import com.dbs.sg.DTE12.common.LoadConfigXml; import com.dbs.sg.DTE12.common.Logger;
package com.dbs.sg.DTE12.service; public class sqlldr { /** * @param args */ public static void main(String[] args) { if (args.length < 2) { System.out.println("1"); System.exit(1); } String configPath = args[0]; boolean skipFlag=true; LoadConfigXml configXml = LoadConfigXml.getConfig(configPath); AESManager aes = new AESManager(configPath); String pwd = aes.Descrypt(configXml.getKeyFile(), configXml.getEncryptFile());
// Path: ETL/source/java source/common/Logger.java // public class Logger // { // private org.apache.log4j.Logger log4jLogger = null; // // private gcsFactory iGcsFactory; // // private gcs iGcs; // // public static Logger getLogger(String configPath, String arg) // { // Logger logger = new Logger(); // LoadConfigXml configXml = LoadConfigXml.getConfig(configPath); // // System.out.println(configXml.getBasePath()); // // System.out.println(configXml.getJavaLogFile()); // logger.log4jLogger = org.apache.log4j.Logger.getLogger(arg); // DOMConfigurator.configure(configXml.getJavaLogFile()); // return logger; // } // // public static Logger getLogger(String configPath,Class className) // { // return getLogger(configPath, className.getName()); // } // // public static Logger getLogger(String configPath,Object object) // { // return getLogger(configPath,object.getClass().getName()); // } // // public void log(Level l, Object message) // { // log4jLogger.log(l, message); // } // public void log(Level l, Object message, Throwable e) // { // log4jLogger.log(l, message, e); // } // // public void debug(Object message) // { // // System.out.println(message); // log4jLogger.debug(message); // } // public void debug(Object message, Throwable e) // { // log4jLogger.debug(message, e); // } // // public void info(Object message) // { // // System.out.println(message); // log4jLogger.info(message); // } // public void info(Object message, Throwable e) // { // log4jLogger.info(message, e); // } // // public void warn(Object message) // { // log4jLogger.warn(message); // } // public void warn(Object message, Throwable e) // { // log4jLogger.warn(message, e); // } // // public void error(Object message) // { // // System.err.println(message); // log4jLogger.error(message); // } // public void error(Object message, Throwable e) // { // // System.err.println(e); // //e.printStackTrace(); // log4jLogger.error(message, e); // } // // public void fatal(Object message) // { // log4jLogger.fatal(message); // } // public void fatal(Object message, Throwable e) // { // log4jLogger.fatal(message, e); // } // // public boolean isDebugEnabled() // { // return log4jLogger.isDebugEnabled(); // } // // public boolean isInfoEnabled() // { // return log4jLogger.isInfoEnabled(); // } // // } // Path: ETL/source/java source/service/sqlldr.java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.dbs.sg.DTE12.common.AESManager; import com.dbs.sg.DTE12.common.LoadConfigXml; import com.dbs.sg.DTE12.common.Logger; package com.dbs.sg.DTE12.service; public class sqlldr { /** * @param args */ public static void main(String[] args) { if (args.length < 2) { System.out.println("1"); System.exit(1); } String configPath = args[0]; boolean skipFlag=true; LoadConfigXml configXml = LoadConfigXml.getConfig(configPath); AESManager aes = new AESManager(configPath); String pwd = aes.Descrypt(configXml.getKeyFile(), configXml.getEncryptFile());
Logger logger = Logger.getLogger(configPath, sqlldr.class);
starqiu/RDMP1
ETL/source/java source/service/sqlplus.java
// Path: ETL/source/java source/common/Logger.java // public class Logger // { // private org.apache.log4j.Logger log4jLogger = null; // // private gcsFactory iGcsFactory; // // private gcs iGcs; // // public static Logger getLogger(String configPath, String arg) // { // Logger logger = new Logger(); // LoadConfigXml configXml = LoadConfigXml.getConfig(configPath); // // System.out.println(configXml.getBasePath()); // // System.out.println(configXml.getJavaLogFile()); // logger.log4jLogger = org.apache.log4j.Logger.getLogger(arg); // DOMConfigurator.configure(configXml.getJavaLogFile()); // return logger; // } // // public static Logger getLogger(String configPath,Class className) // { // return getLogger(configPath, className.getName()); // } // // public static Logger getLogger(String configPath,Object object) // { // return getLogger(configPath,object.getClass().getName()); // } // // public void log(Level l, Object message) // { // log4jLogger.log(l, message); // } // public void log(Level l, Object message, Throwable e) // { // log4jLogger.log(l, message, e); // } // // public void debug(Object message) // { // // System.out.println(message); // log4jLogger.debug(message); // } // public void debug(Object message, Throwable e) // { // log4jLogger.debug(message, e); // } // // public void info(Object message) // { // // System.out.println(message); // log4jLogger.info(message); // } // public void info(Object message, Throwable e) // { // log4jLogger.info(message, e); // } // // public void warn(Object message) // { // log4jLogger.warn(message); // } // public void warn(Object message, Throwable e) // { // log4jLogger.warn(message, e); // } // // public void error(Object message) // { // // System.err.println(message); // log4jLogger.error(message); // } // public void error(Object message, Throwable e) // { // // System.err.println(e); // //e.printStackTrace(); // log4jLogger.error(message, e); // } // // public void fatal(Object message) // { // log4jLogger.fatal(message); // } // public void fatal(Object message, Throwable e) // { // log4jLogger.fatal(message, e); // } // // public boolean isDebugEnabled() // { // return log4jLogger.isDebugEnabled(); // } // // public boolean isInfoEnabled() // { // return log4jLogger.isInfoEnabled(); // } // // }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.dbs.sg.DTE12.common.AESManager; import com.dbs.sg.DTE12.common.LoadConfigXml; import com.dbs.sg.DTE12.common.Logger;
package com.dbs.sg.DTE12.service; public class sqlplus { /** * @param args */ public static void main(String[] args) { if (args.length < 1) { System.out.println("1"); System.exit(1); } boolean bPrintOutput = false; String[] newargs; List tmp = Arrays.asList(args); List lstArgs = new ArrayList(); lstArgs.addAll(tmp); if (lstArgs.contains("-OY")){ bPrintOutput = true; newargs = new String[args.length-1]; lstArgs.remove("-OY"); newargs = (String[]) lstArgs.toArray(new String[]{}); } else newargs = args; String configPath = newargs[0];
// Path: ETL/source/java source/common/Logger.java // public class Logger // { // private org.apache.log4j.Logger log4jLogger = null; // // private gcsFactory iGcsFactory; // // private gcs iGcs; // // public static Logger getLogger(String configPath, String arg) // { // Logger logger = new Logger(); // LoadConfigXml configXml = LoadConfigXml.getConfig(configPath); // // System.out.println(configXml.getBasePath()); // // System.out.println(configXml.getJavaLogFile()); // logger.log4jLogger = org.apache.log4j.Logger.getLogger(arg); // DOMConfigurator.configure(configXml.getJavaLogFile()); // return logger; // } // // public static Logger getLogger(String configPath,Class className) // { // return getLogger(configPath, className.getName()); // } // // public static Logger getLogger(String configPath,Object object) // { // return getLogger(configPath,object.getClass().getName()); // } // // public void log(Level l, Object message) // { // log4jLogger.log(l, message); // } // public void log(Level l, Object message, Throwable e) // { // log4jLogger.log(l, message, e); // } // // public void debug(Object message) // { // // System.out.println(message); // log4jLogger.debug(message); // } // public void debug(Object message, Throwable e) // { // log4jLogger.debug(message, e); // } // // public void info(Object message) // { // // System.out.println(message); // log4jLogger.info(message); // } // public void info(Object message, Throwable e) // { // log4jLogger.info(message, e); // } // // public void warn(Object message) // { // log4jLogger.warn(message); // } // public void warn(Object message, Throwable e) // { // log4jLogger.warn(message, e); // } // // public void error(Object message) // { // // System.err.println(message); // log4jLogger.error(message); // } // public void error(Object message, Throwable e) // { // // System.err.println(e); // //e.printStackTrace(); // log4jLogger.error(message, e); // } // // public void fatal(Object message) // { // log4jLogger.fatal(message); // } // public void fatal(Object message, Throwable e) // { // log4jLogger.fatal(message, e); // } // // public boolean isDebugEnabled() // { // return log4jLogger.isDebugEnabled(); // } // // public boolean isInfoEnabled() // { // return log4jLogger.isInfoEnabled(); // } // // } // Path: ETL/source/java source/service/sqlplus.java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.dbs.sg.DTE12.common.AESManager; import com.dbs.sg.DTE12.common.LoadConfigXml; import com.dbs.sg.DTE12.common.Logger; package com.dbs.sg.DTE12.service; public class sqlplus { /** * @param args */ public static void main(String[] args) { if (args.length < 1) { System.out.println("1"); System.exit(1); } boolean bPrintOutput = false; String[] newargs; List tmp = Arrays.asList(args); List lstArgs = new ArrayList(); lstArgs.addAll(tmp); if (lstArgs.contains("-OY")){ bPrintOutput = true; newargs = new String[args.length-1]; lstArgs.remove("-OY"); newargs = (String[]) lstArgs.toArray(new String[]{}); } else newargs = args; String configPath = newargs[0];
Logger logger = Logger.getLogger(configPath, sqlplus.class);
starqiu/RDMP1
src/main/java/ustc/sse/controller/LoginController.java
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // }
import java.util.Date; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService;
/* * ============================================================ * The SSE USTC Software License * * Login.java * 2014-3-3 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.controller; /** * 实现功能: 登录、注册及注销 * <p> * date author email notes<br /> * -------- --------------------------- ---------------<br /> *2014-3-3 邱星 starqiu@mail.ustc.edu.cn 新建类<br /></p> * */ @Controller public class LoginController { private final static Log log = LogFactory.getLog(LoginController.class); private String userName; @Resource
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // } // Path: src/main/java/ustc/sse/controller/LoginController.java import java.util.Date; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService; /* * ============================================================ * The SSE USTC Software License * * Login.java * 2014-3-3 * * Copyright (c) 2006 China Payment and Remittance Service Co.,Ltd * All rights reserved. * ============================================================ */ package ustc.sse.controller; /** * 实现功能: 登录、注册及注销 * <p> * date author email notes<br /> * -------- --------------------------- ---------------<br /> *2014-3-3 邱星 starqiu@mail.ustc.edu.cn 新建类<br /></p> * */ @Controller public class LoginController { private final static Log log = LogFactory.getLog(LoginController.class); private String userName; @Resource
private UserService userService;
starqiu/RDMP1
src/main/java/ustc/sse/controller/LoginController.java
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // }
import java.util.Date; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService;
* 跳转到关于我们界面 * @param request * @param response * @return */ @RequestMapping("about") public String about(HttpServletRequest request,HttpServletResponse response){ return "about"; } /** * 跳转到联系我们界面 * @param request * @param response * @return */ @RequestMapping("contact") public String contact(HttpServletRequest request,HttpServletResponse response){ return "contact"; } /** * 用户登录,跳转到欢迎界面 * @param request * @param response * @return */ @RequestMapping("login") public String login(HttpServletRequest request,HttpServletResponse response){ userName = request.getParameter("userName"); String pwd = request.getParameter("password");
// Path: src/main/java/ustc/sse/model/User.java // public class User { // /** 用户名 // @Size(min=3,max=20,message="user.length.required") // @Pattern(regexp="^{[a-zA-Z0-9]+_?}+[a-zA-Z0-9]+$",message="user.ptn.required")*/ // private String userName ; // /** 密码 // @Size(min=6,max=20,message="pwd.length.required") // @Pattern(regexp="^[a-zA-Z0-9!@#$%*.]+$",message="pwd.ptn.required")*/ // private String password ; // /** 邮箱 // @Pattern(regexp="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}")*/ // private String email ; // /** 注册日期*/ // private Date regDate ; // // public String getUserName() { // return userName; // } // public void setUserName(String userName) { // this.userName = userName; // } // public Date getRegDate() { // return regDate; // } // public void setRegDate(Date regDate) { // this.regDate = regDate; // } // public String getPassword() { // return password; // } // public void setPassword(String password) { // this.password = password; // } // public String getEmail() { // return email; // } // public void setEmail(String email) { // this.email = email; // } // // } // // Path: src/main/java/ustc/sse/service/UserService.java // @Service // public interface UserService { // /** // * 查询所有用户 // * @return // */ // List<User> selectAllUsers(); // /** // * 根据用户名查询用户信息 // * @param userName // * @return // */ // User selectUserByName(User user); // /** // * 根据用户名得到用户列表 // * @param userName // * @return // */ // List<User> selectUsers(User user); // /** // * 新增用户 // * @param user // * @return // */ // int addUser(User user); // /** // * 删除用户 // * @param userName // * @return // */ // int deleteUser(User user); // /** // * 更新用户信息 // * @param user // * @return // */ // int updateUser(User user); // } // Path: src/main/java/ustc/sse/controller/LoginController.java import java.util.Date; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import ustc.sse.model.User; import ustc.sse.service.UserService; * 跳转到关于我们界面 * @param request * @param response * @return */ @RequestMapping("about") public String about(HttpServletRequest request,HttpServletResponse response){ return "about"; } /** * 跳转到联系我们界面 * @param request * @param response * @return */ @RequestMapping("contact") public String contact(HttpServletRequest request,HttpServletResponse response){ return "contact"; } /** * 用户登录,跳转到欢迎界面 * @param request * @param response * @return */ @RequestMapping("login") public String login(HttpServletRequest request,HttpServletResponse response){ userName = request.getParameter("userName"); String pwd = request.getParameter("password");
User param = new User();