Datasets:

Modalities:
Text
ArXiv:
Tags:
code
Libraries:
Datasets
License:
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() {

Dataset Card for RepoBench-C

Dataset Summary

RepoBench-C (Completion) is a subtask of RepoBench(GitHub, arXiv), focuing on the prediction of the next line of code, given in-file context (including several preceding lines and import statements), and cross-file context.

Settings

  • cff: short for cross_file_first, indicating the cross-file module in next line is first used in the current file.

  • cfr: short for cross_file_random, indicating the cross-file module in next line is not first used in the current file.

  • if: short for in_file, indicating the next line does not contain any cross-file module.

Supported Tasks

  • python_cff: python code prediction with cross-file-first setting.
  • python_cfr: python code prediction with cross-file-random setting.
  • python_if: python code prediction with in-file setting.
  • java_cff: java code prediction with cross-file-first setting.
  • java_cfr: java code prediction with cross-file-random setting.
  • java_if: java code prediction with in-file setting.

Loading Data

For example, if you want to load the test set to test your model on Python code prediction with cff setting, you can do the following:

from datasets import load_dataset

dataset = load_dataset("tianyang/repobench-c", "python_cff", split="test")

Note: The split argument is optional. If not provided, the entire dataset will be loaded.

Dataset Structure

{
    "repo_name": "repository name of the data point",
    "file_path": "path/to/file",
    "context": "commented and concatenated cross-file context",
    "import_statement": "all import statements in the file",
    "code": "the code for next-line prediction",
    "prompt": "cross-file context + import statements + in-file code",
    "next_line": "the next line of the code"
}

Licensing Information

CC BY-NC-ND 4.0

Citation Information

@misc{liu2023repobench,
      title={RepoBench: Benchmarking Repository-Level Code Auto-Completion Systems}, 
      author={Tianyang Liu and Canwen Xu and Julian McAuley},
      year={2023},
      eprint={2306.03091},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}

Contributions

Thanks to @Leolty for adding this dataset.

Downloads last month
2,786