target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testPrepareGraphQueryClose() throws Exception { String query = "DESCRIBE <http: GraphQuery queryObj = conn.prepareGraphQuery(query); try (GraphQueryResult result = queryObj.evaluate()) { while (result.hasNext()) { result.next(); } } }
@Override public GraphQueryResult evaluate() throws QueryEvaluationException { try { sync(); return getMarkLogicClient().sendGraphQuery(getQueryString(),getBindings(),getIncludeInferred(),getBaseURI()); } catch (IOException e) { throw new QueryEvaluationException(e); } catch (MarkLogicRdf4jException e) { throw new QueryEvaluationException(e); } }
MarkLogicGraphQuery extends MarkLogicQuery implements GraphQuery,MarkLogicQueryDependent { @Override public GraphQueryResult evaluate() throws QueryEvaluationException { try { sync(); return getMarkLogicClient().sendGraphQuery(getQueryString(),getBindings(),getIncludeInferred(),getBaseURI()); } catch (IOException e) { throw new QueryEvaluationException(e); } catch (MarkLogicRdf4jException e) { throw new QueryEvaluationException(e); } } }
MarkLogicGraphQuery extends MarkLogicQuery implements GraphQuery,MarkLogicQueryDependent { @Override public GraphQueryResult evaluate() throws QueryEvaluationException { try { sync(); return getMarkLogicClient().sendGraphQuery(getQueryString(),getBindings(),getIncludeInferred(),getBaseURI()); } catch (IOException e) { throw new QueryEvaluationException(e); } catch (MarkLogicRdf4jException e) { throw new QueryEvaluationException(e); } } MarkLogicGraphQuery(MarkLogicClient client, SPARQLQueryBindingSet bindingSet, String baseUri, String queryString, GraphPermissions graphPerms, QueryDefinition queryDef, SPARQLRuleset[] rulesets); }
MarkLogicGraphQuery extends MarkLogicQuery implements GraphQuery,MarkLogicQueryDependent { @Override public GraphQueryResult evaluate() throws QueryEvaluationException { try { sync(); return getMarkLogicClient().sendGraphQuery(getQueryString(),getBindings(),getIncludeInferred(),getBaseURI()); } catch (IOException e) { throw new QueryEvaluationException(e); } catch (MarkLogicRdf4jException e) { throw new QueryEvaluationException(e); } } MarkLogicGraphQuery(MarkLogicClient client, SPARQLQueryBindingSet bindingSet, String baseUri, String queryString, GraphPermissions graphPerms, QueryDefinition queryDef, SPARQLRuleset[] rulesets); @Override GraphQueryResult evaluate(); @Override void evaluate(RDFHandler resultHandler); }
MarkLogicGraphQuery extends MarkLogicQuery implements GraphQuery,MarkLogicQueryDependent { @Override public GraphQueryResult evaluate() throws QueryEvaluationException { try { sync(); return getMarkLogicClient().sendGraphQuery(getQueryString(),getBindings(),getIncludeInferred(),getBaseURI()); } catch (IOException e) { throw new QueryEvaluationException(e); } catch (MarkLogicRdf4jException e) { throw new QueryEvaluationException(e); } } MarkLogicGraphQuery(MarkLogicClient client, SPARQLQueryBindingSet bindingSet, String baseUri, String queryString, GraphPermissions graphPerms, QueryDefinition queryDef, SPARQLRuleset[] rulesets); @Override GraphQueryResult evaluate(); @Override void evaluate(RDFHandler resultHandler); }
@Test public void testHelloWorld() { assertEquals("Hello from Java!", HelloWorld.getHelloWorld()); }
public static String getHelloWorld() { return "Hello from Java!"; }
HelloWorld { public static String getHelloWorld() { return "Hello from Java!"; } }
HelloWorld { public static String getHelloWorld() { return "Hello from Java!"; } }
HelloWorld { public static String getHelloWorld() { return "Hello from Java!"; } static String getHelloWorld(); }
HelloWorld { public static String getHelloWorld() { return "Hello from Java!"; } static String getHelloWorld(); }
@Test public void checkNotNullNoNull() { assertThat(checkNotNull(5, "should never be")).isEqualTo(5); assertThat(checkNotNull("5", "should never be")).isEqualTo("5"); assertThat(checkNotNull(3f, "should never be")).isEqualTo(3f); }
@NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } private Utils(); }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } private Utils(); }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } private Utils(); }
@Test public void checkNotNullNull() { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("null == null"); checkNotNull(null, "null == null"); }
@NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } private Utils(); }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } private Utils(); }
Utils { @NonNull static <T> T checkNotNull(@Nullable final T reference, final String message) { if (reference == null) { throw new IllegalArgumentException(message); } return reference; } private Utils(); }
@Test public void testConcatenate(){ String[] mStrings = new String[]{"Test 1","Test 2"}; String[] mStrings2 = new String[]{"Test 3","Test 4"}; String[] concat = concatenate(mStrings,mStrings2); assertArrayEquals(new String[]{"Test 1","Test 2","Test 3","Test 4"},concat); assertNotSame(mStrings,concatenate(mStrings,null)); assertNotSame(mStrings,concatenate(null,mStrings)); }
public static <T> T[] concatenate(T[] firstArray, T[] secondArray) { if (firstArray == null) { return secondArray.clone(); } if (secondArray == null) { return firstArray.clone(); } T[] result = Arrays.copyOf(firstArray, firstArray.length + secondArray.length); System.arraycopy(secondArray, 0, result, firstArray.length, secondArray.length); return result; }
ArrayUtils { public static <T> T[] concatenate(T[] firstArray, T[] secondArray) { if (firstArray == null) { return secondArray.clone(); } if (secondArray == null) { return firstArray.clone(); } T[] result = Arrays.copyOf(firstArray, firstArray.length + secondArray.length); System.arraycopy(secondArray, 0, result, firstArray.length, secondArray.length); return result; } }
ArrayUtils { public static <T> T[] concatenate(T[] firstArray, T[] secondArray) { if (firstArray == null) { return secondArray.clone(); } if (secondArray == null) { return firstArray.clone(); } T[] result = Arrays.copyOf(firstArray, firstArray.length + secondArray.length); System.arraycopy(secondArray, 0, result, firstArray.length, secondArray.length); return result; } private ArrayUtils(); }
ArrayUtils { public static <T> T[] concatenate(T[] firstArray, T[] secondArray) { if (firstArray == null) { return secondArray.clone(); } if (secondArray == null) { return firstArray.clone(); } T[] result = Arrays.copyOf(firstArray, firstArray.length + secondArray.length); System.arraycopy(secondArray, 0, result, firstArray.length, secondArray.length); return result; } private ArrayUtils(); static T[] concatenate(T[] firstArray, T[] secondArray); }
ArrayUtils { public static <T> T[] concatenate(T[] firstArray, T[] secondArray) { if (firstArray == null) { return secondArray.clone(); } if (secondArray == null) { return firstArray.clone(); } T[] result = Arrays.copyOf(firstArray, firstArray.length + secondArray.length); System.arraycopy(secondArray, 0, result, firstArray.length, secondArray.length); return result; } private ArrayUtils(); static T[] concatenate(T[] firstArray, T[] secondArray); }
@Test void getSearchTime_shouldReturnCorrectValue() { DateTime mDateTime = DateTime.now(); StopLocation station = Mockito.mock(StopLocation.class); Mockito.when(station.getHafasId()).thenReturn("008814001"); VehicleStop stop = Mockito.mock(VehicleStop.class); VehicleStop[] stops = new VehicleStop[]{stop}; Liveboard instance = new LiveboardImpl(station, stops, mDateTime, DEPARTURES, EQUAL_OR_LATER); assertEquals(mDateTime, instance.getSearchTime()); }
public DateTime getSearchTime() { return mSearchTime; }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public DateTime getSearchTime() { return mSearchTime; } }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public DateTime getSearchTime() { return mSearchTime; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public DateTime getSearchTime() { return mSearchTime; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); VehicleStop[] getStops(); DateTime getSearchTime(); QueryTimeDefinition getTimeDefinition(); LiveboardType getLiveboardType(); LiveboardImpl withStopsAppended(LiveboardImpl... other); void setPageInfo(NextDataPointer previous, NextDataPointer current, NextDataPointer next); @Override NextDataPointer getPreviousResultsPointer(); @Override NextDataPointer getCurrentResultsPointer(); @Override NextDataPointer getNextResultsPointer(); }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public DateTime getSearchTime() { return mSearchTime; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); VehicleStop[] getStops(); DateTime getSearchTime(); QueryTimeDefinition getTimeDefinition(); LiveboardType getLiveboardType(); LiveboardImpl withStopsAppended(LiveboardImpl... other); void setPageInfo(NextDataPointer previous, NextDataPointer current, NextDataPointer next); @Override NextDataPointer getPreviousResultsPointer(); @Override NextDataPointer getCurrentResultsPointer(); @Override NextDataPointer getNextResultsPointer(); }
@Test void getTimeDefinition_shouldReturnCorrectValue() { DateTime mDateTime = DateTime.now(); StopLocation station = Mockito.mock(StopLocation.class); Mockito.when(station.getHafasId()).thenReturn("008814001"); VehicleStop stop = Mockito.mock(VehicleStop.class); VehicleStop[] stops = new VehicleStop[]{stop}; Liveboard departing = new LiveboardImpl(station, stops, mDateTime, DEPARTURES, EQUAL_OR_LATER); Liveboard arriving = new LiveboardImpl(station, stops, mDateTime, DEPARTURES, QueryTimeDefinition.EQUAL_OR_EARLIER); assertEquals(EQUAL_OR_LATER, departing.getTimeDefinition()); assertEquals(QueryTimeDefinition.EQUAL_OR_EARLIER, arriving.getTimeDefinition()); }
public QueryTimeDefinition getTimeDefinition() { return mTimeDefinition; }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public QueryTimeDefinition getTimeDefinition() { return mTimeDefinition; } }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public QueryTimeDefinition getTimeDefinition() { return mTimeDefinition; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public QueryTimeDefinition getTimeDefinition() { return mTimeDefinition; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); VehicleStop[] getStops(); DateTime getSearchTime(); QueryTimeDefinition getTimeDefinition(); LiveboardType getLiveboardType(); LiveboardImpl withStopsAppended(LiveboardImpl... other); void setPageInfo(NextDataPointer previous, NextDataPointer current, NextDataPointer next); @Override NextDataPointer getPreviousResultsPointer(); @Override NextDataPointer getCurrentResultsPointer(); @Override NextDataPointer getNextResultsPointer(); }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public QueryTimeDefinition getTimeDefinition() { return mTimeDefinition; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); VehicleStop[] getStops(); DateTime getSearchTime(); QueryTimeDefinition getTimeDefinition(); LiveboardType getLiveboardType(); LiveboardImpl withStopsAppended(LiveboardImpl... other); void setPageInfo(NextDataPointer previous, NextDataPointer current, NextDataPointer next); @Override NextDataPointer getPreviousResultsPointer(); @Override NextDataPointer getCurrentResultsPointer(); @Override NextDataPointer getNextResultsPointer(); }
@Test void getLiveboardType_shouldReturnCorrectValue() { DateTime mDateTime = DateTime.now(); StopLocation station = Mockito.mock(StopLocation.class); Mockito.when(station.getHafasId()).thenReturn("008814001"); VehicleStop stop = Mockito.mock(VehicleStop.class); VehicleStop[] stops = new VehicleStop[]{stop}; Liveboard departing = new LiveboardImpl(station, stops, mDateTime, DEPARTURES, EQUAL_OR_LATER); Liveboard arriving = new LiveboardImpl(station, stops, mDateTime, LiveboardType.ARRIVALS, EQUAL_OR_LATER); assertEquals(DEPARTURES, departing.getLiveboardType()); assertEquals(LiveboardType.ARRIVALS, arriving.getLiveboardType()); }
public LiveboardType getLiveboardType() { return mType; }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public LiveboardType getLiveboardType() { return mType; } }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public LiveboardType getLiveboardType() { return mType; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public LiveboardType getLiveboardType() { return mType; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); VehicleStop[] getStops(); DateTime getSearchTime(); QueryTimeDefinition getTimeDefinition(); LiveboardType getLiveboardType(); LiveboardImpl withStopsAppended(LiveboardImpl... other); void setPageInfo(NextDataPointer previous, NextDataPointer current, NextDataPointer next); @Override NextDataPointer getPreviousResultsPointer(); @Override NextDataPointer getCurrentResultsPointer(); @Override NextDataPointer getNextResultsPointer(); }
LiveboardImpl extends StopLocationImpl implements Liveboard, Serializable { public LiveboardType getLiveboardType() { return mType; } LiveboardImpl(StopLocation station, VehicleStop[] stops, DateTime searchTime, LiveboardType type, QueryTimeDefinition timeDefinition); VehicleStop[] getStops(); DateTime getSearchTime(); QueryTimeDefinition getTimeDefinition(); LiveboardType getLiveboardType(); LiveboardImpl withStopsAppended(LiveboardImpl... other); void setPageInfo(NextDataPointer previous, NextDataPointer current, NextDataPointer next); @Override NextDataPointer getPreviousResultsPointer(); @Override NextDataPointer getCurrentResultsPointer(); @Override NextDataPointer getNextResultsPointer(); }
@Test public void test() { assertEquals("MY", Base32Utils.encode("f".getBytes())); assertEquals("MZXQ", Base32Utils.encode("fo".getBytes())); assertEquals("MZXW6", Base32Utils.encode("foo".getBytes())); assertEquals("MZXW6YQ", Base32Utils.encode("foob".getBytes())); assertEquals("MZXW6YTB", Base32Utils.encode("fooba".getBytes())); assertEquals("MZXW6YTBOI", Base32Utils.encode("foobar".getBytes())); }
public static String encode(byte[] input) { byte b; int symbol; int carry = 0; int shift = 3; StringBuilder sb = new StringBuilder(); for (byte value : input) { b = value; symbol = carry | (b >> shift); sb.append(BASE32_CHARS[symbol & 0x1f]); if (shift > 5) { shift -= 5; symbol = b >> shift; sb.append(BASE32_CHARS[symbol & 0x1f]); } shift = 5 - shift; carry = b << shift; shift = 8 - shift; } if (shift != 3) { sb.append(BASE32_CHARS[carry & 0x1f]); } return sb.toString(); }
Base32Utils { public static String encode(byte[] input) { byte b; int symbol; int carry = 0; int shift = 3; StringBuilder sb = new StringBuilder(); for (byte value : input) { b = value; symbol = carry | (b >> shift); sb.append(BASE32_CHARS[symbol & 0x1f]); if (shift > 5) { shift -= 5; symbol = b >> shift; sb.append(BASE32_CHARS[symbol & 0x1f]); } shift = 5 - shift; carry = b << shift; shift = 8 - shift; } if (shift != 3) { sb.append(BASE32_CHARS[carry & 0x1f]); } return sb.toString(); } }
Base32Utils { public static String encode(byte[] input) { byte b; int symbol; int carry = 0; int shift = 3; StringBuilder sb = new StringBuilder(); for (byte value : input) { b = value; symbol = carry | (b >> shift); sb.append(BASE32_CHARS[symbol & 0x1f]); if (shift > 5) { shift -= 5; symbol = b >> shift; sb.append(BASE32_CHARS[symbol & 0x1f]); } shift = 5 - shift; carry = b << shift; shift = 8 - shift; } if (shift != 3) { sb.append(BASE32_CHARS[carry & 0x1f]); } return sb.toString(); } }
Base32Utils { public static String encode(byte[] input) { byte b; int symbol; int carry = 0; int shift = 3; StringBuilder sb = new StringBuilder(); for (byte value : input) { b = value; symbol = carry | (b >> shift); sb.append(BASE32_CHARS[symbol & 0x1f]); if (shift > 5) { shift -= 5; symbol = b >> shift; sb.append(BASE32_CHARS[symbol & 0x1f]); } shift = 5 - shift; carry = b << shift; shift = 8 - shift; } if (shift != 3) { sb.append(BASE32_CHARS[carry & 0x1f]); } return sb.toString(); } static String encode(byte[] input); }
Base32Utils { public static String encode(byte[] input) { byte b; int symbol; int carry = 0; int shift = 3; StringBuilder sb = new StringBuilder(); for (byte value : input) { b = value; symbol = carry | (b >> shift); sb.append(BASE32_CHARS[symbol & 0x1f]); if (shift > 5) { shift -= 5; symbol = b >> shift; sb.append(BASE32_CHARS[symbol & 0x1f]); } shift = 5 - shift; carry = b << shift; shift = 8 - shift; } if (shift != 3) { sb.append(BASE32_CHARS[carry & 0x1f]); } return sb.toString(); } static String encode(byte[] input); }
@Test void findDefaultUsers() { CriteriaQuery query = mock(CriteriaQuery.class); TypedQuery typedQuery = mock(TypedQuery.class); EntityGraph graph = mock(EntityGraph.class); EntityManager em = MockFactory.createEntityManagerMock(typedQuery, graph, query); UsersResource resource = new UsersResource(); UserSearchParams params = builder(new UserSearchParams()) .set(UserSearchParams::setGroupId, 1L) .set(UserSearchParams::setEmbed, "(groups)") .build(); UserPermissionPrincipal principal = new UserPermissionPrincipal(1L, "admin", Map.of(), Set.of("user:read")); resource.handleOk(params, principal, em); verify(query, times(0)).where(); verify(typedQuery).setFirstResult(eq(0)); verify(typedQuery).setMaxResults(eq(10)); verify(graph).addSubgraph(eq("groups")); }
@Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
@Test void findByNoSuchGroupId() { CriteriaQuery query = mock(CriteriaQuery.class); TypedQuery typedQuery = mock(TypedQuery.class); EntityGraph graph = mock(EntityGraph.class); Root<User> userRoot = mock(Root.class); EntityManager em = MockFactory.createEntityManagerMock(typedQuery, graph, query, userRoot); UsersResource resource = new UsersResource(); UserSearchParams params = builder(new UserSearchParams()) .set(UserSearchParams::setGroupId, 10L) .build(); UserPermissionPrincipal principal = new UserPermissionPrincipal(1L, "admin", Map.of(), Set.of("any_user:read")); resource.handleOk(params, principal, em); verify(userRoot).join(eq("groups")); }
@Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
UsersResource { @Decision(HANDLE_OK) public List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); query.distinct(true); Root<User> userRoot = query.from(User.class); userRoot.fetch("userProfileValues"); query.orderBy(cb.asc(userRoot.get("id"))); List<ResourceField> embedEntities = some(params.getEmbed(), embed -> new ResourceFilter().parse(embed)) .orElse(Collections.emptyList()); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues"); Subgraph<UserProfileValue> userProfileValuesGraph = userGraph.addSubgraph("userProfileValues"); userProfileValuesGraph.addAttributeNodes("value", "userProfileField"); userProfileValuesGraph.addSubgraph("userProfileField").addAttributeNodes("id", "name", "jsonName"); List<Predicate> predicates = new ArrayList<>(); if (params.getGroupId() != null) { Join<User, Group> groups = userRoot.join("groups"); predicates.add(cb.equal(groups.get("id"), params.getGroupId())); } if (!principal.hasPermission("any_user:read")) { Join<User, ?> groups = userRoot.getJoins().stream().filter(j -> j.getModel().getBindableJavaType() == Group.class) .findAny() .orElseGet(() -> userRoot.join("groups")); Join users = groups.join("users"); predicates.add(cb.notEqual(groups.get("name"), "BOUNCR_USER")); predicates.add(cb.equal(users.get("id"), principal.getId())); } Optional.ofNullable(params.getQ()) .ifPresent(q -> { String likeExpr = "%" + q.replaceAll("%", "_%") + "%"; predicates.add(cb.like(userRoot.get("account"), likeExpr, '_')); }); if (!predicates.isEmpty()) { query.where(predicates.toArray(Predicate[]::new)); } if (embedEntities.stream().anyMatch(r -> r.getName().equalsIgnoreCase("groups"))) { userGraph.addAttributeNodes("groups"); userGraph.addSubgraph("groups").addAttributeNodes("name"); } return em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .setHint("javax.persistence.fetchgraph", userGraph) .setFirstResult(params.getOffset()) .setMaxResults(params.getLimit()) .getResultList(); } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
@Test void post() { UsersResource resource = new UsersResource(); ComponentInjector injector = new ComponentInjector( Map.of("converter", system.getComponent("converter"), "config", system.getComponent("config"))); injector.inject(resource); HttpRequest request = builder(new DefaultHttpRequest()) .set(HttpRequest::setRequestMethod, "POST") .build(); RestContext context = new RestContext(new DefaultResource(), request); UserCreateRequest user = builder(new UserCreateRequest()) .set(UserCreateRequest::setAccount, "fuga") .build(); EntityManager em = MockFactory.createEntityManagerMock(); ActionRecord actionRecord = new ActionRecord(); UserPermissionPrincipal principal = new UserPermissionPrincipal(1L, "admin", Map.of(), Set.of()); resource.doPost(user, actionRecord, principal, context, em); }
@Decision(POST) public User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { User user = converter.createFrom(createRequest, User.class); UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> userProfileValues = userProfileService .convertToUserProfileValues(createRequest.getUserProfiles()); user.setUserProfileValues(userProfileValues.stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList())); List<UserProfileVerification> profileVerifications = config.getVerificationPolicy().isVerificationEnabledAtCreateUser() ? userProfileService .createProfileVerification(userProfileValues).stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList()) : Collections.emptyList(); user.setWriteProtected(false); context.putValue(user); config.getHookRepo().runHook(HookPoint.BEFORE_CREATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { em.persist(user); profileVerifications.forEach(em::persist); config.getHookRepo().runHook(HookPoint.AFTER_CREATE_USER, context); }); actionRecord.setActionType(ActionType.USER_CREATED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); return user; }
UsersResource { @Decision(POST) public User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { User user = converter.createFrom(createRequest, User.class); UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> userProfileValues = userProfileService .convertToUserProfileValues(createRequest.getUserProfiles()); user.setUserProfileValues(userProfileValues.stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList())); List<UserProfileVerification> profileVerifications = config.getVerificationPolicy().isVerificationEnabledAtCreateUser() ? userProfileService .createProfileVerification(userProfileValues).stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList()) : Collections.emptyList(); user.setWriteProtected(false); context.putValue(user); config.getHookRepo().runHook(HookPoint.BEFORE_CREATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { em.persist(user); profileVerifications.forEach(em::persist); config.getHookRepo().runHook(HookPoint.AFTER_CREATE_USER, context); }); actionRecord.setActionType(ActionType.USER_CREATED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); return user; } }
UsersResource { @Decision(POST) public User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { User user = converter.createFrom(createRequest, User.class); UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> userProfileValues = userProfileService .convertToUserProfileValues(createRequest.getUserProfiles()); user.setUserProfileValues(userProfileValues.stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList())); List<UserProfileVerification> profileVerifications = config.getVerificationPolicy().isVerificationEnabledAtCreateUser() ? userProfileService .createProfileVerification(userProfileValues).stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList()) : Collections.emptyList(); user.setWriteProtected(false); context.putValue(user); config.getHookRepo().runHook(HookPoint.BEFORE_CREATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { em.persist(user); profileVerifications.forEach(em::persist); config.getHookRepo().runHook(HookPoint.AFTER_CREATE_USER, context); }); actionRecord.setActionType(ActionType.USER_CREATED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); return user; } }
UsersResource { @Decision(POST) public User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { User user = converter.createFrom(createRequest, User.class); UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> userProfileValues = userProfileService .convertToUserProfileValues(createRequest.getUserProfiles()); user.setUserProfileValues(userProfileValues.stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList())); List<UserProfileVerification> profileVerifications = config.getVerificationPolicy().isVerificationEnabledAtCreateUser() ? userProfileService .createProfileVerification(userProfileValues).stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList()) : Collections.emptyList(); user.setWriteProtected(false); context.putValue(user); config.getHookRepo().runHook(HookPoint.BEFORE_CREATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { em.persist(user); profileVerifications.forEach(em::persist); config.getHookRepo().runHook(HookPoint.AFTER_CREATE_USER, context); }); actionRecord.setActionType(ActionType.USER_CREATED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); return user; } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
UsersResource { @Decision(POST) public User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { User user = converter.createFrom(createRequest, User.class); UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> userProfileValues = userProfileService .convertToUserProfileValues(createRequest.getUserProfiles()); user.setUserProfileValues(userProfileValues.stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList())); List<UserProfileVerification> profileVerifications = config.getVerificationPolicy().isVerificationEnabledAtCreateUser() ? userProfileService .createProfileVerification(userProfileValues).stream() .peek(v -> v.setUser(user)) .collect(Collectors.toList()) : Collections.emptyList(); user.setWriteProtected(false); context.putValue(user); config.getHookRepo().runHook(HookPoint.BEFORE_CREATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { em.persist(user); profileVerifications.forEach(em::persist); config.getHookRepo().runHook(HookPoint.AFTER_CREATE_USER, context); }); actionRecord.setActionType(ActionType.USER_CREATED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); return user; } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
@Test void validate() { ComponentInjector injector = new ComponentInjector( Map.of("converter", system.getComponent("converter"), "validator", system.getComponent("validator"), "config", system.getComponent("config"))); UsersResource resource = injector.inject(new UsersResource()); UserCreateRequest createRequest = builder(new UserCreateRequest()) .set(UserCreateRequest::setAccount, "fuga") .build(); HttpRequest request = builder(new DefaultHttpRequest()) .set(HttpRequest::setRequestMethod, "POST") .build(); EntityManager em = MockFactory.createEntityManagerMock(); Problem problem = resource.validateUserCreateRequest(createRequest, new RestContext(new DefaultResource(), request), em); assertThat(problem).isNull(); }
@Decision(value = MALFORMED, method = "POST") public Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } Set<ConstraintViolation<UserCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); config.getHookRepo().runHook(HookPoint.BEFORE_VALIDATE_USER_PROFILES, createRequest.getUserProfiles()); UserProfileService userProfileService = new UserProfileService(em); Set<Problem.Violation> profileViolations = userProfileService.validateUserProfile(createRequest.getUserProfiles()); problem.getViolations().addAll(profileViolations); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; }
UsersResource { @Decision(value = MALFORMED, method = "POST") public Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } Set<ConstraintViolation<UserCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); config.getHookRepo().runHook(HookPoint.BEFORE_VALIDATE_USER_PROFILES, createRequest.getUserProfiles()); UserProfileService userProfileService = new UserProfileService(em); Set<Problem.Violation> profileViolations = userProfileService.validateUserProfile(createRequest.getUserProfiles()); problem.getViolations().addAll(profileViolations); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } }
UsersResource { @Decision(value = MALFORMED, method = "POST") public Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } Set<ConstraintViolation<UserCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); config.getHookRepo().runHook(HookPoint.BEFORE_VALIDATE_USER_PROFILES, createRequest.getUserProfiles()); UserProfileService userProfileService = new UserProfileService(em); Set<Problem.Violation> profileViolations = userProfileService.validateUserProfile(createRequest.getUserProfiles()); problem.getViolations().addAll(profileViolations); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } }
UsersResource { @Decision(value = MALFORMED, method = "POST") public Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } Set<ConstraintViolation<UserCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); config.getHookRepo().runHook(HookPoint.BEFORE_VALIDATE_USER_PROFILES, createRequest.getUserProfiles()); UserProfileService userProfileService = new UserProfileService(em); Set<Problem.Violation> profileViolations = userProfileService.validateUserProfile(createRequest.getUserProfiles()); problem.getViolations().addAll(profileViolations); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
UsersResource { @Decision(value = MALFORMED, method = "POST") public Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } Set<ConstraintViolation<UserCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); config.getHookRepo().runHook(HookPoint.BEFORE_VALIDATE_USER_PROFILES, createRequest.getUserProfiles()); UserProfileService userProfileService = new UserProfileService(em); Set<Problem.Violation> profileViolations = userProfileService.validateUserProfile(createRequest.getUserProfiles()); problem.getViolations().addAll(profileViolations); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } @Decision(value = MALFORMED, method = "POST") Problem validateUserCreateRequest(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "GET") Problem validateUserSearchParams(Parameters params, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "POST") boolean isPostAllowed(UserPermissionPrincipal principal); @Decision(value = CONFLICT, method = "POST") boolean conflict(UserCreateRequest createRequest, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> handleOk(UserSearchParams params, UserPermissionPrincipal principal, EntityManager em); @Decision(POST) User doPost(UserCreateRequest createRequest, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
@Test void create() { TypedQuery query = mock(TypedQuery.class); Mockito.when(query.getResultList()).thenReturn( List.of( builder(new Permission()) .set(Permission::setId, 2L) .set(Permission::setName, "test2").build(), builder(new Permission()) .set(Permission::setId, 3L) .set(Permission::setName, "test3").build() ) ); final EntityManager em = MockFactory.createEntityManagerMock(query); final RolePermissionsResource resource = new RolePermissionsResource(); final RolePermissionsRequest RolePermissionsRequest = new RolePermissionsRequest(); RolePermissionsRequest.addAll(Arrays.asList("test2", "test3")); final List<Permission> Permissions = List.of( builder(new Permission()) .set(Permission::setId, 1L) .set(Permission::setName, "test1").build(), builder(new Permission()) .set(Permission::setId, 2L) .set(Permission::setName, "test2").build() ); final Role role = builder(new Role()) .set(Role::setPermissions, Permissions) .build(); resource.create(RolePermissionsRequest, role, em); assertThat(role.getPermissions()).containsExactly( builder(new Permission()).set(Permission::setId, 1L) .set(Permission::setName, "test1").build(), builder(new Permission()).set(Permission::setId, 2L) .set(Permission::setName, "test2").build(), builder(new Permission()).set(Permission::setId, 3L) .set(Permission::setName, "test3").build() ); }
@Decision(POST) public RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(createRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.addAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return createRequest; }
RolePermissionsResource { @Decision(POST) public RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(createRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.addAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return createRequest; } }
RolePermissionsResource { @Decision(POST) public RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(createRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.addAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return createRequest; } }
RolePermissionsResource { @Decision(POST) public RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(createRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.addAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return createRequest; } @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<Permission> list(Role role, EntityManager em); @Decision(POST) RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em); @Decision(DELETE) RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em); }
RolePermissionsResource { @Decision(POST) public RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(createRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.addAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return createRequest; } @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<Permission> list(Role role, EntityManager em); @Decision(POST) RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em); @Decision(DELETE) RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em); }
@Test void delete() { TypedQuery query = mock(TypedQuery.class); Mockito.when(query.getResultList()).thenReturn( List.of( builder(new Permission()).set(Permission::setId, 1L).set(Permission::setName, "test1").build(), builder(new Permission()).set(Permission::setId, 3L).set(Permission::setName, "test3").build() ) ); final EntityManager em = MockFactory.createEntityManagerMock(query); final RolePermissionsResource resource = new RolePermissionsResource(); final RolePermissionsRequest RolePermissionsRequest = new RolePermissionsRequest(); RolePermissionsRequest.addAll(Arrays.asList("test1", "test3")); final List<Permission> permissions = List.of( builder(new Permission()).set(Permission::setId, 1L).set(Permission::setName, "test1").build(), builder(new Permission()).set(Permission::setId, 2L).set(Permission::setName, "test2").build(), builder(new Permission()).set(Permission::setId, 3L).set(Permission::setName, "test3").build() ); final Role role = builder(new Role()) .set(Role::setPermissions, permissions) .build(); resource.delete(RolePermissionsRequest, role, em); assertThat(role.getPermissions()).containsExactly( builder(new Permission()).set(Permission::setId, 2L).set(Permission::setName, "test2").build() ); }
@Decision(DELETE) public RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(deleteRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.removeAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return deleteRequest; }
RolePermissionsResource { @Decision(DELETE) public RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(deleteRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.removeAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return deleteRequest; } }
RolePermissionsResource { @Decision(DELETE) public RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(deleteRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.removeAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return deleteRequest; } }
RolePermissionsResource { @Decision(DELETE) public RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(deleteRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.removeAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return deleteRequest; } @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<Permission> list(Role role, EntityManager em); @Decision(POST) RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em); @Decision(DELETE) RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em); }
RolePermissionsResource { @Decision(DELETE) public RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Permission> query = cb.createQuery(Permission.class); Root<Permission> permissionRoot = query.from(Permission.class); query.where(permissionRoot.get("name").in(deleteRequest)); List<Permission> permissions = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<Permission> rolePermissions = new HashSet<>(role.getPermissions()); rolePermissions.removeAll(permissions); role.setPermissions(new ArrayList<>(rolePermissions)); }); return deleteRequest; } @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<Permission> list(Role role, EntityManager em); @Decision(POST) RolePermissionsRequest create(RolePermissionsRequest createRequest, Role role, EntityManager em); @Decision(DELETE) RolePermissionsRequest delete(RolePermissionsRequest deleteRequest, Role role, EntityManager em); }
@Test void create() { TypedQuery query = mock(TypedQuery.class); Mockito.when(query.getResultList()).thenReturn( List.of( builder(new User()).set(User::setId, 2L).set(User::setAccount, "test2").build(), builder(new User()).set(User::setId, 3L).set(User::setAccount, "test3").build() ) ); final EntityManager em = MockFactory.createEntityManagerMock(query); final GroupUsersResource resource = new GroupUsersResource(); final GroupUsersRequest groupUsersRequest = new GroupUsersRequest(); groupUsersRequest.addAll(Arrays.asList("test2", "test3")); final List<User> users = List.of( builder(new User()).set(User::setId, 1L).set(User::setAccount, "test1").build(), builder(new User()).set(User::setId, 2L).set(User::setAccount, "test2").build() ); final Group group = builder(new Group()) .set(Group::setUsers, users) .build(); resource.create(groupUsersRequest, group, em); assertThat(group.getUsers()).containsExactly( builder(new User()).set(User::setId, 1L).set(User::setAccount, "test1").build(), builder(new User()).set(User::setId, 2L).set(User::setAccount, "test2").build(), builder(new User()).set(User::setId, 3L).set(User::setAccount, "test3").build() ); }
@Decision(POST) public GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.addAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; }
GroupUsersResource { @Decision(POST) public GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.addAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } }
GroupUsersResource { @Decision(POST) public GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.addAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } }
GroupUsersResource { @Decision(POST) public GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.addAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } @Decision(value = MALFORMED, method = {"POST", "DELETE"}) Problem vaidateCreateRequest(GroupUsersRequest createRequest, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(PROCESSABLE) boolean processable(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> list(Group group, EntityManager em); @Decision(POST) GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em); @Decision(DELETE) GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em); }
GroupUsersResource { @Decision(POST) public GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.addAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } @Decision(value = MALFORMED, method = {"POST", "DELETE"}) Problem vaidateCreateRequest(GroupUsersRequest createRequest, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(PROCESSABLE) boolean processable(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> list(Group group, EntityManager em); @Decision(POST) GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em); @Decision(DELETE) GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em); }
@Test void delete() { TypedQuery query = mock(TypedQuery.class); Mockito.when(query.getResultList()).thenReturn( List.of( builder(new User()).set(User::setId, 1L).set(User::setAccount, "test1").build(), builder(new User()).set(User::setId, 3L).set(User::setAccount, "test3").build() ) ); final EntityManager em = MockFactory.createEntityManagerMock(query); final GroupUsersResource resource = new GroupUsersResource(); final GroupUsersRequest groupUsersRequest = new GroupUsersRequest(); groupUsersRequest.addAll(Arrays.asList("test1", "test3")); final List<User> users = List.of( builder(new User()).set(User::setId, 1L).set(User::setAccount, "test1").build(), builder(new User()).set(User::setId, 2L).set(User::setAccount, "test2").build(), builder(new User()).set(User::setId, 3L).set(User::setAccount, "test3").build() ); final Group group = builder(new Group()) .set(Group::setUsers, users) .build(); resource.delete(groupUsersRequest, group, em); assertThat(group.getUsers()).containsExactly( builder(new User()).set(User::setId, 2L).set(User::setAccount, "test2").build() ); }
@Decision(DELETE) public GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.removeAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; }
GroupUsersResource { @Decision(DELETE) public GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.removeAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } }
GroupUsersResource { @Decision(DELETE) public GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.removeAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } }
GroupUsersResource { @Decision(DELETE) public GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.removeAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } @Decision(value = MALFORMED, method = {"POST", "DELETE"}) Problem vaidateCreateRequest(GroupUsersRequest createRequest, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(PROCESSABLE) boolean processable(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> list(Group group, EntityManager em); @Decision(POST) GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em); @Decision(DELETE) GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em); }
GroupUsersResource { @Decision(DELETE) public GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(userRoot.get("account").in(createRequest)); List<User> users = em.createQuery(query) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultList(); EntityTransactionManager tx = new EntityTransactionManager(em); tx.required(() -> { HashSet<User> groupUsers = new HashSet<>(group.getUsers()); groupUsers.removeAll(users); group.setUsers(new ArrayList<>(groupUsers)); }); return createRequest; } @Decision(value = MALFORMED, method = {"POST", "DELETE"}) Problem vaidateCreateRequest(GroupUsersRequest createRequest, RestContext context); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= { "POST", "DELETE" }) boolean isModifyAllowed(UserPermissionPrincipal principal); @Decision(PROCESSABLE) boolean processable(Parameters params, RestContext context, EntityManager em); @Decision(HANDLE_OK) List<User> list(Group group, EntityManager em); @Decision(POST) GroupUsersRequest create(GroupUsersRequest createRequest, Group group, EntityManager em); @Decision(DELETE) GroupUsersRequest delete(GroupUsersRequest createRequest, Group group, EntityManager em); }
@Test void authenticationSuccessful() { ComponentInjector injector = new ComponentInjector( Map.of("converter", system.getComponent("converter"), "validator", system.getComponent("validator"), "config", system.getComponent("config"))); final PasswordSignInResource resource = injector.inject(new PasswordSignInResource()); PasswordSignInRequest request = builder(new PasswordSignInRequest()) .set(PasswordSignInRequest::setAccount, "kawasima") .set(PasswordSignInRequest::setPassword, "pass1234") .build(); ActionRecord record = builder(new ActionRecord()) .build(); final RestContext context = new RestContext(new DefaultResource(), new DefaultHttpRequest()); final EntityManager em = MockFactory.createEntityManagerMock(); resource.authenticate(request, record, context, em); }
@Decision(AUTHORIZED) public boolean authenticate(PasswordSignInRequest passwordSignInRequest, ActionRecord actionRecord, RestContext context, final EntityManager em) { config.getHookRepo().runHook(HookPoint.BEFORE_SIGN_IN, context); if (context.getMessage().filter(Problem.class::isInstance).isPresent()) { return false; } SignInService signInService = new SignInService(em, storeProvider, config); UserLockService userLockService = new UserLockService(em, config); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(cb.equal(userRoot.get("account"), passwordSignInRequest.getAccount())); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues", "otpKey", "userLock"); userGraph.addSubgraph("otpKey").addAttributeNodes("key"); userGraph.addSubgraph("userLock").addAttributeNodes("lockedAt"); userGraph.addSubgraph("passwordCredential") .addAttributeNodes("password", "salt", "initial", "createdAt"); User user = em.createQuery(query) .setHint("javax.persistence.fetchgraph", userGraph) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultStream().findAny().orElse(null); if (user != null && user.getUserLock() != null) { context.setMessage(builder(Problem.valueOf(401,"Account is locked")) .set(Problem::setType, BouncrProblem.ACCOUNT_IS_LOCKED.problemUri()) .build()); return false; } if (user != null) { actionRecord.setActor(user.getAccount()); if (user.getPasswordCredential() != null && Arrays.equals( user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2( passwordSignInRequest.getPassword(), user.getPasswordCredential().getSalt(), 100))) { context.putValue(user); actionRecord.setActionType(USER_SIGNIN); SignInService.PasswordCredentialStatus status = signInService.validatePasswordCredentialAttributes(user); if (status == EXPIRED || status == INITIAL) { context.setMessage(builder(Problem.valueOf(401,"Password must be changed")) .set(Problem::setType, BouncrProblem.PASSWORD_MUST_BE_CHANGED.problemUri()) .build()); return false; } if (!signInService.validateOtpKey(user.getOtpKey(), passwordSignInRequest.getOneTimePassword())) { context.setMessage(builder(Problem.valueOf(401, "One time password is needed")) .set(Problem::setType, BouncrProblem.ONE_TIME_PASSWORD_IS_NEEDED.problemUri()) .build()); return false; } return true; } else { actionRecord.setActionType(USER_FAILED_SIGNIN); userLockService.lockUser(user); } } return false; }
PasswordSignInResource { @Decision(AUTHORIZED) public boolean authenticate(PasswordSignInRequest passwordSignInRequest, ActionRecord actionRecord, RestContext context, final EntityManager em) { config.getHookRepo().runHook(HookPoint.BEFORE_SIGN_IN, context); if (context.getMessage().filter(Problem.class::isInstance).isPresent()) { return false; } SignInService signInService = new SignInService(em, storeProvider, config); UserLockService userLockService = new UserLockService(em, config); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(cb.equal(userRoot.get("account"), passwordSignInRequest.getAccount())); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues", "otpKey", "userLock"); userGraph.addSubgraph("otpKey").addAttributeNodes("key"); userGraph.addSubgraph("userLock").addAttributeNodes("lockedAt"); userGraph.addSubgraph("passwordCredential") .addAttributeNodes("password", "salt", "initial", "createdAt"); User user = em.createQuery(query) .setHint("javax.persistence.fetchgraph", userGraph) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultStream().findAny().orElse(null); if (user != null && user.getUserLock() != null) { context.setMessage(builder(Problem.valueOf(401,"Account is locked")) .set(Problem::setType, BouncrProblem.ACCOUNT_IS_LOCKED.problemUri()) .build()); return false; } if (user != null) { actionRecord.setActor(user.getAccount()); if (user.getPasswordCredential() != null && Arrays.equals( user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2( passwordSignInRequest.getPassword(), user.getPasswordCredential().getSalt(), 100))) { context.putValue(user); actionRecord.setActionType(USER_SIGNIN); SignInService.PasswordCredentialStatus status = signInService.validatePasswordCredentialAttributes(user); if (status == EXPIRED || status == INITIAL) { context.setMessage(builder(Problem.valueOf(401,"Password must be changed")) .set(Problem::setType, BouncrProblem.PASSWORD_MUST_BE_CHANGED.problemUri()) .build()); return false; } if (!signInService.validateOtpKey(user.getOtpKey(), passwordSignInRequest.getOneTimePassword())) { context.setMessage(builder(Problem.valueOf(401, "One time password is needed")) .set(Problem::setType, BouncrProblem.ONE_TIME_PASSWORD_IS_NEEDED.problemUri()) .build()); return false; } return true; } else { actionRecord.setActionType(USER_FAILED_SIGNIN); userLockService.lockUser(user); } } return false; } }
PasswordSignInResource { @Decision(AUTHORIZED) public boolean authenticate(PasswordSignInRequest passwordSignInRequest, ActionRecord actionRecord, RestContext context, final EntityManager em) { config.getHookRepo().runHook(HookPoint.BEFORE_SIGN_IN, context); if (context.getMessage().filter(Problem.class::isInstance).isPresent()) { return false; } SignInService signInService = new SignInService(em, storeProvider, config); UserLockService userLockService = new UserLockService(em, config); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(cb.equal(userRoot.get("account"), passwordSignInRequest.getAccount())); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues", "otpKey", "userLock"); userGraph.addSubgraph("otpKey").addAttributeNodes("key"); userGraph.addSubgraph("userLock").addAttributeNodes("lockedAt"); userGraph.addSubgraph("passwordCredential") .addAttributeNodes("password", "salt", "initial", "createdAt"); User user = em.createQuery(query) .setHint("javax.persistence.fetchgraph", userGraph) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultStream().findAny().orElse(null); if (user != null && user.getUserLock() != null) { context.setMessage(builder(Problem.valueOf(401,"Account is locked")) .set(Problem::setType, BouncrProblem.ACCOUNT_IS_LOCKED.problemUri()) .build()); return false; } if (user != null) { actionRecord.setActor(user.getAccount()); if (user.getPasswordCredential() != null && Arrays.equals( user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2( passwordSignInRequest.getPassword(), user.getPasswordCredential().getSalt(), 100))) { context.putValue(user); actionRecord.setActionType(USER_SIGNIN); SignInService.PasswordCredentialStatus status = signInService.validatePasswordCredentialAttributes(user); if (status == EXPIRED || status == INITIAL) { context.setMessage(builder(Problem.valueOf(401,"Password must be changed")) .set(Problem::setType, BouncrProblem.PASSWORD_MUST_BE_CHANGED.problemUri()) .build()); return false; } if (!signInService.validateOtpKey(user.getOtpKey(), passwordSignInRequest.getOneTimePassword())) { context.setMessage(builder(Problem.valueOf(401, "One time password is needed")) .set(Problem::setType, BouncrProblem.ONE_TIME_PASSWORD_IS_NEEDED.problemUri()) .build()); return false; } return true; } else { actionRecord.setActionType(USER_FAILED_SIGNIN); userLockService.lockUser(user); } } return false; } }
PasswordSignInResource { @Decision(AUTHORIZED) public boolean authenticate(PasswordSignInRequest passwordSignInRequest, ActionRecord actionRecord, RestContext context, final EntityManager em) { config.getHookRepo().runHook(HookPoint.BEFORE_SIGN_IN, context); if (context.getMessage().filter(Problem.class::isInstance).isPresent()) { return false; } SignInService signInService = new SignInService(em, storeProvider, config); UserLockService userLockService = new UserLockService(em, config); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(cb.equal(userRoot.get("account"), passwordSignInRequest.getAccount())); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues", "otpKey", "userLock"); userGraph.addSubgraph("otpKey").addAttributeNodes("key"); userGraph.addSubgraph("userLock").addAttributeNodes("lockedAt"); userGraph.addSubgraph("passwordCredential") .addAttributeNodes("password", "salt", "initial", "createdAt"); User user = em.createQuery(query) .setHint("javax.persistence.fetchgraph", userGraph) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultStream().findAny().orElse(null); if (user != null && user.getUserLock() != null) { context.setMessage(builder(Problem.valueOf(401,"Account is locked")) .set(Problem::setType, BouncrProblem.ACCOUNT_IS_LOCKED.problemUri()) .build()); return false; } if (user != null) { actionRecord.setActor(user.getAccount()); if (user.getPasswordCredential() != null && Arrays.equals( user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2( passwordSignInRequest.getPassword(), user.getPasswordCredential().getSalt(), 100))) { context.putValue(user); actionRecord.setActionType(USER_SIGNIN); SignInService.PasswordCredentialStatus status = signInService.validatePasswordCredentialAttributes(user); if (status == EXPIRED || status == INITIAL) { context.setMessage(builder(Problem.valueOf(401,"Password must be changed")) .set(Problem::setType, BouncrProblem.PASSWORD_MUST_BE_CHANGED.problemUri()) .build()); return false; } if (!signInService.validateOtpKey(user.getOtpKey(), passwordSignInRequest.getOneTimePassword())) { context.setMessage(builder(Problem.valueOf(401, "One time password is needed")) .set(Problem::setType, BouncrProblem.ONE_TIME_PASSWORD_IS_NEEDED.problemUri()) .build()); return false; } return true; } else { actionRecord.setActionType(USER_FAILED_SIGNIN); userLockService.lockUser(user); } } return false; } @Decision(value = MALFORMED, method = "POST") Problem validatePasswordSignInRequest(PasswordSignInRequest passwordSignInRequest, RestContext context); @Decision(AUTHORIZED) boolean authenticate(PasswordSignInRequest passwordSignInRequest, ActionRecord actionRecord, RestContext context, final EntityManager em); @Decision(ALLOWED) boolean allowed(RestContext context); @Decision(POST) UserSession doPost(User user, HttpRequest request, RestContext context, EntityManager em); @Decision(HANDLE_CREATED) UserSession handleCreated(UserSession userSession); }
PasswordSignInResource { @Decision(AUTHORIZED) public boolean authenticate(PasswordSignInRequest passwordSignInRequest, ActionRecord actionRecord, RestContext context, final EntityManager em) { config.getHookRepo().runHook(HookPoint.BEFORE_SIGN_IN, context); if (context.getMessage().filter(Problem.class::isInstance).isPresent()) { return false; } SignInService signInService = new SignInService(em, storeProvider, config); UserLockService userLockService = new UserLockService(em, config); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> query = cb.createQuery(User.class); Root<User> userRoot = query.from(User.class); query.where(cb.equal(userRoot.get("account"), passwordSignInRequest.getAccount())); EntityGraph<User> userGraph = em.createEntityGraph(User.class); userGraph.addAttributeNodes("account", "userProfileValues", "otpKey", "userLock"); userGraph.addSubgraph("otpKey").addAttributeNodes("key"); userGraph.addSubgraph("userLock").addAttributeNodes("lockedAt"); userGraph.addSubgraph("passwordCredential") .addAttributeNodes("password", "salt", "initial", "createdAt"); User user = em.createQuery(query) .setHint("javax.persistence.fetchgraph", userGraph) .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH) .getResultStream().findAny().orElse(null); if (user != null && user.getUserLock() != null) { context.setMessage(builder(Problem.valueOf(401,"Account is locked")) .set(Problem::setType, BouncrProblem.ACCOUNT_IS_LOCKED.problemUri()) .build()); return false; } if (user != null) { actionRecord.setActor(user.getAccount()); if (user.getPasswordCredential() != null && Arrays.equals( user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2( passwordSignInRequest.getPassword(), user.getPasswordCredential().getSalt(), 100))) { context.putValue(user); actionRecord.setActionType(USER_SIGNIN); SignInService.PasswordCredentialStatus status = signInService.validatePasswordCredentialAttributes(user); if (status == EXPIRED || status == INITIAL) { context.setMessage(builder(Problem.valueOf(401,"Password must be changed")) .set(Problem::setType, BouncrProblem.PASSWORD_MUST_BE_CHANGED.problemUri()) .build()); return false; } if (!signInService.validateOtpKey(user.getOtpKey(), passwordSignInRequest.getOneTimePassword())) { context.setMessage(builder(Problem.valueOf(401, "One time password is needed")) .set(Problem::setType, BouncrProblem.ONE_TIME_PASSWORD_IS_NEEDED.problemUri()) .build()); return false; } return true; } else { actionRecord.setActionType(USER_FAILED_SIGNIN); userLockService.lockUser(user); } } return false; } @Decision(value = MALFORMED, method = "POST") Problem validatePasswordSignInRequest(PasswordSignInRequest passwordSignInRequest, RestContext context); @Decision(AUTHORIZED) boolean authenticate(PasswordSignInRequest passwordSignInRequest, ActionRecord actionRecord, RestContext context, final EntityManager em); @Decision(ALLOWED) boolean allowed(RestContext context); @Decision(POST) UserSession doPost(User user, HttpRequest request, RestContext context, EntityManager em); @Decision(HANDLE_CREATED) UserSession handleCreated(UserSession userSession); }
@Test void updateUserWithEmail() { CriteriaQuery query = mock(CriteriaQuery.class); TypedQuery typedQuery = mock(TypedQuery.class); EntityGraph graph = mock(EntityGraph.class); EntityManager em = MockFactory.createEntityManagerMock(typedQuery, graph, query); UserResource sat = new UserResource(); ComponentInjector injector = new ComponentInjector( Map.of("converter", system.getComponent("converter"), "validator", system.getComponent("validator"), "config", system.getComponent("config"))); injector.inject(sat); UserUpdateRequest updateRequest = new UserUpdateRequest(); updateRequest.setUserProfile("email", "[email protected]"); UserProfileField emailField = builder(new UserProfileField()) .set(UserProfileField::setId, 1L) .set(UserProfileField::setJsonName, "email") .set(UserProfileField::setNeedsVerification, true) .build(); User user = builder(new User()) .set(User::setAccount, "kawasima") .set(User::setUserProfileValues, new ArrayList<>(List.of( builder(new UserProfileValue()) .set(UserProfileValue::setUserProfileField, emailField) .set(UserProfileValue::setValue, "[email protected]") .build() ))) .build(); Mockito.when(typedQuery.getResultList()).thenReturn( List.of(emailField), List.of() ); ActionRecord actionRecord = new ActionRecord(); UserPermissionPrincipal principal = new UserPermissionPrincipal(1L, "kawasima", Map.of("email", "[email protected]"), Set.of()); RestContext context = new RestContext(new DefaultResource(), new DefaultHttpRequest()); sat.update(updateRequest, user, actionRecord, principal, context, em); verify(em).persist(eq(builder(new UserProfileVerification()) .set(UserProfileVerification::setUser, user) .set(UserProfileVerification::setUserProfileField, emailField) .build())); }
@Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(UserUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(value = CONFLICT, method = "PUT") boolean conflict(UserUpdateRequest updateRequest, User user, RestContext context, EntityManager em); @Decision(HANDLE_OK) User handleOk(User user, Parameters params, EntityManager em); @Decision(PUT) User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); @Decision(DELETE) Void delete(User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(UserUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(value = CONFLICT, method = "PUT") boolean conflict(UserUpdateRequest updateRequest, User user, RestContext context, EntityManager em); @Decision(HANDLE_OK) User handleOk(User user, Parameters params, EntityManager em); @Decision(PUT) User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); @Decision(DELETE) Void delete(User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
@Test public void test() { byte[] hash = PasswordUtils.pbkdf2("password", "salt", 100); System.out.println(hash.length); }
public static byte[] pbkdf2(String password, String salt, int iterations) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, 2048); try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA384"); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new UnreachableException(e); } catch (InvalidKeySpecException e) { throw new MisconfigurationException("core.INVALID_KEY", e); } }
PasswordUtils { public static byte[] pbkdf2(String password, String salt, int iterations) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, 2048); try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA384"); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new UnreachableException(e); } catch (InvalidKeySpecException e) { throw new MisconfigurationException("core.INVALID_KEY", e); } } }
PasswordUtils { public static byte[] pbkdf2(String password, String salt, int iterations) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, 2048); try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA384"); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new UnreachableException(e); } catch (InvalidKeySpecException e) { throw new MisconfigurationException("core.INVALID_KEY", e); } } }
PasswordUtils { public static byte[] pbkdf2(String password, String salt, int iterations) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, 2048); try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA384"); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new UnreachableException(e); } catch (InvalidKeySpecException e) { throw new MisconfigurationException("core.INVALID_KEY", e); } } static byte[] pbkdf2(String password, String salt, int iterations); }
PasswordUtils { public static byte[] pbkdf2(String password, String salt, int iterations) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), iterations, 2048); try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA384"); SecretKey secretKey = keyFactory.generateSecret(keySpec); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new UnreachableException(e); } catch (InvalidKeySpecException e) { throw new MisconfigurationException("core.INVALID_KEY", e); } } static byte[] pbkdf2(String password, String salt, int iterations); }
@Test void updateUserWithoutEmail() { CriteriaQuery query = mock(CriteriaQuery.class); TypedQuery typedQuery = mock(TypedQuery.class); EntityGraph graph = mock(EntityGraph.class); EntityManager em = MockFactory.createEntityManagerMock(typedQuery, graph, query); UserResource sat = new UserResource(); ComponentInjector injector = new ComponentInjector( Map.of("converter", system.getComponent("converter"), "validator", system.getComponent("validator"), "config", system.getComponent("config"))); injector.inject(sat); UserUpdateRequest updateRequest = new UserUpdateRequest(); updateRequest.setUserProfile("email", "[email protected]"); UserProfileField emailField = builder(new UserProfileField()) .set(UserProfileField::setId, 1L) .set(UserProfileField::setJsonName, "email") .set(UserProfileField::setNeedsVerification, true) .build(); Mockito.when(typedQuery.getResultList()).thenReturn( List.of(emailField) ); User user = builder(new User()) .set(User::setAccount, "kawasima") .set(User::setUserProfileValues, new ArrayList<>(List.of( builder(new UserProfileValue()) .set(UserProfileValue::setUserProfileField, emailField) .set(UserProfileValue::setValue, "[email protected]") .build() ))) .build(); ActionRecord actionRecord = new ActionRecord(); UserPermissionPrincipal principal = new UserPermissionPrincipal(1L, "kawasima", Map.of("email", "[email protected]"), Set.of()); RestContext context = new RestContext(new DefaultResource(), new DefaultHttpRequest()); sat.update(updateRequest, user, actionRecord, principal, context, em); verify(em, never()).persist(eq(builder(new UserProfileVerification()) .set(UserProfileVerification::setUser, user) .set(UserProfileVerification::setUserProfileField, emailField) .build())); }
@Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(UserUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(value = CONFLICT, method = "PUT") boolean conflict(UserUpdateRequest updateRequest, User user, RestContext context, EntityManager em); @Decision(HANDLE_OK) User handleOk(User user, Parameters params, EntityManager em); @Decision(PUT) User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); @Decision(DELETE) Void delete(User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
UserResource { @Decision(PUT) public User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em) { UserProfileService userProfileService = new UserProfileService(em); List<UserProfileValue> newValues = new ArrayList<>(userProfileService .convertToUserProfileValues(updateRequest.getUserProfiles())); config.getHookRepo().runHook(HookPoint.BEFORE_UPDATE_USER, context); EntityTransactionManager tm = new EntityTransactionManager(em); tm.required(() -> { converter.copy(updateRequest, user); List<UserProfileValue> removeValues = new ArrayList<>(); List<UserProfileValue> updatedValues = new ArrayList<>(); user.getUserProfileValues().forEach(v -> { Optional<UserProfileValue> maybeNewValue = newValues.stream() .filter(newValue -> newValue.getUserProfileField().getId().equals(v.getUserProfileField().getId())) .findAny(); maybeNewValue.ifPresentOrElse( newValue -> { if (!Objects.equals(v.getValue(), newValue.getValue())) { v.setValue(newValue.getValue()); updatedValues.add(v); } newValues.remove(newValue); }, () -> removeValues.add(v) ); }); newValues.forEach(v -> v.setUser(user)); user.getUserProfileValues().addAll(newValues); final Set<UserProfileVerification> currentVerifications = new HashSet<>(userProfileService .findUserProfileVerifications(user.getAccount())); VerificationTargetSet verifications = new VerificationTargetSet(userProfileService .createProfileVerification(Stream.concat(newValues.stream(), updatedValues.stream())) .stream() .map(newVerification -> currentVerifications.stream() .filter(v -> v.getUserProfileField().equals(newVerification.getUserProfileField())) .findAny() .orElseGet(() -> { newVerification.setUser(user); em.persist(newVerification); return newVerification; })) .collect(Collectors.toSet())); if (!verifications.isEmpty()) { context.putValue(verifications); } config.getHookRepo().runHook(HookPoint.AFTER_UPDATE_USER, context); }); actionRecord.setActionType(ActionType.USER_MODIFIED); actionRecord.setActor(principal.getName()); actionRecord.setDescription(user.getAccount()); em.detach(user); return user; } @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(UserUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(AUTHORIZED) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method= "GET") boolean isGetAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(value = ALLOWED, method= "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, Parameters params); @Decision(EXISTS) boolean exists(Parameters params, RestContext context, EntityManager em); @Decision(value = CONFLICT, method = "PUT") boolean conflict(UserUpdateRequest updateRequest, User user, RestContext context, EntityManager em); @Decision(HANDLE_OK) User handleOk(User user, Parameters params, EntityManager em); @Decision(PUT) User update(UserUpdateRequest updateRequest, User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); @Decision(DELETE) Void delete(User user, ActionRecord actionRecord, UserPermissionPrincipal principal, RestContext context, EntityManager em); }
@Test void cyclicSerialize() { ObjectMapper mapper = new ObjectMapper(); User user = builder(new User()) .set(User::setId, 1L) .set(User::setAccount, "test") .set(User::setGroups, new IndirectList<>()) .build(); UserLock userLock = builder(new UserLock()) .set(UserLock::setUser, user) .set(UserLock::setLockedAt, LocalDateTime.now()) .set(UserLock::setLockLevel, LockLevel.LOOSE) .build(); user.setUserLock(userLock); assertThatCode(() -> { mapper.writerFor(User.class).writeValueAsString(user); mapper.writerFor(UserLock.class).writeValueAsString(userLock); }).doesNotThrowAnyException(); }
public void setUserLock(UserLock userLock) { this.userLock = userLock; }
User implements Serializable { public void setUserLock(UserLock userLock) { this.userLock = userLock; } }
User implements Serializable { public void setUserLock(UserLock userLock) { this.userLock = userLock; } }
User implements Serializable { public void setUserLock(UserLock userLock) { this.userLock = userLock; } Long getId(); void setId(Long id); String getAccount(); void setAccount(String account); String getAccountLower(); void setAccountLower(String accountLower); Boolean getWriteProtected(); void setWriteProtected(Boolean writeProtected); List<Group> getGroups(); void setGroups(List<Group> groups); List<UserProfileValue> getUserProfileValues(); void setUserProfileValues(List<UserProfileValue> userProfileValues); @JsonAnyGetter Map<String, Object> getUserProfiles(); UserLock getUserLock(); void setUserLock(UserLock userLock); OtpKey getOtpKey(); void setOtpKey(OtpKey otpKey); PasswordCredential getPasswordCredential(); void setPasswordCredential(PasswordCredential passwordCredential); List<OidcUser> getOidcUsers(); void setOidcUsers(List<OidcUser> oidcUsers); @JsonProperty("oidc_providers") @Transient @JsonInclude(JsonInclude.Include.NON_EMPTY) List<String> getOidcProviders(); List<String> getPermissions(); void setPermissions(List<String> permissions); List<String> getUnverifiedProfiles(); void setUnverifiedProfiles(List<String> unverifiedProfiles); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
User implements Serializable { public void setUserLock(UserLock userLock) { this.userLock = userLock; } Long getId(); void setId(Long id); String getAccount(); void setAccount(String account); String getAccountLower(); void setAccountLower(String accountLower); Boolean getWriteProtected(); void setWriteProtected(Boolean writeProtected); List<Group> getGroups(); void setGroups(List<Group> groups); List<UserProfileValue> getUserProfileValues(); void setUserProfileValues(List<UserProfileValue> userProfileValues); @JsonAnyGetter Map<String, Object> getUserProfiles(); UserLock getUserLock(); void setUserLock(UserLock userLock); OtpKey getOtpKey(); void setOtpKey(OtpKey otpKey); PasswordCredential getPasswordCredential(); void setPasswordCredential(PasswordCredential passwordCredential); List<OidcUser> getOidcUsers(); void setOidcUsers(List<OidcUser> oidcUsers); @JsonProperty("oidc_providers") @Transient @JsonInclude(JsonInclude.Include.NON_EMPTY) List<String> getOidcProviders(); List<String> getPermissions(); void setPermissions(List<String> permissions); List<String> getUnverifiedProfiles(); void setUnverifiedProfiles(List<String> unverifiedProfiles); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); }
@Test void test() { StoreProvider provider = system.getComponent("storeProvider", StoreProvider.class); KeyValueStore store = provider.getStore(StoreProvider.StoreType.BOUNCR_TOKEN); store.write("A", "B"); }
public KeyValueStore getStore(StoreType storeType) { switch(storeType) { case BOUNCR_TOKEN: return bouncrTokenStore; case AUTHORIZATION_CODE: return authorizationCodeStore; case ACCESS_TOKEN: return accessTokenStore; case OIDC_SESSION: return oidcSessionStore; default: throw new IllegalArgumentException(storeType + " is unknown"); } }
StoreProvider extends SystemComponent<StoreProvider> { public KeyValueStore getStore(StoreType storeType) { switch(storeType) { case BOUNCR_TOKEN: return bouncrTokenStore; case AUTHORIZATION_CODE: return authorizationCodeStore; case ACCESS_TOKEN: return accessTokenStore; case OIDC_SESSION: return oidcSessionStore; default: throw new IllegalArgumentException(storeType + " is unknown"); } } }
StoreProvider extends SystemComponent<StoreProvider> { public KeyValueStore getStore(StoreType storeType) { switch(storeType) { case BOUNCR_TOKEN: return bouncrTokenStore; case AUTHORIZATION_CODE: return authorizationCodeStore; case ACCESS_TOKEN: return accessTokenStore; case OIDC_SESSION: return oidcSessionStore; default: throw new IllegalArgumentException(storeType + " is unknown"); } } }
StoreProvider extends SystemComponent<StoreProvider> { public KeyValueStore getStore(StoreType storeType) { switch(storeType) { case BOUNCR_TOKEN: return bouncrTokenStore; case AUTHORIZATION_CODE: return authorizationCodeStore; case ACCESS_TOKEN: return accessTokenStore; case OIDC_SESSION: return oidcSessionStore; default: throw new IllegalArgumentException(storeType + " is unknown"); } } KeyValueStore getStore(StoreType storeType); }
StoreProvider extends SystemComponent<StoreProvider> { public KeyValueStore getStore(StoreType storeType) { switch(storeType) { case BOUNCR_TOKEN: return bouncrTokenStore; case AUTHORIZATION_CODE: return authorizationCodeStore; case ACCESS_TOKEN: return accessTokenStore; case OIDC_SESSION: return oidcSessionStore; default: throw new IllegalArgumentException(storeType + " is unknown"); } } KeyValueStore getStore(StoreType storeType); }
@Test void sortedOrder() { Flake flake = system.getComponent("flake"); BigInteger[] ids = new BigInteger[100]; for (int i=0; i<100; i++) { ids[i] = flake.generateId(); } for (int i=0; i<99; i++) { assertThat(ids[i]).isLessThan(ids[i+1]); } }
public synchronized BigInteger generateId() { ByteBuffer buf = ByteBuffer.allocate(16); long current = clock.millis(); if (current != lastTime) { lastTime = current; sequence = 0; } else { sequence++; } return new BigInteger(buf.putLong(lastTime).put(macAddress).putShort((short)sequence) .array()); }
Flake extends SystemComponent { public synchronized BigInteger generateId() { ByteBuffer buf = ByteBuffer.allocate(16); long current = clock.millis(); if (current != lastTime) { lastTime = current; sequence = 0; } else { sequence++; } return new BigInteger(buf.putLong(lastTime).put(macAddress).putShort((short)sequence) .array()); } }
Flake extends SystemComponent { public synchronized BigInteger generateId() { ByteBuffer buf = ByteBuffer.allocate(16); long current = clock.millis(); if (current != lastTime) { lastTime = current; sequence = 0; } else { sequence++; } return new BigInteger(buf.putLong(lastTime).put(macAddress).putShort((short)sequence) .array()); } }
Flake extends SystemComponent { public synchronized BigInteger generateId() { ByteBuffer buf = ByteBuffer.allocate(16); long current = clock.millis(); if (current != lastTime) { lastTime = current; sequence = 0; } else { sequence++; } return new BigInteger(buf.putLong(lastTime).put(macAddress).putShort((short)sequence) .array()); } synchronized BigInteger generateId(); }
Flake extends SystemComponent { public synchronized BigInteger generateId() { ByteBuffer buf = ByteBuffer.allocate(16); long current = clock.millis(); if (current != lastTime) { lastTime = current; sequence = 0; } else { sequence++; } return new BigInteger(buf.putLong(lastTime).put(macAddress).putShort((short)sequence) .array()); } synchronized BigInteger generateId(); }
@Test void healthCheck_Normal() throws Exception { HttpServerExchange exchange = mock(HttpServerExchange.class); Sender sender = mock(Sender.class); given(exchange.getResponseSender()).willReturn(sender); HealthCheckHandler handler = new HealthCheckHandler(); handler.handleRequest(exchange); verify(sender).send(anyString()); }
@Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } HealthCheckResponse response = HealthCheckResponse.builder() .name("bouncr-proxy") .up() .build(); exchange.setStatusCode(200); exchange.getResponseSender().send(mapper.writeValueAsString(response)); }
HealthCheckHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } HealthCheckResponse response = HealthCheckResponse.builder() .name("bouncr-proxy") .up() .build(); exchange.setStatusCode(200); exchange.getResponseSender().send(mapper.writeValueAsString(response)); } }
HealthCheckHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } HealthCheckResponse response = HealthCheckResponse.builder() .name("bouncr-proxy") .up() .build(); exchange.setStatusCode(200); exchange.getResponseSender().send(mapper.writeValueAsString(response)); } HealthCheckHandler(); }
HealthCheckHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } HealthCheckResponse response = HealthCheckResponse.builder() .name("bouncr-proxy") .up() .build(); exchange.setStatusCode(200); exchange.getResponseSender().send(mapper.writeValueAsString(response)); } HealthCheckHandler(); @Override void handleRequest(HttpServerExchange exchange); }
HealthCheckHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return; } HealthCheckResponse response = HealthCheckResponse.builder() .name("bouncr-proxy") .up() .build(); exchange.setStatusCode(200); exchange.getResponseSender().send(mapper.writeValueAsString(response)); } HealthCheckHandler(); @Override void handleRequest(HttpServerExchange exchange); }
@Test void validateCreateRequest_Error() { TypedQuery query = mock(TypedQuery.class); final EntityManager em = MockFactory.createEntityManagerMock(query); HttpRequest request = builder(new DefaultHttpRequest()) .set(HttpRequest::setRequestMethod, "POST") .build(); RestContext context = new RestContext(new DefaultResource(), request); PasswordCredentialResource resource = new PasswordCredentialResource(); PasswordCredentialCreateRequest createRequest = new PasswordCredentialCreateRequest(); ComponentInjector injector = new ComponentInjector( Map.of("config", system.getComponent("config"), "validator", system.getComponent("validator"))); injector.inject(resource); Problem problem = resource.validateCreateRequest(createRequest, context, em); assertThat(problem).isNotNull(); }
@Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
@Test void validateCreateRequest_Success() { TypedQuery query = mock(TypedQuery.class); final EntityManager em = MockFactory.createEntityManagerMock(query); HttpRequest request = builder(new DefaultHttpRequest()) .set(HttpRequest::setRequestMethod, "POST") .build(); RestContext context = new RestContext(new DefaultResource(), request); PasswordCredentialResource resource = new PasswordCredentialResource(); PasswordCredentialCreateRequest createRequest = new PasswordCredentialCreateRequest(); createRequest.setAccount("test_user"); createRequest.setPassword("pass1234"); ComponentInjector injector = new ComponentInjector( Map.of("config", system.getComponent("config"), "validator", system.getComponent("validator"))); injector.inject(resource); Problem problem = resource.validateCreateRequest(createRequest, context, em); assertThat(problem).isNull(); }
@Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
PasswordCredentialResource { @Decision(value = MALFORMED, method = "POST") public Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { if (createRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } PasswordPolicyService passwordPolicyService = new PasswordPolicyService(config.getPasswordPolicy(), em); Set<ConstraintViolation<PasswordCredentialCreateRequest>> violations = validator.validate(createRequest); Problem problem = builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); Optional.ofNullable(passwordPolicyService.validateCreatePassword(createRequest)) .ifPresent(violation -> problem.getViolations().add(violation)); if (problem.getViolations().isEmpty()) { context.putValue(createRequest); } return problem.getViolations().isEmpty() ? null : problem; } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
@Test void userProcessableInPost_Successful() { TypedQuery query = mock(TypedQuery.class); User user = builder(new User()) .set(User::setId, 1L) .set(User::setAccount, "test_user") .build(); when(query.getResultStream()).thenReturn(Stream.of(user)); final EntityManager em = MockFactory.createEntityManagerMock(query); HttpRequest request = builder(new DefaultHttpRequest()) .set(HttpRequest::setRequestMethod, "POST") .build(); RestContext context = new RestContext(new DefaultResource(), request); PasswordCredentialResource resource = new PasswordCredentialResource(); PasswordCredentialCreateRequest createRequest = new PasswordCredentialCreateRequest(); createRequest.setAccount("test_user"); createRequest.setPassword("pass1234"); ComponentInjector injector = new ComponentInjector( Map.of("config", system.getComponent("config"), "validator", system.getComponent("validator"))); injector.inject(resource); boolean ret = resource.userProcessableInPost(createRequest, context, em); assertThat(ret).isTrue(); }
@Decision(value=PROCESSABLE, method="POST") public boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { return findUserByAccount(createRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }).isPresent(); }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="POST") public boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { return findUserByAccount(createRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }).isPresent(); } }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="POST") public boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { return findUserByAccount(createRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }).isPresent(); } }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="POST") public boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { return findUserByAccount(createRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }).isPresent(); } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="POST") public boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em) { return findUserByAccount(createRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }).isPresent(); } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
@Test void userProcessableInPut_Successful() { TypedQuery query = mock(TypedQuery.class); PasswordCredential credential = builder(new PasswordCredential()) .set(PasswordCredential::setPassword, PasswordUtils.pbkdf2("pass1234", "saltsalt", 100)) .set(PasswordCredential::setSalt, "saltsalt") .build(); User user = builder(new User()) .set(User::setId, 1L) .set(User::setAccount, "test_user") .set(User::setPasswordCredential, credential) .build(); when(query.getResultStream()).thenReturn(Stream.of(user)); final EntityManager em = MockFactory.createEntityManagerMock(query); HttpRequest request = builder(new DefaultHttpRequest()) .set(HttpRequest::setRequestMethod, "POST") .build(); RestContext context = new RestContext(new DefaultResource(), request); PasswordCredentialResource resource = new PasswordCredentialResource(); PasswordCredentialUpdateRequest updateRequest = builder(new PasswordCredentialUpdateRequest()) .set(PasswordCredentialUpdateRequest::setAccount, "test_user") .set(PasswordCredentialUpdateRequest::setOldPassword, "pass1234") .set(PasswordCredentialUpdateRequest::setNewPassword, "pass5678") .build(); ComponentInjector injector = new ComponentInjector( Map.of("config", system.getComponent("config"), "validator", system.getComponent("validator"))); injector.inject(resource); boolean ret = resource.userProcessableInPut(updateRequest, context, em); assertThat(ret).isTrue(); }
@Decision(value=PROCESSABLE, method="PUT") public boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em) { return findUserByAccount(updateRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }) .filter(user -> user.getPasswordCredential() != null) .filter(user -> Arrays.equals(user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2(updateRequest.getOldPassword(), user.getPasswordCredential().getSalt(), 100)) ) .isPresent(); }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="PUT") public boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em) { return findUserByAccount(updateRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }) .filter(user -> user.getPasswordCredential() != null) .filter(user -> Arrays.equals(user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2(updateRequest.getOldPassword(), user.getPasswordCredential().getSalt(), 100)) ) .isPresent(); } }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="PUT") public boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em) { return findUserByAccount(updateRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }) .filter(user -> user.getPasswordCredential() != null) .filter(user -> Arrays.equals(user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2(updateRequest.getOldPassword(), user.getPasswordCredential().getSalt(), 100)) ) .isPresent(); } }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="PUT") public boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em) { return findUserByAccount(updateRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }) .filter(user -> user.getPasswordCredential() != null) .filter(user -> Arrays.equals(user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2(updateRequest.getOldPassword(), user.getPasswordCredential().getSalt(), 100)) ) .isPresent(); } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
PasswordCredentialResource { @Decision(value=PROCESSABLE, method="PUT") public boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em) { return findUserByAccount(updateRequest.getAccount(), em) .map(user -> { context.putValue(user); return user; }) .filter(user -> user.getPasswordCredential() != null) .filter(user -> Arrays.equals(user.getPasswordCredential().getPassword(), PasswordUtils.pbkdf2(updateRequest.getOldPassword(), user.getPasswordCredential().getSalt(), 100)) ) .isPresent(); } @Decision(value = MALFORMED, method = "POST") Problem validateCreateRequest(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "PUT") Problem validateUpdateRequest(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(value = MALFORMED, method = "DELETE") Problem validateDeleteRequest(PasswordCredentialUpdateRequest deleteRequest, RestContext context, EntityManager em); @Decision(value = AUTHORIZED, method = {"POST", "DELETE"}) boolean isAuthorized(UserPermissionPrincipal principal); @Decision(value = ALLOWED, method = "POST") boolean isPostAllowed(UserPermissionPrincipal principal, PasswordCredentialCreateRequest createRequest); @Decision(value = ALLOWED, method = "PUT") boolean isPutAllowed(UserPermissionPrincipal principal, PasswordCredentialUpdateRequest updateRequest); @Decision(value = ALLOWED, method = "DELETE") boolean isDeleteAllowed(UserPermissionPrincipal principal, PasswordCredentialDeleteRequest deleteRequest); @Decision(value=PROCESSABLE, method="POST") boolean userProcessableInPost(PasswordCredentialCreateRequest createRequest, RestContext context, EntityManager em); @Decision(value=PROCESSABLE, method="PUT") boolean userProcessableInPut(PasswordCredentialUpdateRequest updateRequest, RestContext context, EntityManager em); @Decision(POST) PasswordCredential create(PasswordCredentialCreateRequest createRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(PUT) PasswordCredential update(PasswordCredentialUpdateRequest updateRequest, User user, UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); @Decision(DELETE) Void delete(UserPermissionPrincipal principal, ActionRecord actionRecord, RestContext context, EntityManager em); }
@Test public void reportCurrentTime() { await().atMost(Duration.TEN_SECONDS).untilAsserted(() -> { verify(tasks, atLeast(2)).reportCurrentTime(); }); }
@Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); }
ScheduledTasks { @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } }
ScheduledTasks { @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } }
ScheduledTasks { @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } @Scheduled(fixedRate = 5000) void reportCurrentTime(); }
ScheduledTasks { @Scheduled(fixedRate = 5000) public void reportCurrentTime() { log.info("The time is now {}", dateFormat.format(new Date())); } @Scheduled(fixedRate = 5000) void reportCurrentTime(); }
@Test public void testOverNexus() throws Exception { @SuppressWarnings("resource") final TopicLogger logger = new TopicLogger().withExcludeTopics(Topic.of("t")); edge = EdgeNode.builder() .withServerConfig(new XServerConfig().withPort(SocketUtils.getAvailablePort(PORT))) .withPlugins(logger) .build(); remote = RemoteNode.builder().build(); final RemoteNexusHandler handler = mock(RemoteNexusHandler.class); final RemoteNexus nexus = remote.open(new URI("ws: nexus.bind(new BindFrame().withSubscribe("test")).get(); nexus.publish(new PublishBinaryFrame("test", "test".getBytes())); nexus.publish(new PublishTextFrame("test", "test")); SocketUtils.await().until(() -> { verify(handler).onText(notNull(), notNull(), notNull()); verify(handler).onBinary(notNull(), notNull(), notNull()); }); }
public TopicLogger withExcludeTopics(Topic... excludeTopics) { this.excludeTopics = excludeTopics; return this; }
TopicLogger implements Plugin, TopicListener { public TopicLogger withExcludeTopics(Topic... excludeTopics) { this.excludeTopics = excludeTopics; return this; } }
TopicLogger implements Plugin, TopicListener { public TopicLogger withExcludeTopics(Topic... excludeTopics) { this.excludeTopics = excludeTopics; return this; } }
TopicLogger implements Plugin, TopicListener { public TopicLogger withExcludeTopics(Topic... excludeTopics) { this.excludeTopics = excludeTopics; return this; } TopicLogger withLogger(Logger logger); TopicLogger withExcludeTopics(Topic... excludeTopics); @Override void onBuild(EdgeNodeBuilder builder); @Override void onRun(EdgeNode edge); @Override void close(); @Override void onOpen(EdgeNexus nexus); @Override void onClose(EdgeNexus nexus); @Override void onBind(EdgeNexus nexus, BindFrame bind, BindResponseFrame bindRes); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override String toString(); }
TopicLogger implements Plugin, TopicListener { public TopicLogger withExcludeTopics(Topic... excludeTopics) { this.excludeTopics = excludeTopics; return this; } TopicLogger withLogger(Logger logger); TopicLogger withExcludeTopics(Topic... excludeTopics); @Override void onBuild(EdgeNodeBuilder builder); @Override void onRun(EdgeNode edge); @Override void close(); @Override void onOpen(EdgeNexus nexus); @Override void onClose(EdgeNexus nexus); @Override void onBind(EdgeNexus nexus, BindFrame bind, BindResponseFrame bindRes); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override String toString(); }
@Test public void testToString() { assertNotNull(backplane.toString()); }
@Override public String toString() { return "KafkaBackplane [config: " + config + ", clusterId: " + clusterId + ", brokerId: " + brokerId + "]"; }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public String toString() { return "KafkaBackplane [config: " + config + ", clusterId: " + clusterId + ", brokerId: " + brokerId + "]"; } }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public String toString() { return "KafkaBackplane [config: " + config + ", clusterId: " + clusterId + ", brokerId: " + brokerId + "]"; } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public String toString() { return "KafkaBackplane [config: " + config + ", clusterId: " + clusterId + ", brokerId: " + brokerId + "]"; } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public String toString() { return "KafkaBackplane [config: " + config + ", clusterId: " + clusterId + ", brokerId: " + brokerId + "]"; } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
@Test public void testObjectPayload() { test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", newTestObject(), "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testMapPayload() { test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", newTestObject().getAttributes(), "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testStringPayload() { test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", "payload", "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testDoublePayload() { test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", 12.34, "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testBooleanPayload() { test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", true, "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testArrayPayload() { test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", Arrays.asList("eenie", "meenie", "minie"), "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testNullPayload() { test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", null, "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testPushUpdateString() { final ScramjetPushUpdate push = new ScramjetPushUpdate("test/topic", 30, "testPayload"); test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", push, "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testPushUpdateMap() { final ScramjetPushUpdate push = new ScramjetPushUpdate("test/topic", 30, newTestObject().getAttributes()); test(new ScramjetMessage(UUID.randomUUID().toString(), "TestMessage", push, "junit", new Date())); }
@Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); }
ScramjetMessage { @Override public String toString() { return "ScramjetMessage [id=" + id + ", messageType=" + messageType + ", payload=" + payload + ", publisher=" + publisher + ", sentAt=" + sentAt + "]"; } ScramjetMessage(String id, String messageType, Object payload, String publisher, Date sentAt); String getId(); String getMessageType(); Object getPayload(); String getPublisher(); Date getSentAt(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static ScramjetMessage fromJson(Gson gson, String json); String toJson(Gson gson); static GsonBuilder defaultGsonBuilder(); static final String TYPE_ATT; }
@Test public void testLoadConfig() throws IOException { final KafkaBackplaneConfig config = new MappingContext() .withParser(new SnakeyamlParser()) .fromStream(KafkaBackplaneConfigTest.class.getClassLoader().getResourceAsStream("kafka-backplane-config.yaml")) .map(KafkaBackplaneConfig.class); assertNotNull(config.toString()); final KafkaCluster<String, KafkaData> kafka = (KafkaCluster<String, KafkaData>) config.kafka; assertNotNull(kafka.getConfig().getCommonProps()); assertNotNull(kafka.getConfig().getProducerProps()); assertNotNull(kafka.getConfig().getConsumerProps()); final Properties consumerProps = new Properties(); consumerProps.setProperty("key.deserializer", StringDeserializer.class.getName()); consumerProps.setProperty("value.deserializer", config.deserializer.getName()); kafka.getConsumer(consumerProps); final Properties producerProps = new Properties(); producerProps.setProperty("key.serializer", StringSerializer.class.getName()); producerProps.setProperty("value.serializer", config.serializer.getName()); kafka.getProducer(producerProps); }
@Override public String toString() { return "KafkaBackplaneConfig [kafka: " + kafka + ", topic: " + topic + ", serializer: " + serializer + ", deserializer: " + deserializer + ", pollTimeoutMillis: " + pollTimeoutMillis + ", ttlMillis: " + ttlMillis + "]"; }
KafkaBackplaneConfig { @Override public String toString() { return "KafkaBackplaneConfig [kafka: " + kafka + ", topic: " + topic + ", serializer: " + serializer + ", deserializer: " + deserializer + ", pollTimeoutMillis: " + pollTimeoutMillis + ", ttlMillis: " + ttlMillis + "]"; } }
KafkaBackplaneConfig { @Override public String toString() { return "KafkaBackplaneConfig [kafka: " + kafka + ", topic: " + topic + ", serializer: " + serializer + ", deserializer: " + deserializer + ", pollTimeoutMillis: " + pollTimeoutMillis + ", ttlMillis: " + ttlMillis + "]"; } }
KafkaBackplaneConfig { @Override public String toString() { return "KafkaBackplaneConfig [kafka: " + kafka + ", topic: " + topic + ", serializer: " + serializer + ", deserializer: " + deserializer + ", pollTimeoutMillis: " + pollTimeoutMillis + ", ttlMillis: " + ttlMillis + "]"; } @Override String toString(); }
KafkaBackplaneConfig { @Override public String toString() { return "KafkaBackplaneConfig [kafka: " + kafka + ", topic: " + topic + ", serializer: " + serializer + ", deserializer: " + deserializer + ", pollTimeoutMillis: " + pollTimeoutMillis + ", ttlMillis: " + ttlMillis + "]"; } @Override String toString(); @YInject public Kafka<String, KafkaData> kafka; @YInject public String topic; @YInject public Class<? extends Serializer<KafkaData>> serializer; @YInject public Class<? extends Deserializer<KafkaData>> deserializer; @YInject public long pollTimeoutMillis; @YInject public long ttlMillis; }
@Test public void testReadNoDefault() { assertEquals("bar", reader.read("foo")); assertNull(reader.read("baz")); }
<T> T read(String key) { return read(key, () -> null); }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } AttributeReader(Map<String, Object> atts); }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } AttributeReader(Map<String, Object> atts); }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } AttributeReader(Map<String, Object> atts); }
@Test public void testReadDefault() { assertEquals("default", reader.read("baz", () -> "default")); }
<T> T read(String key) { return read(key, () -> null); }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } AttributeReader(Map<String, Object> atts); }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } AttributeReader(Map<String, Object> atts); }
AttributeReader { <T> T read(String key) { return read(key, () -> null); } AttributeReader(Map<String, Object> atts); }
@Test public void testGetTypeName() { assertEquals("type", reader.getTypeName()); }
String getTypeName() { return (String) atts.get(ScramjetMessage.TYPE_ATT); }
AttributeReader { String getTypeName() { return (String) atts.get(ScramjetMessage.TYPE_ATT); } }
AttributeReader { String getTypeName() { return (String) atts.get(ScramjetMessage.TYPE_ATT); } AttributeReader(Map<String, Object> atts); }
AttributeReader { String getTypeName() { return (String) atts.get(ScramjetMessage.TYPE_ATT); } AttributeReader(Map<String, Object> atts); }
AttributeReader { String getTypeName() { return (String) atts.get(ScramjetMessage.TYPE_ATT); } AttributeReader(Map<String, Object> atts); }
@Test public void testGetAttributes() { assertEquals("bar", reader.getAttributes().get("foo")); }
Map<String, Object> getAttributes() { return atts; }
AttributeReader { Map<String, Object> getAttributes() { return atts; } }
AttributeReader { Map<String, Object> getAttributes() { return atts; } AttributeReader(Map<String, Object> atts); }
AttributeReader { Map<String, Object> getAttributes() { return atts; } AttributeReader(Map<String, Object> atts); }
AttributeReader { Map<String, Object> getAttributes() { return atts; } AttributeReader(Map<String, Object> atts); }
@Test public void testGetProfilePathProperty() { System.setProperty("flywheel.launchpad.profile", "conf/test-good"); final File path = Launchpad.getProfilePath(new HashMap<>()); assertNotNull(path); assertEquals("conf/test-good", path.getPath()); }
static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
@Test public void testGetProfilePathEnvDefault() { final File path = Launchpad.getProfilePath(new HashMap<>()); assertNotNull(path); assertEquals("conf/default", path.getPath()); }
static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
@Test public void testGetProfilePathEnvSupplied() { final Map<String, String> env = new HashMap<>(); env.put("FLYWHEEL_PROFILE", "conf/test-good"); final File path = Launchpad.getProfilePath(env); assertNotNull(path); assertEquals("conf/test-good", path.getPath()); }
static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
Launchpad { static File getProfilePath(Map<String, String> env) { final String propertyName = "flywheel.launchpad.profile"; final String envName = "FLYWHEEL_PROFILE"; final String profileProp = System.getProperty(propertyName); final File profilePath; if (profileProp != null) { profilePath = new File(profileProp); } else { final String profileEnv = env.get(envName); if (profileEnv != null) { profilePath = new File(profileEnv); } else { profilePath = new File(DEF_PROFILE); } } return profilePath; } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
@Test public void testMain() { System.setProperty("flywheel.launchpad.profile", "conf/test-good"); Launchpad.main(); }
public static void main(String... args) { bootstrap(args, System::exit); }
Launchpad { public static void main(String... args) { bootstrap(args, System::exit); } }
Launchpad { public static void main(String... args) { bootstrap(args, System::exit); } Launchpad(File profilePath); }
Launchpad { public static void main(String... args) { bootstrap(args, System::exit); } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
Launchpad { public static void main(String... args) { bootstrap(args, System::exit); } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
@Test public void testBootstrap() { final IntConsumer exitHandler = mock(IntConsumer.class); System.setProperty("flywheel.launchpad.profile", "conf/test-bad"); Launchpad.bootstrap(new String[0], exitHandler); verify(exitHandler).accept(eq(1)); }
static void bootstrap(String[] args, IntConsumer exitHandler) { try { new Launchpad(getProfilePath(System.getenv())).launch(args); } catch (LaunchpadException e) { err.format("Error:\n"); e.printStackTrace(err); exitHandler.accept(1); } }
Launchpad { static void bootstrap(String[] args, IntConsumer exitHandler) { try { new Launchpad(getProfilePath(System.getenv())).launch(args); } catch (LaunchpadException e) { err.format("Error:\n"); e.printStackTrace(err); exitHandler.accept(1); } } }
Launchpad { static void bootstrap(String[] args, IntConsumer exitHandler) { try { new Launchpad(getProfilePath(System.getenv())).launch(args); } catch (LaunchpadException e) { err.format("Error:\n"); e.printStackTrace(err); exitHandler.accept(1); } } Launchpad(File profilePath); }
Launchpad { static void bootstrap(String[] args, IntConsumer exitHandler) { try { new Launchpad(getProfilePath(System.getenv())).launch(args); } catch (LaunchpadException e) { err.format("Error:\n"); e.printStackTrace(err); exitHandler.accept(1); } } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
Launchpad { static void bootstrap(String[] args, IntConsumer exitHandler) { try { new Launchpad(getProfilePath(System.getenv())).launch(args); } catch (LaunchpadException e) { err.format("Error:\n"); e.printStackTrace(err); exitHandler.accept(1); } } Launchpad(File profilePath); void launch(String[] args); Profile getProfile(); static void main(String... args); }
@Test public void test() throws IOException, URISyntaxException { try (HttpStubAuthenticator auth = new MappingContext() .withParser(new SnakeyamlParser()) .fromStream(HttpStubAuthenticatorConfigTest.class.getClassLoader().getResourceAsStream("http-stub-auth-config.yaml")) .map(HttpStubAuthenticator.class)) { assertEquals(new URI("http: assertEquals(4, auth.getConfig().poolSize); assertEquals(30000, auth.getConfig().timeoutMillis); assertNotNull(auth.toString()); assertNotNull(auth.getConfig().toString()); } }
@Override public String toString() { return "HttpStubAuthenticatorConfig [uri: " + uri + ", poolSize: " + poolSize + ", timeoutMillis: " + timeoutMillis + "]"; }
HttpStubAuthenticatorConfig { @Override public String toString() { return "HttpStubAuthenticatorConfig [uri: " + uri + ", poolSize: " + poolSize + ", timeoutMillis: " + timeoutMillis + "]"; } }
HttpStubAuthenticatorConfig { @Override public String toString() { return "HttpStubAuthenticatorConfig [uri: " + uri + ", poolSize: " + poolSize + ", timeoutMillis: " + timeoutMillis + "]"; } }
HttpStubAuthenticatorConfig { @Override public String toString() { return "HttpStubAuthenticatorConfig [uri: " + uri + ", poolSize: " + poolSize + ", timeoutMillis: " + timeoutMillis + "]"; } HttpStubAuthenticatorConfig withURI(URI uri); HttpStubAuthenticatorConfig withPoolSize(int poolSize); HttpStubAuthenticatorConfig withTimeoutMillis(int timeoutMillis); @Override String toString(); }
HttpStubAuthenticatorConfig { @Override public String toString() { return "HttpStubAuthenticatorConfig [uri: " + uri + ", poolSize: " + poolSize + ", timeoutMillis: " + timeoutMillis + "]"; } HttpStubAuthenticatorConfig withURI(URI uri); HttpStubAuthenticatorConfig withPoolSize(int poolSize); HttpStubAuthenticatorConfig withTimeoutMillis(int timeoutMillis); @Override String toString(); }
@Test public void testReceive() { final Map<TopicPartition, List<ConsumerRecord<String, String>>> recordsMap = Collections.singletonMap(new TopicPartition("test", 0), Arrays.asList(new ConsumerRecord<>("test", 0, 0, "key", "value"))); final ConsumerRecords<String, String> records = new ConsumerRecords<>(recordsMap); when(consumer.poll(notNull())).then(split(() -> records, () -> new ConsumerRecords<>(Collections.emptyMap()))); receiver = new KafkaReceiver<String, String>(consumer, 1, "TestThread", recordHandler, errorHandler); SocketUtils.await().until(() -> { verify(recordHandler, times(1)).onReceive(eq(records)); verify(errorHandler, never()).onError(any()); }); }
public void await() throws InterruptedException { join(); }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); static ErrorHandler genericErrorLogger(Logger logger); @Override void run(); @Override void close(); void await(); }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); static ErrorHandler genericErrorLogger(Logger logger); @Override void run(); @Override void close(); void await(); }
@Test public void testInterrupt() throws InterruptedException { when(consumer.poll(notNull())).then(split(() -> { throw createInterruptException(); })); receiver = new KafkaReceiver<String, String>(consumer, 1, "TestThread", recordHandler, errorHandler); verify(recordHandler, never()).onReceive(any()); verify(errorHandler, never()).onError(any()); receiver.await(); }
public void await() throws InterruptedException { join(); }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); static ErrorHandler genericErrorLogger(Logger logger); @Override void run(); @Override void close(); void await(); }
KafkaReceiver extends Thread implements AutoCloseable { public void await() throws InterruptedException { join(); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); static ErrorHandler genericErrorLogger(Logger logger); @Override void run(); @Override void close(); void await(); }
@Test public void testGenericErrorLogger() { when(consumer.poll(notNull())).then(split(() -> { throw new RuntimeException("boom"); })); final Logger logger = mock(Logger.class); receiver = new KafkaReceiver<String, String>(consumer, 1, "TestThread", recordHandler, KafkaReceiver.genericErrorLogger(logger)); SocketUtils.await().until(() -> { verify(recordHandler, never()).onReceive(any()); verify(logger, atLeastOnce()).warn(anyString(), any(RuntimeException.class)); }); }
public static ErrorHandler genericErrorLogger(Logger logger) { return cause -> logger.warn("Error processing Kafka record", cause); }
KafkaReceiver extends Thread implements AutoCloseable { public static ErrorHandler genericErrorLogger(Logger logger) { return cause -> logger.warn("Error processing Kafka record", cause); } }
KafkaReceiver extends Thread implements AutoCloseable { public static ErrorHandler genericErrorLogger(Logger logger) { return cause -> logger.warn("Error processing Kafka record", cause); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); }
KafkaReceiver extends Thread implements AutoCloseable { public static ErrorHandler genericErrorLogger(Logger logger) { return cause -> logger.warn("Error processing Kafka record", cause); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); static ErrorHandler genericErrorLogger(Logger logger); @Override void run(); @Override void close(); void await(); }
KafkaReceiver extends Thread implements AutoCloseable { public static ErrorHandler genericErrorLogger(Logger logger) { return cause -> logger.warn("Error processing Kafka record", cause); } KafkaReceiver(Consumer<K, V> consumer, long pollTimeoutMillis, String threadName, RecordHandler<K, V> handler, ErrorHandler errorHandler); static ErrorHandler genericErrorLogger(Logger logger); @Override void run(); @Override void close(); void await(); }
@Test(expected=IllegalArgumentException.class) public void testSerializeError() { final KafkaData d = new KafkaData(new RuntimeException()); serializer.serialize("test", d); }
@Override public byte[] serialize(String topic, KafkaData data) { if (data.isError()) throw new IllegalArgumentException("Cannot serialize an error"); final ScramjetMessage msg = toScramjet(data); final String json = msg.toJson(gson); return s.serialize(topic, json); }
ScramjetSerializer implements Serializer<KafkaData> { @Override public byte[] serialize(String topic, KafkaData data) { if (data.isError()) throw new IllegalArgumentException("Cannot serialize an error"); final ScramjetMessage msg = toScramjet(data); final String json = msg.toJson(gson); return s.serialize(topic, json); } }
ScramjetSerializer implements Serializer<KafkaData> { @Override public byte[] serialize(String topic, KafkaData data) { if (data.isError()) throw new IllegalArgumentException("Cannot serialize an error"); final ScramjetMessage msg = toScramjet(data); final String json = msg.toJson(gson); return s.serialize(topic, json); } }
ScramjetSerializer implements Serializer<KafkaData> { @Override public byte[] serialize(String topic, KafkaData data) { if (data.isError()) throw new IllegalArgumentException("Cannot serialize an error"); final ScramjetMessage msg = toScramjet(data); final String json = msg.toJson(gson); return s.serialize(topic, json); } @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] serialize(String topic, KafkaData data); @Override void close(); }
ScramjetSerializer implements Serializer<KafkaData> { @Override public byte[] serialize(String topic, KafkaData data) { if (data.isError()) throw new IllegalArgumentException("Cannot serialize an error"); final ScramjetMessage msg = toScramjet(data); final String json = msg.toJson(gson); return s.serialize(topic, json); } @Override void configure(Map<String, ?> configs, boolean isKey); @Override byte[] serialize(String topic, KafkaData data); @Override void close(); }
@Test public void testAttach() { attach(); }
@Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
@Test public void testOnReceiveText() { final BackplaneConnector connector = attach(); final KafkaData d = new KafkaData("id", "source", "topic", null, "hello", System.currentTimeMillis(), System.currentTimeMillis() + 10_000); getProducer().send(new ProducerRecord<>(config.topic, d)); SocketUtils.await().until(() -> { Mockito.verify(connector).publish(Mockito.eq("topic"), Mockito.eq("hello")); }); }
@Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
@Test public void testOnReceiveBinary() { final BackplaneConnector connector = attach(); final byte[] bytes = "hello".getBytes(); final KafkaData d = new KafkaData("id", "source", "topic", bytes, null, System.currentTimeMillis(), System.currentTimeMillis() + 10_000); getProducer().send(new ProducerRecord<>(config.topic, d)); SocketUtils.await().until(() -> { Mockito.verify(connector).publish(Mockito.eq("topic"), Mockito.eq(bytes)); }); }
@Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
@Test public void testOnReceiveError() { final BackplaneConnector connector = attach(); final KafkaData d = new KafkaData(new RuntimeException("boom")); getProducer().send(new ProducerRecord<>(config.topic, d)); SocketUtils.await().until(() -> { Mockito.verify(connector, Mockito.never()).publish(Mockito.anyString(), Mockito.anyString()); Mockito.verify(connector, Mockito.never()).publish(Mockito.anyString(), Mockito.any(byte[].class)); Mockito.verify(logger, Mockito.atLeastOnce()).warn(Mockito.any(), Mockito.any(RuntimeException.class)); }); }
@Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
KafkaBackplane implements Backplane, RecordHandler<String, KafkaData> { @Override public void attach(BackplaneConnector connector) { LOG.debug("Attaching Kafka backplane..."); this.connector = connector; final Consumer<String, KafkaData> consumer = config.kafka.getConsumer(getConsumerProps()); seekToEnd(consumer, config.topic); final String threadName = "KafkaReceiver-" + clusterId + "-" + brokerId + "-" + config.topic; receiver = new KafkaReceiver<>( consumer, config.pollTimeoutMillis, threadName, this, KafkaReceiver.genericErrorLogger(LOG)); producer = config.kafka.getProducer(getProducerProps()); LOG.debug("Backplane attached"); } KafkaBackplane(@YInject(name="backplaneConfig") KafkaBackplaneConfig config, @YInject(name="clusterId") String clusterId, @YInject(name="brokerId") String brokerId); KafkaBackplane(KafkaBackplaneConfig config, String clusterId, String brokerId, ErrorHandler errorHandler); @Override void attach(BackplaneConnector connector); @Override void onReceive(ConsumerRecords<String, KafkaData> records); @Override void onPublish(EdgeNexus nexus, PublishTextFrame pub); @Override void onPublish(EdgeNexus nexus, PublishBinaryFrame pub); @Override void close(); @Override String toString(); }
@Test public void testGetHandledExceptionList() throws Exception { String result; String expected; expect( pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_XML_PATH)).andReturn(EXC_WEB_XML); expect(fileManager.exists(EXC_WEB_XML)).andReturn(true); expect(fileManager.updateFile(EXC_WEB_XML)) .andReturn(webXmlMutableFile); expect(webXmlMutableFile.getInputStream()).andReturn( getClass().getResourceAsStream(EXC_WEB_XML)); replay(pathResolver, fileManager, webXmlMutableFile); result = webExceptionHandlerOperationsImpl.getHandledExceptionList(); assertTrue("Test 1 \nThere aren't exceptions defined in " + EXC_WEB_XML + " file", result != null); logger.log(Level.INFO, "Test 1 \nExceptions defined in " + EXC_WEB_XML + " :\n" + result); reset(pathResolver, fileManager, webXmlMutableFile); expect( pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_XML_PATH)).andReturn(NO_EXC_WEB_XML); expect(fileManager.exists(NO_EXC_WEB_XML)).andReturn(true); expect(fileManager.updateFile(NO_EXC_WEB_XML)).andReturn( webXmlMutableFile); expect(webXmlMutableFile.getInputStream()).andReturn( getClass().getResourceAsStream(NO_EXC_WEB_XML)); replay(pathResolver, fileManager, webXmlMutableFile); result = webExceptionHandlerOperationsImpl.getHandledExceptionList(); expected = "Handled Exceptions:\n"; assertEquals("Test 2 \nThere are exceptions defined in " + NO_EXC_WEB_XML + " file", expected, result); logger.log(Level.INFO, "Test 2 \nThere aren't exceptions defined in " + NO_EXC_WEB_XML); reset(pathResolver, fileManager, webXmlMutableFile); }
public String getHandledExceptionList() { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); List<Element> simpleMappingException = null; simpleMappingException = XmlUtils.findElements(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop", root); Validate.notNull(simpleMappingException, "There aren't Exceptions handled by the application."); StringBuilder exceptionList = new StringBuilder("Handled Exceptions:\n"); for (Element element : simpleMappingException) { exceptionList.append(element.getAttribute("key") + "\n"); } return exceptionList.toString(); }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { public String getHandledExceptionList() { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); List<Element> simpleMappingException = null; simpleMappingException = XmlUtils.findElements(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop", root); Validate.notNull(simpleMappingException, "There aren't Exceptions handled by the application."); StringBuilder exceptionList = new StringBuilder("Handled Exceptions:\n"); for (Element element : simpleMappingException) { exceptionList.append(element.getAttribute("key") + "\n"); } return exceptionList.toString(); } }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { public String getHandledExceptionList() { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); List<Element> simpleMappingException = null; simpleMappingException = XmlUtils.findElements(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop", root); Validate.notNull(simpleMappingException, "There aren't Exceptions handled by the application."); StringBuilder exceptionList = new StringBuilder("Handled Exceptions:\n"); for (Element element : simpleMappingException) { exceptionList.append(element.getAttribute("key") + "\n"); } return exceptionList.toString(); } }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { public String getHandledExceptionList() { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); List<Element> simpleMappingException = null; simpleMappingException = XmlUtils.findElements(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop", root); Validate.notNull(simpleMappingException, "There aren't Exceptions handled by the application."); StringBuilder exceptionList = new StringBuilder("Handled Exceptions:\n"); for (Element element : simpleMappingException) { exceptionList.append(element.getAttribute("key") + "\n"); } return exceptionList.toString(); } String getHandledExceptionList(); void addNewHandledException(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); void removeExceptionHandled(String exceptionName); void languageExceptionHandled(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); String getLanguagePropertiesFile(String exceptionLanguage); void setUpGvNIXExceptions(); boolean isExceptionMappingAvailable(); boolean isMessageMappingAvailable(); boolean isProjectAvailable(); static String getFilename(String path); WebProjectUtils getWebProjectUtils(); MessageBundleUtils getMessageBundleUtils(); OperationUtils getOperationUtils(); }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { public String getHandledExceptionList() { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); List<Element> simpleMappingException = null; simpleMappingException = XmlUtils.findElements(RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop", root); Validate.notNull(simpleMappingException, "There aren't Exceptions handled by the application."); StringBuilder exceptionList = new StringBuilder("Handled Exceptions:\n"); for (Element element : simpleMappingException) { exceptionList.append(element.getAttribute("key") + "\n"); } return exceptionList.toString(); } String getHandledExceptionList(); void addNewHandledException(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); void removeExceptionHandled(String exceptionName); void languageExceptionHandled(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); String getLanguagePropertiesFile(String exceptionLanguage); void setUpGvNIXExceptions(); boolean isExceptionMappingAvailable(); boolean isMessageMappingAvailable(); boolean isProjectAvailable(); static String getFilename(String path); WebProjectUtils getWebProjectUtils(); MessageBundleUtils getMessageBundleUtils(); OperationUtils getOperationUtils(); }
@Test public void testUpdateWebMvcConfig() throws Exception { String result; String expected; String exceptionName; String exceptionJspxPath; exceptionName = "java.lang.Exception"; expected = "Exception"; exceptionJspxPath = EXC_JSPX_PATH.concat( StringUtils.uncapitalize(expected)).concat(".jspx"); expect( pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_XML_PATH)).andReturn(EXC_WEB_XML); expect(fileManager.exists(EXC_WEB_XML)).andReturn(true); expect(fileManager.updateFile(EXC_WEB_XML)) .andReturn(webXmlMutableFile); expect(webXmlMutableFile.getInputStream()).andReturn( getClass().getResourceAsStream(EXC_WEB_XML)); expect( pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), "WEB-INF/views/" + StringUtils.uncapitalize(expected) + ".jspx")).andReturn(exceptionJspxPath); expect(fileManager.exists(exceptionJspxPath)).andReturn(false); expect(webXmlMutableFile.getOutputStream()).andReturn( new FileOutputStream("/tmp/exceptions-webmvc-config.xml")); replay(pathResolver, fileManager, webXmlMutableFile); result = webExceptionHandlerOperationsImpl .updateWebMvcConfig(exceptionName); assertEquals("Test 1 \nThere isn't new exception defined in " + EXC_WEB_XML + " file", StringUtils.uncapitalize(expected), result); logger.log(Level.INFO, "Test 1 \nNew Exception view: '" + result + "' defined in: " + EXC_WEB_XML); reset(pathResolver, fileManager, webXmlMutableFile); }
protected String updateWebMvcConfig(String exceptionName) { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); Element simpleMappingException = XmlUtils.findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root); Element exceptionResolver = XmlUtils .findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root); boolean updateMappings = false; boolean updateController = false; String exceptionViewName; if (exceptionResolver != null) { exceptionViewName = exceptionResolver.getTextContent(); } else { updateMappings = true; exceptionViewName = getExceptionViewName(exceptionName); } Element newExceptionMapping; newExceptionMapping = webXml.createElement("prop"); newExceptionMapping.setAttribute("key", exceptionName); Validate.isTrue(exceptionViewName != null, "Can't create the view for the:\t" + exceptionName + " Exception."); newExceptionMapping.setTextContent(exceptionViewName); if (updateMappings) { simpleMappingException.appendChild(newExceptionMapping); } Element newExceptionView = XmlUtils.findFirstElement( "/beans/view-controller[@path='/" + exceptionViewName + "']", root); if (newExceptionView == null) { updateController = true; } newExceptionView = webXml.createElementNS( "http: newExceptionView.setPrefix("mvc"); newExceptionView.setAttribute("path", "/" + exceptionViewName); if (updateController) { root.appendChild(newExceptionView); } if (updateMappings || updateController) { XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml); } return exceptionViewName; }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { protected String updateWebMvcConfig(String exceptionName) { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); Element simpleMappingException = XmlUtils.findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root); Element exceptionResolver = XmlUtils .findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root); boolean updateMappings = false; boolean updateController = false; String exceptionViewName; if (exceptionResolver != null) { exceptionViewName = exceptionResolver.getTextContent(); } else { updateMappings = true; exceptionViewName = getExceptionViewName(exceptionName); } Element newExceptionMapping; newExceptionMapping = webXml.createElement("prop"); newExceptionMapping.setAttribute("key", exceptionName); Validate.isTrue(exceptionViewName != null, "Can't create the view for the:\t" + exceptionName + " Exception."); newExceptionMapping.setTextContent(exceptionViewName); if (updateMappings) { simpleMappingException.appendChild(newExceptionMapping); } Element newExceptionView = XmlUtils.findFirstElement( "/beans/view-controller[@path='/" + exceptionViewName + "']", root); if (newExceptionView == null) { updateController = true; } newExceptionView = webXml.createElementNS( "http: newExceptionView.setPrefix("mvc"); newExceptionView.setAttribute("path", "/" + exceptionViewName); if (updateController) { root.appendChild(newExceptionView); } if (updateMappings || updateController) { XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml); } return exceptionViewName; } }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { protected String updateWebMvcConfig(String exceptionName) { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); Element simpleMappingException = XmlUtils.findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root); Element exceptionResolver = XmlUtils .findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root); boolean updateMappings = false; boolean updateController = false; String exceptionViewName; if (exceptionResolver != null) { exceptionViewName = exceptionResolver.getTextContent(); } else { updateMappings = true; exceptionViewName = getExceptionViewName(exceptionName); } Element newExceptionMapping; newExceptionMapping = webXml.createElement("prop"); newExceptionMapping.setAttribute("key", exceptionName); Validate.isTrue(exceptionViewName != null, "Can't create the view for the:\t" + exceptionName + " Exception."); newExceptionMapping.setTextContent(exceptionViewName); if (updateMappings) { simpleMappingException.appendChild(newExceptionMapping); } Element newExceptionView = XmlUtils.findFirstElement( "/beans/view-controller[@path='/" + exceptionViewName + "']", root); if (newExceptionView == null) { updateController = true; } newExceptionView = webXml.createElementNS( "http: newExceptionView.setPrefix("mvc"); newExceptionView.setAttribute("path", "/" + exceptionViewName); if (updateController) { root.appendChild(newExceptionView); } if (updateMappings || updateController) { XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml); } return exceptionViewName; } }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { protected String updateWebMvcConfig(String exceptionName) { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); Element simpleMappingException = XmlUtils.findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root); Element exceptionResolver = XmlUtils .findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root); boolean updateMappings = false; boolean updateController = false; String exceptionViewName; if (exceptionResolver != null) { exceptionViewName = exceptionResolver.getTextContent(); } else { updateMappings = true; exceptionViewName = getExceptionViewName(exceptionName); } Element newExceptionMapping; newExceptionMapping = webXml.createElement("prop"); newExceptionMapping.setAttribute("key", exceptionName); Validate.isTrue(exceptionViewName != null, "Can't create the view for the:\t" + exceptionName + " Exception."); newExceptionMapping.setTextContent(exceptionViewName); if (updateMappings) { simpleMappingException.appendChild(newExceptionMapping); } Element newExceptionView = XmlUtils.findFirstElement( "/beans/view-controller[@path='/" + exceptionViewName + "']", root); if (newExceptionView == null) { updateController = true; } newExceptionView = webXml.createElementNS( "http: newExceptionView.setPrefix("mvc"); newExceptionView.setAttribute("path", "/" + exceptionViewName); if (updateController) { root.appendChild(newExceptionView); } if (updateMappings || updateController) { XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml); } return exceptionViewName; } String getHandledExceptionList(); void addNewHandledException(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); void removeExceptionHandled(String exceptionName); void languageExceptionHandled(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); String getLanguagePropertiesFile(String exceptionLanguage); void setUpGvNIXExceptions(); boolean isExceptionMappingAvailable(); boolean isMessageMappingAvailable(); boolean isProjectAvailable(); static String getFilename(String path); WebProjectUtils getWebProjectUtils(); MessageBundleUtils getMessageBundleUtils(); OperationUtils getOperationUtils(); }
WebExceptionHandlerOperationsImpl implements WebExceptionHandlerOperations { protected String updateWebMvcConfig(String exceptionName) { String webXmlPath = pathResolver.getIdentifier( LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""), WEB_MVC_CONFIG); Validate.isTrue(fileManager.exists(webXmlPath), WEB_MVC_CONFIG_NOT_FOUND); MutableFile webXmlMutableFile = null; Document webXml; try { webXmlMutableFile = fileManager.updateFile(webXmlPath); webXml = XmlUtils.getDocumentBuilder().parse( webXmlMutableFile.getInputStream()); } catch (Exception e) { throw new IllegalStateException(e); } Element root = webXml.getDocumentElement(); Element simpleMappingException = XmlUtils.findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props", root); Element exceptionResolver = XmlUtils .findFirstElement( RESOLVER_BEAN_MESSAGE + "/property[@name='exceptionMappings']/props/prop[@key='" + exceptionName + "']", root); boolean updateMappings = false; boolean updateController = false; String exceptionViewName; if (exceptionResolver != null) { exceptionViewName = exceptionResolver.getTextContent(); } else { updateMappings = true; exceptionViewName = getExceptionViewName(exceptionName); } Element newExceptionMapping; newExceptionMapping = webXml.createElement("prop"); newExceptionMapping.setAttribute("key", exceptionName); Validate.isTrue(exceptionViewName != null, "Can't create the view for the:\t" + exceptionName + " Exception."); newExceptionMapping.setTextContent(exceptionViewName); if (updateMappings) { simpleMappingException.appendChild(newExceptionMapping); } Element newExceptionView = XmlUtils.findFirstElement( "/beans/view-controller[@path='/" + exceptionViewName + "']", root); if (newExceptionView == null) { updateController = true; } newExceptionView = webXml.createElementNS( "http: newExceptionView.setPrefix("mvc"); newExceptionView.setAttribute("path", "/" + exceptionViewName); if (updateController) { root.appendChild(newExceptionView); } if (updateMappings || updateController) { XmlUtils.writeXml(webXmlMutableFile.getOutputStream(), webXml); } return exceptionViewName; } String getHandledExceptionList(); void addNewHandledException(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); void removeExceptionHandled(String exceptionName); void languageExceptionHandled(String exceptionName, String exceptionTitle, String exceptionDescription, String exceptionLanguage); String getLanguagePropertiesFile(String exceptionLanguage); void setUpGvNIXExceptions(); boolean isExceptionMappingAvailable(); boolean isMessageMappingAvailable(); boolean isProjectAvailable(); static String getFilename(String path); WebProjectUtils getWebProjectUtils(); MessageBundleUtils getMessageBundleUtils(); OperationUtils getOperationUtils(); }
@Test public void testGetLocalName() throws Exception { assertEquals("address", WsdlParserUtils.getLocalName("soap:address")); }
protected static String getLocalName(String elementName) { Validate.notNull(elementName, "Element name required"); return elementName.replaceFirst(getNamespace(elementName) + NAMESPACE_SEPARATOR, ""); }
WsdlParserUtils { protected static String getLocalName(String elementName) { Validate.notNull(elementName, "Element name required"); return elementName.replaceFirst(getNamespace(elementName) + NAMESPACE_SEPARATOR, ""); } }
WsdlParserUtils { protected static String getLocalName(String elementName) { Validate.notNull(elementName, "Element name required"); return elementName.replaceFirst(getNamespace(elementName) + NAMESPACE_SEPARATOR, ""); } }
WsdlParserUtils { protected static String getLocalName(String elementName) { Validate.notNull(elementName, "Element name required"); return elementName.replaceFirst(getNamespace(elementName) + NAMESPACE_SEPARATOR, ""); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); }
WsdlParserUtils { protected static String getLocalName(String elementName) { Validate.notNull(elementName, "Element name required"); return elementName.replaceFirst(getNamespace(elementName) + NAMESPACE_SEPARATOR, ""); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); static final String SOAP_11_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_11; static final String SOAP_12_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_12; static final String XML_NAMESPACE_PREFIX; static final String NAMESPACE_SEPARATOR; static final String FILE_SEPARATOR; static final String XPATH_SEPARATOR; static final String PACKAGE_SEPARATOR; static final char javaPkgSeparator; static final Collator englishCollator; static final char keywordPrefix; static final String TARGET_GENERATED_SOURCES_PATH; static final String DEFINITIONS_ELEMENT; static final String BINDING_ELEMENT; static final String PORT_TYPE_ELEMENT; static final String SERVICE_ELEMENT; static final String PORT_ELEMENT; static final String ADDRESS_ELEMENT; static final String TARGET_NAMESPACE_ATTRIBUTE; static final String NAME_ATTRIBUTE; static final String BINDING_ATTRIBUTE; static final String TYPE_ATTRIBUTE; static final String STYLE_ATTRIBUTE; static final String BINDINGS_XPATH; static final String PORT_TYPES_XPATH; static final String ADDRESSES_XPATH; static final String CHILD_BINDINGS_XPATH; }
@Test public void testGetNamespace() throws Exception { assertEquals("soap", WsdlParserUtils.getNamespace("soap:address")); }
protected static String getNamespace(String elementName) { Validate.notNull(elementName, "Element name required"); String prefix = ""; int index = elementName.indexOf(NAMESPACE_SEPARATOR); if (index != -1) { prefix = elementName.substring(0, index); } return prefix; }
WsdlParserUtils { protected static String getNamespace(String elementName) { Validate.notNull(elementName, "Element name required"); String prefix = ""; int index = elementName.indexOf(NAMESPACE_SEPARATOR); if (index != -1) { prefix = elementName.substring(0, index); } return prefix; } }
WsdlParserUtils { protected static String getNamespace(String elementName) { Validate.notNull(elementName, "Element name required"); String prefix = ""; int index = elementName.indexOf(NAMESPACE_SEPARATOR); if (index != -1) { prefix = elementName.substring(0, index); } return prefix; } }
WsdlParserUtils { protected static String getNamespace(String elementName) { Validate.notNull(elementName, "Element name required"); String prefix = ""; int index = elementName.indexOf(NAMESPACE_SEPARATOR); if (index != -1) { prefix = elementName.substring(0, index); } return prefix; } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); }
WsdlParserUtils { protected static String getNamespace(String elementName) { Validate.notNull(elementName, "Element name required"); String prefix = ""; int index = elementName.indexOf(NAMESPACE_SEPARATOR); if (index != -1) { prefix = elementName.substring(0, index); } return prefix; } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); static final String SOAP_11_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_11; static final String SOAP_12_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_12; static final String XML_NAMESPACE_PREFIX; static final String NAMESPACE_SEPARATOR; static final String FILE_SEPARATOR; static final String XPATH_SEPARATOR; static final String PACKAGE_SEPARATOR; static final char javaPkgSeparator; static final Collator englishCollator; static final char keywordPrefix; static final String TARGET_GENERATED_SOURCES_PATH; static final String DEFINITIONS_ELEMENT; static final String BINDING_ELEMENT; static final String PORT_TYPE_ELEMENT; static final String SERVICE_ELEMENT; static final String PORT_ELEMENT; static final String ADDRESS_ELEMENT; static final String TARGET_NAMESPACE_ATTRIBUTE; static final String NAME_ATTRIBUTE; static final String BINDING_ATTRIBUTE; static final String TYPE_ATTRIBUTE; static final String STYLE_ATTRIBUTE; static final String BINDINGS_XPATH; static final String PORT_TYPES_XPATH; static final String ADDRESSES_XPATH; static final String CHILD_BINDINGS_XPATH; }
@Test public void testGetTargetNamespaceRelatedPackage() throws Exception { Document wsdl = XmlUtils.getDocumentBuilder().parse(TEMP_CONVERT_WSDL); Element root = wsdl.getDocumentElement(); assertEquals("com.w3schools.www.webservices.", WsdlParserUtils.getTargetNamespaceRelatedPackage(root)); File file = new File(SRC_TEST_RESOURCES_PATH, TEMP_CONVERT_MODIFIED_LOCAL_WSDL); wsdl = XmlUtils.getDocumentBuilder().parse(file); root = wsdl.getDocumentElement(); assertEquals("org.te3mupuuri.www.kk.idu1ur.", WsdlParserUtils.getTargetNamespaceRelatedPackage(root)); wsdl = XmlUtils.getDocumentBuilder().parse(ELASTIC_MAP_REDUCE_WSDL); root = wsdl.getDocumentElement(); assertEquals("com.amazonaws.elasticmapreduce.doc.u2009u03u31.", WsdlParserUtils.getTargetNamespaceRelatedPackage(root)); }
public static String getTargetNamespaceRelatedPackage(Element root) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String namespace = getTargetNamespace(root); String pkg = getTargetNamespaceRelatedPackage(namespace, root) .toLowerCase(); pkg = pkg.replace('_', 'u'); return pkg.concat("."); }
WsdlParserUtils { public static String getTargetNamespaceRelatedPackage(Element root) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String namespace = getTargetNamespace(root); String pkg = getTargetNamespaceRelatedPackage(namespace, root) .toLowerCase(); pkg = pkg.replace('_', 'u'); return pkg.concat("."); } }
WsdlParserUtils { public static String getTargetNamespaceRelatedPackage(Element root) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String namespace = getTargetNamespace(root); String pkg = getTargetNamespaceRelatedPackage(namespace, root) .toLowerCase(); pkg = pkg.replace('_', 'u'); return pkg.concat("."); } }
WsdlParserUtils { public static String getTargetNamespaceRelatedPackage(Element root) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String namespace = getTargetNamespace(root); String pkg = getTargetNamespaceRelatedPackage(namespace, root) .toLowerCase(); pkg = pkg.replace('_', 'u'); return pkg.concat("."); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); }
WsdlParserUtils { public static String getTargetNamespaceRelatedPackage(Element root) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String namespace = getTargetNamespace(root); String pkg = getTargetNamespaceRelatedPackage(namespace, root) .toLowerCase(); pkg = pkg.replace('_', 'u'); return pkg.concat("."); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); static final String SOAP_11_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_11; static final String SOAP_12_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_12; static final String XML_NAMESPACE_PREFIX; static final String NAMESPACE_SEPARATOR; static final String FILE_SEPARATOR; static final String XPATH_SEPARATOR; static final String PACKAGE_SEPARATOR; static final char javaPkgSeparator; static final Collator englishCollator; static final char keywordPrefix; static final String TARGET_GENERATED_SOURCES_PATH; static final String DEFINITIONS_ELEMENT; static final String BINDING_ELEMENT; static final String PORT_TYPE_ELEMENT; static final String SERVICE_ELEMENT; static final String PORT_ELEMENT; static final String ADDRESS_ELEMENT; static final String TARGET_NAMESPACE_ATTRIBUTE; static final String NAME_ATTRIBUTE; static final String BINDING_ATTRIBUTE; static final String TYPE_ATTRIBUTE; static final String STYLE_ATTRIBUTE; static final String BINDINGS_XPATH; static final String PORT_TYPES_XPATH; static final String ADDRESSES_XPATH; static final String CHILD_BINDINGS_XPATH; }
@Test public void testGetServiceClassPath() throws Exception { Document wsdl = XmlUtils.getDocumentBuilder().parse(TEMP_CONVERT_WSDL); Element root = wsdl.getDocumentElement(); assertEquals("com.w3schools.www.webservices.TempConvert", WsdlParserUtils.getServiceClassPath(root, WsType.IMPORT)); File file = new File(SRC_TEST_RESOURCES_PATH, TEMP_CONVERT_MODIFIED_LOCAL_WSDL); wsdl = XmlUtils.getDocumentBuilder().parse(file); root = wsdl.getDocumentElement(); assertEquals( "org.te3mupuuri.www.kk.idu1ur.TEMP_002fC_0023ONe_0040R_002bT$GE_003dR_002aG_0027E_00282_00293_002c4_002f2_0025Rmm12Mm", WsdlParserUtils.getServiceClassPath(root, WsType.IMPORT)); }
public static String getServiceClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String name = findFirstCompatibleServiceClassName(root, sense); if (sense.equals(WsType.IMPORT_RPC_ENCODED)) { name = name.concat("Locator"); } return path + capitalizeFirstChar(name); }
WsdlParserUtils { public static String getServiceClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String name = findFirstCompatibleServiceClassName(root, sense); if (sense.equals(WsType.IMPORT_RPC_ENCODED)) { name = name.concat("Locator"); } return path + capitalizeFirstChar(name); } }
WsdlParserUtils { public static String getServiceClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String name = findFirstCompatibleServiceClassName(root, sense); if (sense.equals(WsType.IMPORT_RPC_ENCODED)) { name = name.concat("Locator"); } return path + capitalizeFirstChar(name); } }
WsdlParserUtils { public static String getServiceClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String name = findFirstCompatibleServiceClassName(root, sense); if (sense.equals(WsType.IMPORT_RPC_ENCODED)) { name = name.concat("Locator"); } return path + capitalizeFirstChar(name); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); }
WsdlParserUtils { public static String getServiceClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String name = findFirstCompatibleServiceClassName(root, sense); if (sense.equals(WsType.IMPORT_RPC_ENCODED)) { name = name.concat("Locator"); } return path + capitalizeFirstChar(name); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); static final String SOAP_11_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_11; static final String SOAP_12_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_12; static final String XML_NAMESPACE_PREFIX; static final String NAMESPACE_SEPARATOR; static final String FILE_SEPARATOR; static final String XPATH_SEPARATOR; static final String PACKAGE_SEPARATOR; static final char javaPkgSeparator; static final Collator englishCollator; static final char keywordPrefix; static final String TARGET_GENERATED_SOURCES_PATH; static final String DEFINITIONS_ELEMENT; static final String BINDING_ELEMENT; static final String PORT_TYPE_ELEMENT; static final String SERVICE_ELEMENT; static final String PORT_ELEMENT; static final String ADDRESS_ELEMENT; static final String TARGET_NAMESPACE_ATTRIBUTE; static final String NAME_ATTRIBUTE; static final String BINDING_ATTRIBUTE; static final String TYPE_ATTRIBUTE; static final String STYLE_ATTRIBUTE; static final String BINDINGS_XPATH; static final String PORT_TYPES_XPATH; static final String ADDRESSES_XPATH; static final String CHILD_BINDINGS_XPATH; }
@Test public void testGetPortTypeClassPath() throws Exception { Document wsdl = XmlUtils.getDocumentBuilder().parse(TEMP_CONVERT_WSDL); Element root = wsdl.getDocumentElement(); assertEquals("com.w3schools.www.webservices.TempConvertSoap", WsdlParserUtils.getPortTypeClassPath(root, WsType.IMPORT)); wsdl = XmlUtils.getDocumentBuilder().parse(KK_WEB_SERVICE_ENG_WSDL); root = wsdl.getDocumentElement(); assertEquals("com.konakart.ws.KKWSEngIf", WsdlParserUtils.getPortTypeClassPath(root, WsType.IMPORT)); }
public static String getPortTypeClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String portType = findFirstCompatiblePortTypeClassName(root, sense); String port = findFirstCompatiblePortClassName(root, sense); if (WsType.IMPORT_RPC_ENCODED.equals(sense) && portType.equals(port)) { portType = portType.concat("_PortType"); } return path + capitalizeFirstChar(portType); }
WsdlParserUtils { public static String getPortTypeClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String portType = findFirstCompatiblePortTypeClassName(root, sense); String port = findFirstCompatiblePortClassName(root, sense); if (WsType.IMPORT_RPC_ENCODED.equals(sense) && portType.equals(port)) { portType = portType.concat("_PortType"); } return path + capitalizeFirstChar(portType); } }
WsdlParserUtils { public static String getPortTypeClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String portType = findFirstCompatiblePortTypeClassName(root, sense); String port = findFirstCompatiblePortClassName(root, sense); if (WsType.IMPORT_RPC_ENCODED.equals(sense) && portType.equals(port)) { portType = portType.concat("_PortType"); } return path + capitalizeFirstChar(portType); } }
WsdlParserUtils { public static String getPortTypeClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String portType = findFirstCompatiblePortTypeClassName(root, sense); String port = findFirstCompatiblePortClassName(root, sense); if (WsType.IMPORT_RPC_ENCODED.equals(sense) && portType.equals(port)) { portType = portType.concat("_PortType"); } return path + capitalizeFirstChar(portType); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); }
WsdlParserUtils { public static String getPortTypeClassPath(Element root, WsType sense) { Validate.notNull(root, ROOT_ELEMENT_REQUIRED); String path = getTargetNamespaceRelatedPackage(root); String portType = findFirstCompatiblePortTypeClassName(root, sense); String port = findFirstCompatiblePortClassName(root, sense); if (WsType.IMPORT_RPC_ENCODED.equals(sense) && portType.equals(port)) { portType = portType.concat("_PortType"); } return path + capitalizeFirstChar(portType); } static String getTargetNamespace(Element root); static String getTargetNamespaceRelatedPackage(Element root); static String makePackageName(String namespace); static boolean isJavaKeyword(String keyword); static String makeNonJavaKeyword(String keyword); static Element findFirstCompatibleAddress(Element root); static String getServiceClassPath(Element root, WsType sense); static String getPortTypeClassPath(Element root, WsType sense); static File getPortTypeJavaFile(Element root, WsType sense); static String findFirstCompatibleServiceElementName(Element root); static Element findFirstCompatiblePort(Element root); static Element checkCompatiblePort(Element root); static Element checkCompatibleAddress(Element root); static String findFirstCompatiblePortClassName(Element root, WsType sense); static boolean isJavaId(String id); static String xmlNameToJavaClass(String name); static String capitalizeFirstChar(String name); static String xmlNameToJava(String name); static boolean isRpcEncoded(Element root); static Element validateWsdlUrl(String url); static final String SOAP_11_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_11; static final String SOAP_12_NAMESPACE; static final String NAMESPACE_WITHOUT_SLASH_12; static final String XML_NAMESPACE_PREFIX; static final String NAMESPACE_SEPARATOR; static final String FILE_SEPARATOR; static final String XPATH_SEPARATOR; static final String PACKAGE_SEPARATOR; static final char javaPkgSeparator; static final Collator englishCollator; static final char keywordPrefix; static final String TARGET_GENERATED_SOURCES_PATH; static final String DEFINITIONS_ELEMENT; static final String BINDING_ELEMENT; static final String PORT_TYPE_ELEMENT; static final String SERVICE_ELEMENT; static final String PORT_ELEMENT; static final String ADDRESS_ELEMENT; static final String TARGET_NAMESPACE_ATTRIBUTE; static final String NAME_ATTRIBUTE; static final String BINDING_ATTRIBUTE; static final String TYPE_ATTRIBUTE; static final String STYLE_ATTRIBUTE; static final String BINDINGS_XPATH; static final String PORT_TYPES_XPATH; static final String ADDRESSES_XPATH; static final String CHILD_BINDINGS_XPATH; }
@Test public void testConvertPackageToTargetNamespace() throws Exception { String packageName = "org.gvnix.service.roo.addon"; String targetNamespaceExpected = "http: String targetNamespaceResult; targetNamespaceResult = wSConfigServiceImpl .convertPackageToTargetNamespace(packageName); Validate.isTrue( targetNamespaceResult != null && targetNamespaceResult.length() != 0, "The method doesn't work properly."); assertTrue("The namespace is not well generated", targetNamespaceResult.contains(targetNamespaceExpected)); }
public String convertPackageToTargetNamespace(String packageName) { if (!StringUtils.isNotBlank(packageName)) { return ""; } String[] delimitedString = StringUtils.split(packageName, "."); List<String> revertedList = new ArrayList<String>(); String revertedString; for (int i = delimitedString.length - 1; i >= 0; i--) { revertedList.add(delimitedString[i]); } revertedString = collectionToDelimitedString(revertedList, ".", "", ""); revertedString = "http: return revertedString; }
WSConfigServiceImpl implements WSConfigService { public String convertPackageToTargetNamespace(String packageName) { if (!StringUtils.isNotBlank(packageName)) { return ""; } String[] delimitedString = StringUtils.split(packageName, "."); List<String> revertedList = new ArrayList<String>(); String revertedString; for (int i = delimitedString.length - 1; i >= 0; i--) { revertedList.add(delimitedString[i]); } revertedString = collectionToDelimitedString(revertedList, ".", "", ""); revertedString = "http: return revertedString; } }
WSConfigServiceImpl implements WSConfigService { public String convertPackageToTargetNamespace(String packageName) { if (!StringUtils.isNotBlank(packageName)) { return ""; } String[] delimitedString = StringUtils.split(packageName, "."); List<String> revertedList = new ArrayList<String>(); String revertedString; for (int i = delimitedString.length - 1; i >= 0; i--) { revertedList.add(delimitedString[i]); } revertedString = collectionToDelimitedString(revertedList, ".", "", ""); revertedString = "http: return revertedString; } }
WSConfigServiceImpl implements WSConfigService { public String convertPackageToTargetNamespace(String packageName) { if (!StringUtils.isNotBlank(packageName)) { return ""; } String[] delimitedString = StringUtils.split(packageName, "."); List<String> revertedList = new ArrayList<String>(); String revertedString; for (int i = delimitedString.length - 1; i >= 0; i--) { revertedList.add(delimitedString[i]); } revertedString = collectionToDelimitedString(revertedList, ".", "", ""); revertedString = "http: return revertedString; } boolean install(WsType type); boolean publishClassAsWebService(JavaType className, AnnotationMetadata annotationMetadata); String convertPackageToTargetNamespace(String packageName); void addToJava2wsPlugin(JavaType serviceClass, String serviceName, String addressName, String fullyQualifiedTypeName); void installWsdl2javaPlugin(); boolean addImportLocation(String wsdlLocation, WsType type); boolean addWsdlLocation(String wsdlLocation, Document wsdlDocument); void disableWsdlLocation(); boolean importService(JavaType serviceClass, String wsdlLocation, WsType type); void mvn(String parameters, String message); static String collectionToDelimitedString(List<String> coll, String delim, String prefix, String suffix); MetadataService getMetadataService(); FileManager getFileManager(); ProjectOperations getProjectOperations(); SecurityService getSecurityService(); AnnotationsService getAnnotationsService(); MavenOperations getMavenOperations(); }
WSConfigServiceImpl implements WSConfigService { public String convertPackageToTargetNamespace(String packageName) { if (!StringUtils.isNotBlank(packageName)) { return ""; } String[] delimitedString = StringUtils.split(packageName, "."); List<String> revertedList = new ArrayList<String>(); String revertedString; for (int i = delimitedString.length - 1; i >= 0; i--) { revertedList.add(delimitedString[i]); } revertedString = collectionToDelimitedString(revertedList, ".", "", ""); revertedString = "http: return revertedString; } boolean install(WsType type); boolean publishClassAsWebService(JavaType className, AnnotationMetadata annotationMetadata); String convertPackageToTargetNamespace(String packageName); void addToJava2wsPlugin(JavaType serviceClass, String serviceName, String addressName, String fullyQualifiedTypeName); void installWsdl2javaPlugin(); boolean addImportLocation(String wsdlLocation, WsType type); boolean addWsdlLocation(String wsdlLocation, Document wsdlDocument); void disableWsdlLocation(); boolean importService(JavaType serviceClass, String wsdlLocation, WsType type); void mvn(String parameters, String message); static String collectionToDelimitedString(List<String> coll, String delim, String prefix, String suffix); MetadataService getMetadataService(); FileManager getFileManager(); ProjectOperations getProjectOperations(); SecurityService getSecurityService(); AnnotationsService getAnnotationsService(); MavenOperations getMavenOperations(); }
@Test public void swiftTest() { String withoutReplacement = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, " + "J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.,:'+-/()?"; String replaceSwift = Iso20022Util.replaceSwift(withoutReplacement); Assert.assertEquals(withoutReplacement, replaceSwift); String withReplacement = "asdfA SDF++* \"13 2456?=)(_:;; M@|#@#|@||@#¼¼½¬|||]¢}"; String expectedAfterReplacement = "asdfA SDF++. .13 2456?.)(.:.. M....................."; replaceSwift = Iso20022Util.replaceSwift(withReplacement); Assert.assertEquals(expectedAfterReplacement, replaceSwift); String withReplacementCH = "!;>÷=àäöü&"; String expectedAfterReplacementCH = ".....aaeoeue+"; replaceSwift = Iso20022Util.replaceSwift(withReplacementCH); Assert.assertEquals(expectedAfterReplacementCH, replaceSwift); String withReplacementCH2 = "51/1/Chindä & Co. Luzärn"; String expectedAfterReplacementCH2 = "51/1/Chindae + Co. Luzaern"; replaceSwift = Iso20022Util.replaceSwift(withReplacementCH2); Assert.assertEquals(expectedAfterReplacementCH2, replaceSwift); String withReplacementDoubleSlash = "/Nicht mit / beginnen und an keiner Stelle String expectedAfterReplacementDoubleSlash = "Nicht mit / beginnen und an keiner Stelle / enthalten."; replaceSwift = Iso20022Util.replaceSwift(withReplacementDoubleSlash); Assert.assertEquals(expectedAfterReplacementDoubleSlash, replaceSwift); }
@Nullable @Contract("!null->!null; null->null;") public static String replaceSwift(@Nullable String text) { if (null == text) { return null; } String result = text; for (String[] swiftReplacement : SWIFT_REPLACEMENTS) { result = result.replace(swiftReplacement[0], swiftReplacement[1]); } result = SWIFT_EXCLUDE_PATTERN.matcher(result).replaceAll("."); result = DOUBLE_QUOTE_PATTERN.matcher(result).replaceAll(Matcher.quoteReplacement("/")); if (result.startsWith("/")) { result = result.substring(1); } return result; }
Iso20022Util { @Nullable @Contract("!null->!null; null->null;") public static String replaceSwift(@Nullable String text) { if (null == text) { return null; } String result = text; for (String[] swiftReplacement : SWIFT_REPLACEMENTS) { result = result.replace(swiftReplacement[0], swiftReplacement[1]); } result = SWIFT_EXCLUDE_PATTERN.matcher(result).replaceAll("."); result = DOUBLE_QUOTE_PATTERN.matcher(result).replaceAll(Matcher.quoteReplacement("/")); if (result.startsWith("/")) { result = result.substring(1); } return result; } }
Iso20022Util { @Nullable @Contract("!null->!null; null->null;") public static String replaceSwift(@Nullable String text) { if (null == text) { return null; } String result = text; for (String[] swiftReplacement : SWIFT_REPLACEMENTS) { result = result.replace(swiftReplacement[0], swiftReplacement[1]); } result = SWIFT_EXCLUDE_PATTERN.matcher(result).replaceAll("."); result = DOUBLE_QUOTE_PATTERN.matcher(result).replaceAll(Matcher.quoteReplacement("/")); if (result.startsWith("/")) { result = result.substring(1); } return result; } private Iso20022Util(); }
Iso20022Util { @Nullable @Contract("!null->!null; null->null;") public static String replaceSwift(@Nullable String text) { if (null == text) { return null; } String result = text; for (String[] swiftReplacement : SWIFT_REPLACEMENTS) { result = result.replace(swiftReplacement[0], swiftReplacement[1]); } result = SWIFT_EXCLUDE_PATTERN.matcher(result).replaceAll("."); result = DOUBLE_QUOTE_PATTERN.matcher(result).replaceAll(Matcher.quoteReplacement("/")); if (result.startsWith("/")) { result = result.substring(1); } return result; } private Iso20022Util(); @Nonnull static XMLGregorianCalendar toXmlGregorianCalendar(@Nonnull LocalDateTime localDateTime); @Nonnull static XMLGregorianCalendar toXmlGregorianCalendar(@Nonnull ZonedDateTime zonedDateTime); @Nonnull static LocalDateTime from(@Nonnull XMLGregorianCalendar calendar); @Nullable static LocalDateTime from(@Nullable DateAndDateTimeChoice choice); @Nullable @Contract("!null->!null; null->null;") static String replaceSwift(@Nullable String text); }
Iso20022Util { @Nullable @Contract("!null->!null; null->null;") public static String replaceSwift(@Nullable String text) { if (null == text) { return null; } String result = text; for (String[] swiftReplacement : SWIFT_REPLACEMENTS) { result = result.replace(swiftReplacement[0], swiftReplacement[1]); } result = SWIFT_EXCLUDE_PATTERN.matcher(result).replaceAll("."); result = DOUBLE_QUOTE_PATTERN.matcher(result).replaceAll(Matcher.quoteReplacement("/")); if (result.startsWith("/")) { result = result.substring(1); } return result; } private Iso20022Util(); @Nonnull static XMLGregorianCalendar toXmlGregorianCalendar(@Nonnull LocalDateTime localDateTime); @Nonnull static XMLGregorianCalendar toXmlGregorianCalendar(@Nonnull ZonedDateTime zonedDateTime); @Nonnull static LocalDateTime from(@Nonnull XMLGregorianCalendar calendar); @Nullable static LocalDateTime from(@Nullable DateAndDateTimeChoice choice); @Nullable @Contract("!null->!null; null->null;") static String replaceSwift(@Nullable String text); }
@Test public void validateXmlWithXsdSuccessTest() { assertTrue(CamtUtil.isMatchingXsdSchema(readXml(VALID_CAMT53_XML), CAMT053V00104.getXsdPath())); assertTrue(CamtUtil.isMatchingXsdSchema(readXml(VALID_CAMT54_XML), CAMT054V00104.getXsdPath())); }
public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } private CamtUtil(); }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } private CamtUtil(); @Nonnull static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes); static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd); }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } private CamtUtil(); @Nonnull static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes); static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd); }
@Test public void validateXmlWithXsdFailureTest() { byte[] bytes = readXml(INVALID_XML); assertFalse(CamtUtil.isMatchingXsdSchema(bytes, CAMT054V00104.getXsdPath())); assertFalse(CamtUtil.isMatchingXsdSchema(readXml(VALID_CAMT53_XML), CAMT054V00104.getXsdPath())); assertFalse(CamtUtil.isMatchingXsdSchema(readXml(VALID_CAMT54_XML), CAMT053V00104.getXsdPath())); }
public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } private CamtUtil(); }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } private CamtUtil(); @Nonnull static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes); static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd); }
CamtUtil { public static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd) { try (ByteArrayInputStream xmlAsStream = new ByteArrayInputStream(xmlAsBytes); InputStream xsdAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToXsd)) { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new StreamSource(xsdAsStream)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(xmlAsStream)); return true; } catch (IOException e) { throw new Iso20022RuntimeException("IO Exception while validating xml file with xsd schema", e); } catch (SAXException ignore) { return false; } } private CamtUtil(); @Nonnull static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes); static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd); }
@Test public void detectDetectCamtTypeVersionTest() { assertEquals(CAMT053V00104, CamtUtil.detectCamtTypeVersion(readXml(VALID_CAMT53_XML))); assertEquals(CAMT054V00104, CamtUtil.detectCamtTypeVersion(readXml(VALID_CAMT54_XML))); }
@Nonnull public static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes) throws Iso20022RuntimeException { return Arrays.stream(CamtTypeVersion.values()) .filter(type -> isMatchingXsdSchema(xmlAsBytes, type.getXsdPath())) .findAny() .orElseThrow(() -> new Iso20022RuntimeException("Cannot process input. XSD validation failed.")); }
CamtUtil { @Nonnull public static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes) throws Iso20022RuntimeException { return Arrays.stream(CamtTypeVersion.values()) .filter(type -> isMatchingXsdSchema(xmlAsBytes, type.getXsdPath())) .findAny() .orElseThrow(() -> new Iso20022RuntimeException("Cannot process input. XSD validation failed.")); } }
CamtUtil { @Nonnull public static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes) throws Iso20022RuntimeException { return Arrays.stream(CamtTypeVersion.values()) .filter(type -> isMatchingXsdSchema(xmlAsBytes, type.getXsdPath())) .findAny() .orElseThrow(() -> new Iso20022RuntimeException("Cannot process input. XSD validation failed.")); } private CamtUtil(); }
CamtUtil { @Nonnull public static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes) throws Iso20022RuntimeException { return Arrays.stream(CamtTypeVersion.values()) .filter(type -> isMatchingXsdSchema(xmlAsBytes, type.getXsdPath())) .findAny() .orElseThrow(() -> new Iso20022RuntimeException("Cannot process input. XSD validation failed.")); } private CamtUtil(); @Nonnull static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes); static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd); }
CamtUtil { @Nonnull public static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes) throws Iso20022RuntimeException { return Arrays.stream(CamtTypeVersion.values()) .filter(type -> isMatchingXsdSchema(xmlAsBytes, type.getXsdPath())) .findAny() .orElseThrow(() -> new Iso20022RuntimeException("Cannot process input. XSD validation failed.")); } private CamtUtil(); @Nonnull static CamtTypeVersion detectCamtTypeVersion(@Nonnull byte[] xmlAsBytes); static boolean isMatchingXsdSchema(byte[] xmlAsBytes, @Nonnull String pathToXsd); }
@Test public void testNumberOfDigits() { assertThat(FormatUtil.numberOfDigits(0)).isEqualTo(1); assertThat(FormatUtil.numberOfDigits(1)).isEqualTo(1); assertThat(FormatUtil.numberOfDigits(5)).isEqualTo(1); assertThat(FormatUtil.numberOfDigits(10)).isEqualTo(2); assertThat(FormatUtil.numberOfDigits(99)).isEqualTo(2); assertThat(FormatUtil.numberOfDigits(100)).isEqualTo(3); assertThat(FormatUtil.numberOfDigits(1000)).isEqualTo(4); }
static int numberOfDigits(long l) { if (l == 0) { return 1; } return ((int) Math.ceil(Math.log10(l + 0.5))); }
FormatUtil { static int numberOfDigits(long l) { if (l == 0) { return 1; } return ((int) Math.ceil(Math.log10(l + 0.5))); } }
FormatUtil { static int numberOfDigits(long l) { if (l == 0) { return 1; } return ((int) Math.ceil(Math.log10(l + 0.5))); } private FormatUtil(); }
FormatUtil { static int numberOfDigits(long l) { if (l == 0) { return 1; } return ((int) Math.ceil(Math.log10(l + 0.5))); } private FormatUtil(); static void padRight(StringBuilder buf, char c, int count); }
FormatUtil { static int numberOfDigits(long l) { if (l == 0) { return 1; } return ((int) Math.ceil(Math.log10(l + 0.5))); } private FormatUtil(); static void padRight(StringBuilder buf, char c, int count); }
@Test public void testRunWithUserNameFilter() { SmallFilesReportCommand command = new SmallFilesReportCommand(); command.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { command.mainCommand.out = printStream; command.mainCommand.err = command.mainCommand.out; command.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); command.mainCommand.userNameFilter = "mm"; command.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo("\n" + "Small files report (< 2 MiB)\n" + "\n" + "Overall small files : 3\n" + "User (filtered) small files : 2\n" + "\n" + "#Small files | Path (top 10) \n" + "------------------------------\n" + " 3 | /\n" + " 2 | /test3\n" + " 1 | /test3/foo\n" + "\n" + "Username | #Small files | %\n" + "------------------------------------\n" + "mm | 2 | 66.7%\n" + "\n" + "Username | Small files hotspots (top 10 count/path)\n" + "---------------------------------------------------\n" + "mm | 2 | /\n" + " | 1 | /test3\n" + "---------------------------------------------------\n" ); } }
@Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } @Override void run(); }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } @Override void run(); }
@Test public void testComputeBucketUpperBorders() { SizeBucket sizeBucket = new SizeBucket(); assertThat(sizeBucket.computeBucketUpperBorders()).isEqualTo(new long[]{0 }); sizeBucket.add(1024L); assertThat(sizeBucket.computeBucketUpperBorders()).isEqualTo(new long[]{0, 1024L * 1024L }); }
public long[] computeBucketUpperBorders() { return getBucketModel().computeBucketUpperBorders(findMaxNumBucket()); }
SizeBucket { public long[] computeBucketUpperBorders() { return getBucketModel().computeBucketUpperBorders(findMaxNumBucket()); } }
SizeBucket { public long[] computeBucketUpperBorders() { return getBucketModel().computeBucketUpperBorders(findMaxNumBucket()); } SizeBucket(); SizeBucket(BucketModel bucketModel); }
SizeBucket { public long[] computeBucketUpperBorders() { return getBucketModel().computeBucketUpperBorders(findMaxNumBucket()); } SizeBucket(); SizeBucket(BucketModel bucketModel); void add(long size); long[] computeBucketUpperBorders(); int findMaxNumBucket(); long getBucketCounter(int bucket); long[] get(); int size(); BucketModel getBucketModel(); @Override String toString(); }
SizeBucket { public long[] computeBucketUpperBorders() { return getBucketModel().computeBucketUpperBorders(findMaxNumBucket()); } SizeBucket(); SizeBucket(BucketModel bucketModel); void add(long size); long[] computeBucketUpperBorders(); int findMaxNumBucket(); long getBucketCounter(int bucket); long[] get(); int size(); BucketModel getBucketModel(); @Override String toString(); }
@Test public void testParse() { for (int i = 0; i < formattedValues.length; i++) { assertThat(IECBinary.parse(formattedValues[i])).isEqualTo(rawValues[i]); } assertThat(IECBinary.parse("0")).isEqualTo(0); assertThat(IECBinary.parse("0B")).isEqualTo(0); assertThat(IECBinary.parse("1 KiB")).isEqualTo(1024); for (String value : new String[]{"", " ", "KiB"}) { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> IECBinary.parse(value)); } }
public static long parse(String formattedValue) { final Matcher matcher = PATTERN_VALUE_WITH_STORAGE_UNIT.matcher(formattedValue); if (!matcher.matches()) { throw new IllegalArgumentException("Expected pattern " + PATTERN_VALUE_WITH_STORAGE_UNIT.pattern() + " but got value <" + formattedValue + ">"); } long number = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); if (null != unit) { for (int i = 0; i < UNITS.length; i++) { if (unit.equalsIgnoreCase(UNITS[i])) { number *= Math.pow(1024, i); break; } } } return number; }
IECBinary { public static long parse(String formattedValue) { final Matcher matcher = PATTERN_VALUE_WITH_STORAGE_UNIT.matcher(formattedValue); if (!matcher.matches()) { throw new IllegalArgumentException("Expected pattern " + PATTERN_VALUE_WITH_STORAGE_UNIT.pattern() + " but got value <" + formattedValue + ">"); } long number = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); if (null != unit) { for (int i = 0; i < UNITS.length; i++) { if (unit.equalsIgnoreCase(UNITS[i])) { number *= Math.pow(1024, i); break; } } } return number; } }
IECBinary { public static long parse(String formattedValue) { final Matcher matcher = PATTERN_VALUE_WITH_STORAGE_UNIT.matcher(formattedValue); if (!matcher.matches()) { throw new IllegalArgumentException("Expected pattern " + PATTERN_VALUE_WITH_STORAGE_UNIT.pattern() + " but got value <" + formattedValue + ">"); } long number = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); if (null != unit) { for (int i = 0; i < UNITS.length; i++) { if (unit.equalsIgnoreCase(UNITS[i])) { number *= Math.pow(1024, i); break; } } } return number; } private IECBinary(); }
IECBinary { public static long parse(String formattedValue) { final Matcher matcher = PATTERN_VALUE_WITH_STORAGE_UNIT.matcher(formattedValue); if (!matcher.matches()) { throw new IllegalArgumentException("Expected pattern " + PATTERN_VALUE_WITH_STORAGE_UNIT.pattern() + " but got value <" + formattedValue + ">"); } long number = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); if (null != unit) { for (int i = 0; i < UNITS.length; i++) { if (unit.equalsIgnoreCase(UNITS[i])) { number *= Math.pow(1024, i); break; } } } return number; } private IECBinary(); static String format(long numericalValue); static long parse(String formattedValue); }
IECBinary { public static long parse(String formattedValue) { final Matcher matcher = PATTERN_VALUE_WITH_STORAGE_UNIT.matcher(formattedValue); if (!matcher.matches()) { throw new IllegalArgumentException("Expected pattern " + PATTERN_VALUE_WITH_STORAGE_UNIT.pattern() + " but got value <" + formattedValue + ">"); } long number = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); if (null != unit) { for (int i = 0; i < UNITS.length; i++) { if (unit.equalsIgnoreCase(UNITS[i])) { number *= Math.pow(1024, i); break; } } } return number; } private IECBinary(); static String format(long numericalValue); static long parse(String formattedValue); }
@Test public void testFormat() { for (int i = 0; i < formattedValues.length; i++) { assertThat(IECBinary.format(rawValues[i])).isEqualTo(formattedValues[i]); } assertThat(IECBinary.format(1024 + 512 - 1)).isEqualTo("1 KiB"); assertThat(IECBinary.format(1024 + 512)).isEqualTo("2 KiB"); }
public static String format(long numericalValue) { if (numericalValue < 1024) { return numericalValue + " B"; } int exp = (int) (Math.log(numericalValue) / Math.log(1024)); String pre = "KMGTPE".charAt(exp - 1) + "i"; return String.format("%.0f %sB", numericalValue / Math.pow(1024, exp), pre); }
IECBinary { public static String format(long numericalValue) { if (numericalValue < 1024) { return numericalValue + " B"; } int exp = (int) (Math.log(numericalValue) / Math.log(1024)); String pre = "KMGTPE".charAt(exp - 1) + "i"; return String.format("%.0f %sB", numericalValue / Math.pow(1024, exp), pre); } }
IECBinary { public static String format(long numericalValue) { if (numericalValue < 1024) { return numericalValue + " B"; } int exp = (int) (Math.log(numericalValue) / Math.log(1024)); String pre = "KMGTPE".charAt(exp - 1) + "i"; return String.format("%.0f %sB", numericalValue / Math.pow(1024, exp), pre); } private IECBinary(); }
IECBinary { public static String format(long numericalValue) { if (numericalValue < 1024) { return numericalValue + " B"; } int exp = (int) (Math.log(numericalValue) / Math.log(1024)); String pre = "KMGTPE".charAt(exp - 1) + "i"; return String.format("%.0f %sB", numericalValue / Math.pow(1024, exp), pre); } private IECBinary(); static String format(long numericalValue); static long parse(String formattedValue); }
IECBinary { public static String format(long numericalValue) { if (numericalValue < 1024) { return numericalValue + " B"; } int exp = (int) (Math.log(numericalValue) / Math.log(1024)); String pre = "KMGTPE".charAt(exp - 1) + "i"; return String.format("%.0f %sB", numericalValue / Math.pow(1024, exp), pre); } private IECBinary(); static String format(long numericalValue); static long parse(String formattedValue); }
@Test public void testLoadHadoop27xFsImage() throws IOException { try (RandomAccessFile file = new RandomAccessFile("src/test/resources/fsi_small_h2x.img", "r")) { final FsImageData hadoopV2xImage = new FsImageLoader.Builder().parallel().build().load(file); loadAndVisit(hadoopV2xImage, new FsVisitor.Builder()); } }
public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); FsImageData load(RandomAccessFile file); }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); FsImageData load(RandomAccessFile file); }
@Test public void testLoadHadoop33xCompressedFsImage() throws IOException { try (RandomAccessFile file = new RandomAccessFile("src/test/resources/fsimage_d800_f210k_compressed.img", "r")) { final FsImageData hadoopV3xCompressedImage = new FsImageLoader.Builder().parallel().build().load(file); final CountingVisitor visitor = new CountingVisitor(hadoopV3xCompressedImage); new FsVisitor.Builder().parallel().visit(hadoopV3xCompressedImage, visitor); assertThat(visitor.groups.size()).isEqualTo(1); assertThat(visitor.users.size()).isEqualTo(1); assertThat(visitor.numFiles.get()).isEqualTo(209560L); assertThat(visitor.numDirs.get()).isEqualTo(807L); assertThat(visitor.numSymLinks.get()).isEqualTo(0L); } }
public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); FsImageData load(RandomAccessFile file); }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); FsImageData load(RandomAccessFile file); }
@Test public void testLoadEmptyFSImage() throws IOException { try (RandomAccessFile file = new RandomAccessFile("src/test/resources/fsimage_0000000000000000000", "r")) { final FsImageData emptyImage = new FsImageLoader.Builder().build().load(file); AtomicBoolean rootVisited = new AtomicBoolean(false); new FsVisitor.Builder().visit(emptyImage, new FsVisitor() { @Override public void onFile(FsImageProto.INodeSection.INode inode, String path) { } @Override public void onDirectory(FsImageProto.INodeSection.INode inode, String path) { rootVisited.set(ROOT_PATH.equals(path)); } @Override public void onSymLink(FsImageProto.INodeSection.INode inode, String path) { } }); assertThat(rootVisited).isTrue(); } }
public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); FsImageData load(RandomAccessFile file); }
FsImageLoader { public FsImageData load(RandomAccessFile file) throws IOException { if (!FSImageUtil.checkFileFormat(file)) { throw new IOException("Unrecognized FSImage format (no magic header?)"); } FileSummary summary = FSImageUtil.loadSummary(file); String codec = summary.getCodec(); try (FileInputStream fin = new FileInputStream(file.getFD())) { final List<FileSummary.Section> sectionsList = summary.getSectionsList(); FileSummary.Section sectionStringTable = findSectionByName(sectionsList, SectionName.STRING_TABLE); StringTable stringTable = loadSection(fin, codec, sectionStringTable, this::loadStringTable); FileSummary.Section sectionInodeRef = findSectionByName(sectionsList, SectionName.INODE_REFERENCE); ImmutableLongArray refIdList = loadSection(fin, codec, sectionInodeRef, this::loadINodeReferenceSection); FileSummary.Section sectionInode = findSectionByName(sectionsList, SectionName.INODE); INodesRepository inodes = loadSection(fin, codec, sectionInode, this::loadINodeSection); FileSummary.Section sectionInodeDir = findSectionByName(sectionsList, SectionName.INODE_DIR); Long2ObjectLinkedOpenHashMap<long[]> dirMap = loadSection(fin, codec, sectionInodeDir, (InputStream is, long length) -> loadINodeDirectorySection(is, refIdList)); return new FsImageData(stringTable, inodes, dirMap); } } FsImageLoader(Builder.LoadingStrategy loadingStrategy); FsImageData load(RandomAccessFile file); }
@Test public void testRun() { PathReportCommand pathReportCommand = new PathReportCommand(); pathReportCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { pathReportCommand.mainCommand.out = printStream; pathReportCommand.mainCommand.err = pathReportCommand.mainCommand.out; pathReportCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); pathReportCommand.run(); final String actualStdout = byteArrayOutputStream.toString(); assertThat(actualStdout) .isEqualTo("\n" + "Path report (path=/, no filter) :\n" + "---------------------------------\n" + "\n" + "11 files, 8 directories and 0 symlinks\n" + "\n" + "drwxr-xr-x mm supergroup /\n" + "drwxr-xr-x mm supergroup /test1\n" + "drwxr-xr-x mm supergroup /test2\n" + "drwxr-xr-x mm supergroup /test3\n" + "drwxr-xr-x mm supergroup /test3/foo\n" + "drwxr-xr-x mm supergroup /test3/foo/bar\n" + "-rw-r--r-- mm nobody /test3/foo/bar/test_20MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_2MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_40MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_4MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_5MiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/bar/test_80MiB.img\n" + "-rw-r--r-- root root /test3/foo/test_1KiB.img\n" + "-rw-r--r-- mm supergroup /test3/foo/test_20MiB.img\n" + "-rw-r--r-- mm supergroup /test3/test.img\n" + "-rw-r--r-- foo nobody /test3/test_160MiB.img\n" + "-rw-r--r-- mm supergroup /test_2KiB.img\n" + "drwxr-xr-x mm supergroup /user\n" + "drwxr-xr-x mm supergroup /user/mm\n" ); } }
@Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } @Override void run(); }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } @Override void run(); }
@Test public void testRunWithFilterForUserFoo() { PathReportCommand pathReportCommand = new PathReportCommand(); pathReportCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { pathReportCommand.mainCommand.out = printStream; pathReportCommand.mainCommand.err = printStream; pathReportCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); pathReportCommand.mainCommand.userNameFilter = "foo"; pathReportCommand.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo("\n" + "Path report (path=/, user=~foo) :\n" + "---------------------------------\n" + "\n" + "1 file, 0 directories and 0 symlinks\n" + "\n" + "-rw-r--r-- foo nobody /test3/test_160MiB.img\n" ); } }
@Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } @Override void run(); }
PathReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { createReport(fsImageData); } } @Override void run(); }
@Test public void testVersion() { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); HdfsFSImageTool.out = new PrintStream(byteArrayOutputStream); HdfsFSImageTool.err = HdfsFSImageTool.out; HdfsFSImageTool.run(new String[]{"-V"}); Pattern pattern = Pattern.compile("Version 1\\..*\n" + "Build timestamp 20.*\n" + "SCM Version .*\n" + "SCM Branch .*\n"); assertThat(byteArrayOutputStream.toString()) .matches(pattern); }
protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } static void main(String[] args); }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } static void main(String[] args); }
@Test public void testHelp() { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); HdfsFSImageTool.out = new PrintStream(byteArrayOutputStream); HdfsFSImageTool.err = HdfsFSImageTool.out; HdfsFSImageTool.run(new String[]{"-h"}); assertThat(byteArrayOutputStream.toString()) .isEqualTo("Analyze Hadoop FSImage file for user/group reports\n" + "Usage: hfsa-tool [-hVv] [-fun=<userNameFilter>] [-p=<dirs>[,<dirs>...]]... FILE\n" + " [COMMAND]\n" + " FILE FSImage file to process.\n" + " -fun, --filter-by-user=<userNameFilter>\n" + " Filter user name by <regexp>.\n" + " -h, --help Show this help message and exit.\n" + " -p, --path=<dirs>[,<dirs>...]\n" + " Directory path(s) to start traversing (default: [/]).\n" + " Default: [/]\n" + " -v Turns on verbose output. Use `-vv` for debug output.\n" + " -V, --version Print version information and exit.\n" + "Commands:\n" + " summary Generates an HDFS usage summary (default command if no other\n" + " command specified)\n" + " smallfiles, sf Reports on small file usage\n" + " inode, i Shows INode details\n" + " path, p Lists INode paths\n" + "Runs summary command by default.\n" ); }
protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } static void main(String[] args); }
HdfsFSImageTool { protected static int run(String[] args) { final IExecutionExceptionHandler exceptionHandler = (ex, commandLine, parseResult) -> { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); if (getRootLogger().isInfoEnabled()) { commandLine.getErr().println("Exiting - use option [-v] for more verbose details."); } if (getRootLogger().isDebugEnabled()) { commandLine.getErr().println(commandLine.getColorScheme().errorText(ex.getMessage())); } return commandLine.getExitCodeExceptionMapper() != null ? commandLine.getExitCodeExceptionMapper().getExitCode(ex) : commandLine.getCommandSpec().exitCodeOnExecutionException(); }; CommandLine cmd = new CommandLine(new MainCommand()); cmd.setColorScheme(Help.defaultColorScheme(Help.Ansi.AUTO)); cmd.setOut(new PrintWriter(out)); cmd.setExecutionExceptionHandler(exceptionHandler); cmd.setExecutionStrategy(new RunLast()); return cmd.execute(args); } static void main(String[] args); }
@Test public void testRun() { SummaryReportCommand summaryReportCommand = new SummaryReportCommand(); summaryReportCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { summaryReportCommand.mainCommand.out = printStream; summaryReportCommand.mainCommand.err = summaryReportCommand.mainCommand.out; summaryReportCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); summaryReportCommand.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo("\n" + "HDFS Summary : /\n" + "----------------\n" + "\n" + "#Groups | #Users | #Directories | #Symlinks | #Files | Size [MB] | #Blocks | File Size Buckets \n" + " | | | | | | | 0 B 1 MiB 2 MiB 4 MiB 8 MiB 16 MiB 32 MiB 64 MiB 128 MiB 256 MiB\n" + "----------------------------------------------------------------------------------------------------------------------------------------------------------\n" + " 3 | 3 | 8 | 0 | 11 | 331 | 12 | 0 2 1 2 1 0 2 1 1 1\n" + "\n" + "By group: 3 | #Directories | #SymLinks | #File | Size [MB] | #Blocks | File Size Buckets\n" + " | | | | | | 0 B 1 MiB 2 MiB 4 MiB 8 MiB 16 MiB 32 MiB 64 MiB 128 MiB 256 MiB\n" + "---------------------------------------------------------------------------------------------------------------------------------------------------------\n" + " root | 0 | 0 | 1 | 0 | 1 | 0 1 0 0 0 0 0 0 0 0\n" + " supergroup | 8 | 0 | 8 | 151 | 8 | 0 1 1 2 1 0 1 1 1 0\n" + " nobody | 0 | 0 | 2 | 180 | 3 | 0 0 0 0 0 0 1 0 0 1\n" + "\n" + "By user: 3 | #Directories | #SymLinks | #File | Size [MB] | #Blocks | File Size Buckets\n" + " | | | | | | 0 B 1 MiB 2 MiB 4 MiB 8 MiB 16 MiB 32 MiB 64 MiB 128 MiB 256 MiB\n" + "---------------------------------------------------------------------------------------------------------------------------------------------------------\n" + " root | 0 | 0 | 1 | 0 | 1 | 0 1 0 0 0 0 0 0 0 0\n" + " foo | 0 | 0 | 1 | 160 | 2 | 0 0 0 0 0 0 0 0 0 1\n" + " mm | 8 | 0 | 9 | 171 | 9 | 0 1 1 2 1 0 2 1 1 0\n" ); } }
@Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } @Override void run(); }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } @Override void run(); }
@Test public void testRunWithFilterForUserFoo() { SummaryReportCommand summaryReportCommand = new SummaryReportCommand(); summaryReportCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { summaryReportCommand.mainCommand.out = printStream; summaryReportCommand.mainCommand.err = printStream; summaryReportCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); summaryReportCommand.mainCommand.userNameFilter = "foo"; summaryReportCommand.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo("\n" + "HDFS Summary : /\n" + "----------------\n" + "\n" + "#Groups | #Users | #Directories | #Symlinks | #Files | Size [MB] | #Blocks | File Size Buckets \n" + " | | | | | | | 0 B 1 MiB 2 MiB 4 MiB 8 MiB 16 MiB 32 MiB 64 MiB 128 MiB 256 MiB\n" + "----------------------------------------------------------------------------------------------------------------------------------------------------------\n" + " 3 | 3 | 8 | 0 | 11 | 331 | 12 | 0 2 1 2 1 0 2 1 1 1\n" + "\n" + "By group: 3 | #Directories | #SymLinks | #File | Size [MB] | #Blocks | File Size Buckets\n" + " | | | | | | 0 B 1 MiB 2 MiB 4 MiB 8 MiB 16 MiB 32 MiB 64 MiB 128 MiB 256 MiB\n" + "---------------------------------------------------------------------------------------------------------------------------------------------------------\n" + " root | 0 | 0 | 1 | 0 | 1 | 0 1 0 0 0 0 0 0 0 0\n" + " supergroup | 8 | 0 | 8 | 151 | 8 | 0 1 1 2 1 0 1 1 1 0\n" + " nobody | 0 | 0 | 2 | 180 | 3 | 0 0 0 0 0 0 1 0 0 1\n" + "\n" + "By user: 1 | #Directories | #SymLinks | #File | Size [MB] | #Blocks | File Size Buckets\n" + " | | | | | | 0 B 1 MiB 2 MiB 4 MiB 8 MiB 16 MiB 32 MiB 64 MiB 128 MiB 256 MiB\n" + "---------------------------------------------------------------------------------------------------------------------------------------------------------\n" + " foo | 0 | 0 | 1 | 160 | 2 | 0 0 0 0 0 0 0 0 0 1\n" ); } }
@Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } @Override void run(); }
SummaryReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.info("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting finished [{}ms].", System.currentTimeMillis() - start); doSummary(report); } } } @Override void run(); }
@Test public void testFilter() { final List<UserStats> list = Arrays.asList(new UserStats("foobar"), new UserStats("foo_bar"), new UserStats("fo_obar"), new UserStats("nofoobar")); String userNameFilter = "^foo.*"; List<UserStats> filtered = filterByUserName(list, userNameFilter); assertThat(filtered.size()).isEqualTo(2); assertThat(filtered.get(0).userName).isEqualTo("foobar"); assertThat(filtered.get(1).userName).isEqualTo("foo_bar"); userNameFilter = "foo.*"; filtered = filterByUserName(list, userNameFilter); assertThat(filtered).extracting(userStats -> userStats.userName) .isEqualTo(Arrays.asList("foobar", "foo_bar", "nofoobar")); userNameFilter = ".*bar.*"; filtered = filterByUserName(list, userNameFilter); assertThat(filtered).isEqualTo(list); }
static List<UserStats> filterByUserName(Collection<UserStats> userStats, String userNamePattern) { List<UserStats> filtered = new ArrayList<>(userStats); if (null != userNamePattern && !userNamePattern.isEmpty()) { Pattern pattern = Pattern.compile(userNamePattern); filtered.removeIf(u -> !pattern.matcher(u.userName).find()); } return filtered; }
SummaryReportCommand extends AbstractReportCommand { static List<UserStats> filterByUserName(Collection<UserStats> userStats, String userNamePattern) { List<UserStats> filtered = new ArrayList<>(userStats); if (null != userNamePattern && !userNamePattern.isEmpty()) { Pattern pattern = Pattern.compile(userNamePattern); filtered.removeIf(u -> !pattern.matcher(u.userName).find()); } return filtered; } }
SummaryReportCommand extends AbstractReportCommand { static List<UserStats> filterByUserName(Collection<UserStats> userStats, String userNamePattern) { List<UserStats> filtered = new ArrayList<>(userStats); if (null != userNamePattern && !userNamePattern.isEmpty()) { Pattern pattern = Pattern.compile(userNamePattern); filtered.removeIf(u -> !pattern.matcher(u.userName).find()); } return filtered; } }
SummaryReportCommand extends AbstractReportCommand { static List<UserStats> filterByUserName(Collection<UserStats> userStats, String userNamePattern) { List<UserStats> filtered = new ArrayList<>(userStats); if (null != userNamePattern && !userNamePattern.isEmpty()) { Pattern pattern = Pattern.compile(userNamePattern); filtered.removeIf(u -> !pattern.matcher(u.userName).find()); } return filtered; } @Override void run(); }
SummaryReportCommand extends AbstractReportCommand { static List<UserStats> filterByUserName(Collection<UserStats> userStats, String userNamePattern) { List<UserStats> filtered = new ArrayList<>(userStats); if (null != userNamePattern && !userNamePattern.isEmpty()) { Pattern pattern = Pattern.compile(userNamePattern); filtered.removeIf(u -> !pattern.matcher(u.userName).find()); } return filtered; } @Override void run(); }
@Test public void testRun() { InodeInfoCommand infoCommand = new InodeInfoCommand(); infoCommand.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { infoCommand.mainCommand.out = printStream; infoCommand.mainCommand.err = infoCommand.mainCommand.out; infoCommand.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); infoCommand.inodeIds = new String[]{"/", "/test3", "/test3/test_160MiB.img", "16387"}; infoCommand.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo( "type: DIRECTORY\n" + "id: 16385\n" + "name: \"\"\n" + "directory {\n" + " modificationTime: 1499493618390\n" + " nsQuota: 9223372036854775807\n" + " dsQuota: 18446744073709551615\n" + " permission: 1099511759341\n" + "}\n" + "\n" + "type: DIRECTORY\n" + "id: 16388\n" + "name: \"test3\"\n" + "directory {\n" + " modificationTime: 1497734744891\n" + " nsQuota: 18446744073709551615\n" + " dsQuota: 18446744073709551615\n" + " permission: 1099511759341\n" + "}\n" + "\n" + "type: FILE\n" + "id: 16402\n" + "name: \"test_160MiB.img\"\n" + "file {\n" + " replication: 1\n" + " modificationTime: 1497734744886\n" + " accessTime: 1497734743534\n" + " preferredBlockSize: 134217728\n" + " permission: 5497558401444\n" + " blocks {\n" + " blockId: 1073741834\n" + " genStamp: 1010\n" + " numBytes: 134217728\n" + " }\n" + " blocks {\n" + " blockId: 1073741835\n" + " genStamp: 1011\n" + " numBytes: 33554432\n" + " }\n" + " storagePolicyID: 0\n" + "}\n" + "\n" + "type: DIRECTORY\n" + "id: 16387\n" + "name: \"test2\"\n" + "directory {\n" + " modificationTime: 1497733426149\n" + " nsQuota: 18446744073709551615\n" + " dsQuota: 18446744073709551615\n" + " permission: 1099511759341\n" + "}\n" + "\n" ); } }
@Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String inodeId : inodeIds) { showInodeDetails(fsImageData, inodeId); } } }
InodeInfoCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String inodeId : inodeIds) { showInodeDetails(fsImageData, inodeId); } } } }
InodeInfoCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String inodeId : inodeIds) { showInodeDetails(fsImageData, inodeId); } } } }
InodeInfoCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String inodeId : inodeIds) { showInodeDetails(fsImageData, inodeId); } } } @Override void run(); }
InodeInfoCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String inodeId : inodeIds) { showInodeDetails(fsImageData, inodeId); } } } @Override void run(); }
@Test public void testRun() { SmallFilesReportCommand command = new SmallFilesReportCommand(); command.mainCommand = new HdfsFSImageTool.MainCommand(); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PrintStream printStream = new PrintStream(byteArrayOutputStream)) { command.mainCommand.out = printStream; command.mainCommand.err = command.mainCommand.out; command.mainCommand.fsImageFile = new File("src/test/resources/fsi_small.img"); command.run(); assertThat(byteArrayOutputStream.toString()) .isEqualTo("\n" + "Small files report (< 2 MiB)\n" + "\n" + "Overall small files : 3\n" + "\n" + "#Small files | Path (top 10) \n" + "------------------------------\n" + " 3 | /\n" + " 2 | /test3\n" + " 1 | /test3/foo\n" + "\n" + "Username | #Small files | %\n" + "------------------------------------\n" + "mm | 2 | 66.7%\n" + "root | 1 | 33.3%\n" + "\n" + "Username | Small files hotspots (top 10 count/path)\n" + "---------------------------------------------------\n" + "mm | 2 | /\n" + " | 1 | /test3\n" + "---------------------------------------------------\n" + "root | 1 | /\n" + " | 1 | /test3\n" + " | 1 | /test3/foo\n" + "---------------------------------------------------\n" ); } }
@Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } @Override void run(); }
SmallFilesReportCommand extends AbstractReportCommand { @Override public void run() { final FsImageData fsImageData = loadFsImage(); if (null != fsImageData) { for (String dir : mainCommand.dirs) { log.debug("Visiting {} ...", dir); long start = System.currentTimeMillis(); final Report report = computeReport(fsImageData, dir); log.info("Visiting directory {} finished [{}ms].", dir, System.currentTimeMillis() - start); handleReport(report); } } } @Override void run(); }
@Test public void testStatus_success() throws ApiException { when(statusApi.status()).thenReturn(new FirecloudSystemStatus()); assertThat(service.getFirecloudStatus()).isTrue(); }
@Override public boolean getFirecloudStatus() { try { statusApiProvider.get().status(); } catch (ApiException e) { log.log(Level.WARNING, "Firecloud status check request failed", e); String response = e.getResponseBody(); try { JSONObject errorBody = new JSONObject(response); JSONObject subSystemStatus = errorBody.getJSONObject(STATUS_SUBSYSTEMS_KEY); if (subSystemStatus != null) { return systemOkay(subSystemStatus, THURLOE_STATUS_NAME) && systemOkay(subSystemStatus, SAM_STATUS_NAME) && systemOkay(subSystemStatus, RAWLS_STATUS_NAME) && systemOkay(subSystemStatus, GOOGLE_BUCKETS_STATUS_NAME); } } catch (JSONException ignored) { } return false; } return true; }
FireCloudServiceImpl implements FireCloudService { @Override public boolean getFirecloudStatus() { try { statusApiProvider.get().status(); } catch (ApiException e) { log.log(Level.WARNING, "Firecloud status check request failed", e); String response = e.getResponseBody(); try { JSONObject errorBody = new JSONObject(response); JSONObject subSystemStatus = errorBody.getJSONObject(STATUS_SUBSYSTEMS_KEY); if (subSystemStatus != null) { return systemOkay(subSystemStatus, THURLOE_STATUS_NAME) && systemOkay(subSystemStatus, SAM_STATUS_NAME) && systemOkay(subSystemStatus, RAWLS_STATUS_NAME) && systemOkay(subSystemStatus, GOOGLE_BUCKETS_STATUS_NAME); } } catch (JSONException ignored) { } return false; } return true; } }
FireCloudServiceImpl implements FireCloudService { @Override public boolean getFirecloudStatus() { try { statusApiProvider.get().status(); } catch (ApiException e) { log.log(Level.WARNING, "Firecloud status check request failed", e); String response = e.getResponseBody(); try { JSONObject errorBody = new JSONObject(response); JSONObject subSystemStatus = errorBody.getJSONObject(STATUS_SUBSYSTEMS_KEY); if (subSystemStatus != null) { return systemOkay(subSystemStatus, THURLOE_STATUS_NAME) && systemOkay(subSystemStatus, SAM_STATUS_NAME) && systemOkay(subSystemStatus, RAWLS_STATUS_NAME) && systemOkay(subSystemStatus, GOOGLE_BUCKETS_STATUS_NAME); } } catch (JSONException ignored) { } return false; } return true; } @Autowired FireCloudServiceImpl( Provider<WorkbenchConfig> configProvider, Provider<ProfileApi> profileApiProvider, Provider<BillingApi> billingApiProvider, Provider<GroupsApi> groupsApiProvider, Provider<NihApi> nihApiProvider, @Qualifier(FireCloudConfig.END_USER_WORKSPACE_API) Provider<WorkspacesApi> endUserWorkspacesApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_WORKSPACE_API) Provider<WorkspacesApi> serviceAccountWorkspaceApiProvider, Provider<StatusApi> statusApiProvider, @Qualifier(FireCloudConfig.END_USER_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> endUserStaticNotebooksApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> serviceAccountStaticNotebooksApiProvider, FirecloudRetryHandler retryHandler, @Qualifier(Constants.FIRECLOUD_ADMIN_CREDS) Provider<ServiceAccountCredentials> fcAdminCredsProvider, IamCredentialsClient iamCredentialsClient, HttpTransport httpTransport); }
FireCloudServiceImpl implements FireCloudService { @Override public boolean getFirecloudStatus() { try { statusApiProvider.get().status(); } catch (ApiException e) { log.log(Level.WARNING, "Firecloud status check request failed", e); String response = e.getResponseBody(); try { JSONObject errorBody = new JSONObject(response); JSONObject subSystemStatus = errorBody.getJSONObject(STATUS_SUBSYSTEMS_KEY); if (subSystemStatus != null) { return systemOkay(subSystemStatus, THURLOE_STATUS_NAME) && systemOkay(subSystemStatus, SAM_STATUS_NAME) && systemOkay(subSystemStatus, RAWLS_STATUS_NAME) && systemOkay(subSystemStatus, GOOGLE_BUCKETS_STATUS_NAME); } } catch (JSONException ignored) { } return false; } return true; } @Autowired FireCloudServiceImpl( Provider<WorkbenchConfig> configProvider, Provider<ProfileApi> profileApiProvider, Provider<BillingApi> billingApiProvider, Provider<GroupsApi> groupsApiProvider, Provider<NihApi> nihApiProvider, @Qualifier(FireCloudConfig.END_USER_WORKSPACE_API) Provider<WorkspacesApi> endUserWorkspacesApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_WORKSPACE_API) Provider<WorkspacesApi> serviceAccountWorkspaceApiProvider, Provider<StatusApi> statusApiProvider, @Qualifier(FireCloudConfig.END_USER_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> endUserStaticNotebooksApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> serviceAccountStaticNotebooksApiProvider, FirecloudRetryHandler retryHandler, @Qualifier(Constants.FIRECLOUD_ADMIN_CREDS) Provider<ServiceAccountCredentials> fcAdminCredsProvider, IamCredentialsClient iamCredentialsClient, HttpTransport httpTransport); ApiClient getApiClientWithImpersonation(String userEmail); @Override @VisibleForTesting String getApiBasePath(); @Override boolean getFirecloudStatus(); @Override FirecloudMe getMe(); @Override void registerUser(String contactEmail, String firstName, String lastName); @Override void createAllOfUsBillingProject(String projectName); @Override void deleteBillingProject(String billingProject); @Override FirecloudBillingProjectStatus getBillingProjectStatus(String projectName); @Override void addOwnerToBillingProject(String ownerEmail, String projectName); @Override void removeOwnerFromBillingProject( String ownerEmailToRemove, String projectName, Optional<String> callerAccessToken); @Override FirecloudWorkspace createWorkspace(String projectName, String workspaceName); @Override FirecloudWorkspace cloneWorkspace( String fromProject, String fromName, String toProject, String toName); @Override List<FirecloudBillingProjectMembership> getBillingProjectMemberships(); @Override FirecloudWorkspaceACLUpdateResponseList updateWorkspaceACL( String projectName, String workspaceName, List<FirecloudWorkspaceACLUpdate> aclUpdates); @Override FirecloudWorkspaceACL getWorkspaceAclAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspaceAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspace(String projectName, String workspaceName); @Override Optional<FirecloudWorkspaceResponse> getWorkspace(DbWorkspace dbWorkspace); @Override List<FirecloudWorkspaceResponse> getWorkspaces(); @Override void deleteWorkspace(String projectName, String workspaceName); @Override FirecloudManagedGroupWithMembers getGroup(String groupName); @Override FirecloudManagedGroupWithMembers createGroup(String groupName); @Override void addUserToGroup(String email, String groupName); @Override void removeUserFromGroup(String email, String groupName); @Override boolean isUserMemberOfGroup(String email, String groupName); @Override String staticNotebooksConvert(byte[] notebook); @Override String staticNotebooksConvertAsService(byte[] notebook); @Override FirecloudNihStatus getNihStatus(); @Override void postNihCallback(FirecloudJWTWrapper wrapper); }
FireCloudServiceImpl implements FireCloudService { @Override public boolean getFirecloudStatus() { try { statusApiProvider.get().status(); } catch (ApiException e) { log.log(Level.WARNING, "Firecloud status check request failed", e); String response = e.getResponseBody(); try { JSONObject errorBody = new JSONObject(response); JSONObject subSystemStatus = errorBody.getJSONObject(STATUS_SUBSYSTEMS_KEY); if (subSystemStatus != null) { return systemOkay(subSystemStatus, THURLOE_STATUS_NAME) && systemOkay(subSystemStatus, SAM_STATUS_NAME) && systemOkay(subSystemStatus, RAWLS_STATUS_NAME) && systemOkay(subSystemStatus, GOOGLE_BUCKETS_STATUS_NAME); } } catch (JSONException ignored) { } return false; } return true; } @Autowired FireCloudServiceImpl( Provider<WorkbenchConfig> configProvider, Provider<ProfileApi> profileApiProvider, Provider<BillingApi> billingApiProvider, Provider<GroupsApi> groupsApiProvider, Provider<NihApi> nihApiProvider, @Qualifier(FireCloudConfig.END_USER_WORKSPACE_API) Provider<WorkspacesApi> endUserWorkspacesApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_WORKSPACE_API) Provider<WorkspacesApi> serviceAccountWorkspaceApiProvider, Provider<StatusApi> statusApiProvider, @Qualifier(FireCloudConfig.END_USER_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> endUserStaticNotebooksApiProvider, @Qualifier(FireCloudConfig.SERVICE_ACCOUNT_STATIC_NOTEBOOKS_API) Provider<StaticNotebooksApi> serviceAccountStaticNotebooksApiProvider, FirecloudRetryHandler retryHandler, @Qualifier(Constants.FIRECLOUD_ADMIN_CREDS) Provider<ServiceAccountCredentials> fcAdminCredsProvider, IamCredentialsClient iamCredentialsClient, HttpTransport httpTransport); ApiClient getApiClientWithImpersonation(String userEmail); @Override @VisibleForTesting String getApiBasePath(); @Override boolean getFirecloudStatus(); @Override FirecloudMe getMe(); @Override void registerUser(String contactEmail, String firstName, String lastName); @Override void createAllOfUsBillingProject(String projectName); @Override void deleteBillingProject(String billingProject); @Override FirecloudBillingProjectStatus getBillingProjectStatus(String projectName); @Override void addOwnerToBillingProject(String ownerEmail, String projectName); @Override void removeOwnerFromBillingProject( String ownerEmailToRemove, String projectName, Optional<String> callerAccessToken); @Override FirecloudWorkspace createWorkspace(String projectName, String workspaceName); @Override FirecloudWorkspace cloneWorkspace( String fromProject, String fromName, String toProject, String toName); @Override List<FirecloudBillingProjectMembership> getBillingProjectMemberships(); @Override FirecloudWorkspaceACLUpdateResponseList updateWorkspaceACL( String projectName, String workspaceName, List<FirecloudWorkspaceACLUpdate> aclUpdates); @Override FirecloudWorkspaceACL getWorkspaceAclAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspaceAsService(String projectName, String workspaceName); @Override FirecloudWorkspaceResponse getWorkspace(String projectName, String workspaceName); @Override Optional<FirecloudWorkspaceResponse> getWorkspace(DbWorkspace dbWorkspace); @Override List<FirecloudWorkspaceResponse> getWorkspaces(); @Override void deleteWorkspace(String projectName, String workspaceName); @Override FirecloudManagedGroupWithMembers getGroup(String groupName); @Override FirecloudManagedGroupWithMembers createGroup(String groupName); @Override void addUserToGroup(String email, String groupName); @Override void removeUserFromGroup(String email, String groupName); @Override boolean isUserMemberOfGroup(String email, String groupName); @Override String staticNotebooksConvert(byte[] notebook); @Override String staticNotebooksConvertAsService(byte[] notebook); @Override FirecloudNihStatus getNihStatus(); @Override void postNihCallback(FirecloudJWTWrapper wrapper); static final List<String> FIRECLOUD_API_OAUTH_SCOPES; static final List<String> FIRECLOUD_WORKSPACE_REQUIRED_FIELDS; }
@Test public void testLocalize_playgroundMode() throws org.pmiops.workbench.notebooks.ApiException { RuntimeLocalizeRequest req = new RuntimeLocalizeRequest() .notebookNames(ImmutableList.of("foo.ipynb")) .playgroundMode(true); stubGetWorkspace(WORKSPACE_NS, WORKSPACE_ID, LOGGED_IN_USER_EMAIL); RuntimeLocalizeResponse resp = runtimeController.localize(BILLING_PROJECT_ID, req).getBody(); assertThat(resp.getRuntimeLocalDirectory()).isEqualTo("workspaces_playground/myfirstworkspace"); verify(proxyApi) .welderLocalize(eq(BILLING_PROJECT_ID), eq(getRuntimeName()), welderReqCaptor.capture()); Localize welderReq = welderReqCaptor.getValue(); assertThat( welderReq.getEntries().stream() .map(e -> e.getLocalDestinationPath()) .collect(Collectors.toList())) .containsExactly( "workspaces_playground/myfirstworkspace/foo.ipynb", "workspaces_playground/myfirstworkspace/.all_of_us_config.json", "workspaces/myfirstworkspace/.all_of_us_config.json"); assertThat( welderReq.getEntries().stream() .filter( e -> e.getLocalDestinationPath() .equals("workspaces_playground/myfirstworkspace/foo.ipynb") && e.getSourceUri().equals("gs: .count()) .isAtLeast(1L); }
@Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void testLocalize_differentNamespace() throws org.pmiops.workbench.notebooks.ApiException { RuntimeLocalizeRequest req = new RuntimeLocalizeRequest() .notebookNames(ImmutableList.of("foo.ipynb")) .playgroundMode(false); stubGetWorkspace(WORKSPACE_NS, WORKSPACE_ID, LOGGED_IN_USER_EMAIL); stubGetWorkspace("other-proj", "myotherworkspace", LOGGED_IN_USER_EMAIL); RuntimeLocalizeResponse resp = runtimeController.localize("other-proj", req).getBody(); verify(proxyApi) .welderLocalize(eq("other-proj"), eq(getRuntimeName()), welderReqCaptor.capture()); Localize welderReq = welderReqCaptor.getValue(); assertThat( welderReq.getEntries().stream() .map(e -> e.getLocalDestinationPath()) .collect(Collectors.toList())) .containsExactly( "workspaces/myotherworkspace/foo.ipynb", "workspaces/myotherworkspace/.all_of_us_config.json", "workspaces_playground/myotherworkspace/.all_of_us_config.json"); assertThat( welderReq.getEntries().stream() .filter( e -> e.getLocalDestinationPath().equals("workspaces/myotherworkspace/foo.ipynb") && e.getSourceUri().equals("gs: .count()) .isAtLeast(1L); assertThat(resp.getRuntimeLocalDirectory()).isEqualTo("workspaces/myotherworkspace"); JSONObject aouJson = dataUriToJson( welderReq.getEntries().stream() .filter( e -> e.getLocalDestinationPath() .equals("workspaces/myotherworkspace/.all_of_us_config.json")) .findFirst() .get() .getSourceUri()); assertThat(aouJson.getString("BILLING_CLOUD_PROJECT")).isEqualTo("other-proj"); }
@Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void testLocalize_noNotebooks() throws org.pmiops.workbench.notebooks.ApiException { RuntimeLocalizeRequest req = new RuntimeLocalizeRequest(); req.setPlaygroundMode(false); stubGetWorkspace(WORKSPACE_NS, WORKSPACE_ID, LOGGED_IN_USER_EMAIL); RuntimeLocalizeResponse resp = runtimeController.localize(BILLING_PROJECT_ID, req).getBody(); verify(proxyApi) .welderLocalize(eq(BILLING_PROJECT_ID), eq(getRuntimeName()), welderReqCaptor.capture()); Localize welderReq = welderReqCaptor.getValue(); assertThat( welderReq.getEntries().stream() .map(e -> e.getLocalDestinationPath()) .collect(Collectors.toList())) .containsExactly( "workspaces_playground/myfirstworkspace/.all_of_us_config.json", "workspaces/myfirstworkspace/.all_of_us_config.json"); assertThat(resp.getRuntimeLocalDirectory()).isEqualTo("workspaces/myfirstworkspace"); }
@Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void getRuntime_validateActiveBilling() { doThrow(ForbiddenException.class) .when(mockWorkspaceService) .validateActiveBilling(WORKSPACE_NS, WORKSPACE_ID); assertThrows(ForbiddenException.class, () -> runtimeController.getRuntime(WORKSPACE_NS)); }
@Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void getRuntime_validateActiveBilling_checkAccessFirst() { doThrow(ForbiddenException.class) .when(mockWorkspaceService) .enforceWorkspaceAccessLevelAndRegisteredAuthDomain( WORKSPACE_NS, WORKSPACE_ID, WorkspaceAccessLevel.WRITER); assertThrows(ForbiddenException.class, () -> runtimeController.getRuntime(WORKSPACE_NS)); verify(mockWorkspaceService, never()).validateActiveBilling(anyString(), anyString()); }
@Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<Runtime> getRuntime(String workspaceNamespace) { String firecloudWorkspaceName = lookupWorkspace(workspaceNamespace).getFirecloudName(); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( workspaceNamespace, firecloudWorkspaceName, WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling(workspaceNamespace, firecloudWorkspaceName); try { return ResponseEntity.ok( leonardoMapper.toApiRuntime( leonardoNotebooksClient.getRuntime( workspaceNamespace, userProvider.get().getRuntimeName()))); } catch (NotFoundException e) { if (!workbenchConfigProvider.get().featureFlags.enableCustomRuntimes) { throw e; } return ResponseEntity.ok(getOverrideFromListRuntimes(workspaceNamespace)); } } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void localize_validateActiveBilling() { doThrow(ForbiddenException.class) .when(mockWorkspaceService) .validateActiveBilling(WORKSPACE_NS, WORKSPACE_ID); RuntimeLocalizeRequest req = new RuntimeLocalizeRequest(); assertThrows(ForbiddenException.class, () -> runtimeController.localize(WORKSPACE_NS, req)); }
@Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void localize_validateActiveBilling_checkAccessFirst() { doThrow(ForbiddenException.class) .when(mockWorkspaceService) .enforceWorkspaceAccessLevelAndRegisteredAuthDomain( WORKSPACE_NS, WORKSPACE_ID, WorkspaceAccessLevel.WRITER); RuntimeLocalizeRequest req = new RuntimeLocalizeRequest(); assertThrows(ForbiddenException.class, () -> runtimeController.localize(WORKSPACE_NS, req)); verify(mockWorkspaceService, never()).validateActiveBilling(anyString(), anyString()); }
@Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
RuntimeController implements RuntimeApiDelegate { @Override public ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body) { DbWorkspace dbWorkspace = lookupWorkspace(workspaceNamespace); workspaceService.enforceWorkspaceAccessLevelAndRegisteredAuthDomain( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName(), WorkspaceAccessLevel.WRITER); workspaceService.validateActiveBilling( dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()); final FirecloudWorkspace firecloudWorkspace; try { firecloudWorkspace = fireCloudService .getWorkspace(dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName()) .getWorkspace(); } catch (NotFoundException e) { throw new NotFoundException( String.format( "workspace %s/%s not found or not accessible", dbWorkspace.getWorkspaceNamespace(), dbWorkspace.getFirecloudName())); } DbCdrVersion cdrVersion = dbWorkspace.getCdrVersion(); String gcsNotebooksDir = "gs: long workspaceId = dbWorkspace.getWorkspaceId(); body.getNotebookNames() .forEach( notebookName -> userRecentResourceService.updateNotebookEntry( workspaceId, userProvider.get().getUserId(), gcsNotebooksDir + "/" + notebookName)); String workspacePath = dbWorkspace.getFirecloudName(); String editDir = "workspaces/" + workspacePath; String playgroundDir = "workspaces_playground/" + workspacePath; String targetDir = body.getPlaygroundMode() ? playgroundDir : editDir; leonardoNotebooksClient.createStorageLink( workspaceNamespace, userProvider.get().getRuntimeName(), new StorageLink() .cloudStorageDirectory(gcsNotebooksDir) .localBaseDirectory(editDir) .localSafeModeBaseDirectory(playgroundDir) .pattern(DELOC_PATTERN)); Map<String, String> localizeMap = new HashMap<>(); String aouConfigUri = aouConfigDataUri(firecloudWorkspace, cdrVersion, workspaceNamespace); localizeMap.put(editDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); localizeMap.put(playgroundDir + "/" + AOU_CONFIG_FILENAME, aouConfigUri); if (body.getNotebookNames() != null) { localizeMap.putAll( body.getNotebookNames().stream() .collect( Collectors.toMap( name -> targetDir + "/" + name, name -> gcsNotebooksDir + "/" + name))); } log.info(localizeMap.toString()); leonardoNotebooksClient.localize( workspaceNamespace, userProvider.get().getRuntimeName(), localizeMap); return ResponseEntity.ok(new RuntimeLocalizeResponse().runtimeLocalDirectory(targetDir)); } @Autowired RuntimeController( LeonardoRuntimeAuditor leonardoRuntimeAuditor, LeonardoNotebooksClient leonardoNotebooksClient, Provider<DbUser> userProvider, WorkspaceService workspaceService, FireCloudService fireCloudService, Provider<WorkbenchConfig> workbenchConfigProvider, UserService userService, UserRecentResourceService userRecentResourceService, UserDao userDao, LeonardoMapper leonardoMapper, Clock clock); @Override @AuthorityRequired(Authority.SECURITY_ADMIN) ResponseEntity<List<ListRuntimeResponse>> deleteRuntimesInProject( String billingProjectId, ListRuntimeDeleteRequest req); @Override ResponseEntity<Runtime> getRuntime(String workspaceNamespace); @Override ResponseEntity<EmptyResponse> createRuntime(String workspaceNamespace, Runtime runtime); @Override ResponseEntity<EmptyResponse> deleteRuntime(String workspaceNamespace); @Override ResponseEntity<RuntimeLocalizeResponse> localize( String workspaceNamespace, RuntimeLocalizeRequest body); @Override @AuthorityRequired({Authority.DEVELOPER}) ResponseEntity<EmptyResponse> updateClusterConfig(UpdateClusterConfigRequest body); }
@Test public void findDomainInfos() { cbCriteriaDao.save( DbCriteria.builder() .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD9CM.toString()) .addCount(0L) .addHierarchy(true) .addStandard(false) .addParentId(0) .addFullText("term*[CONDITION_rank1]") .build()); DbDomainInfo dbDomainInfo = domainInfoDao.save( new DbDomainInfo() .conceptId(1L) .domain((short) 0) .domainId("CONDITION") .name("Conditions") .description("descr") .allConceptCount(0) .standardConceptCount(0) .participantCount(1000)); DomainInfo domainInfo = controller.findDomainInfos(1L, "term").getBody().getItems().get(0); assertEquals(domainInfo.getName(), dbDomainInfo.getName()); assertEquals(domainInfo.getDescription(), dbDomainInfo.getDescription()); assertEquals(domainInfo.getParticipantCount().longValue(), dbDomainInfo.getParticipantCount()); assertEquals(domainInfo.getAllConceptCount().longValue(), 1); assertEquals(domainInfo.getStandardConceptCount().longValue(), 0); }
@Override public ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); validateTerm(term); return ResponseEntity.ok( new DomainInfoResponse().items(cohortBuilderService.findDomainInfos(term))); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); validateTerm(term); return ResponseEntity.ok( new DomainInfoResponse().items(cohortBuilderService.findDomainInfos(term))); } }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); validateTerm(term); return ResponseEntity.ok( new DomainInfoResponse().items(cohortBuilderService.findDomainInfos(term))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); validateTerm(term); return ResponseEntity.ok( new DomainInfoResponse().items(cohortBuilderService.findDomainInfos(term))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete( Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue( Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm( Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions( Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId( Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo( Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); validateTerm(term); return ResponseEntity.ok( new DomainInfoResponse().items(cohortBuilderService.findDomainInfos(term))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete( Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue( Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm( Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions( Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId( Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo( Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }
@Test public void findSurveyModules() { DbCriteria surveyCriteria = cbCriteriaDao.save( DbCriteria.builder() .addDomainId(DomainType.SURVEY.toString()) .addType(CriteriaType.PPI.toString()) .addSubtype(CriteriaSubType.QUESTION.toString()) .addCount(0L) .addHierarchy(true) .addStandard(false) .addParentId(0) .addConceptId("1") .addName("The Basics") .build()); cbCriteriaDao.save( DbCriteria.builder() .addDomainId(DomainType.SURVEY.toString()) .addType(CriteriaType.PPI.toString()) .addSubtype(CriteriaSubType.ANSWER.toString()) .addCount(0L) .addHierarchy(true) .addStandard(false) .addParentId(0) .addConceptId("1") .addFullText("term*[SURVEY_rank1]") .addPath(String.valueOf(surveyCriteria.getId())) .build()); DbSurveyModule dbSurveyModule = surveyModuleDao.save( new DbSurveyModule() .conceptId(1L) .name("The Basics") .description("descr") .questionCount(1) .participantCount(1000)); SurveyModule surveyModule = controller.findSurveyModules(1L, "term").getBody().getItems().get(0); assertEquals(surveyModule.getName(), dbSurveyModule.getName()); assertEquals(surveyModule.getDescription(), dbSurveyModule.getDescription()); assertEquals( surveyModule.getParticipantCount().longValue(), dbSurveyModule.getParticipantCount()); assertEquals(surveyModule.getQuestionCount().longValue(), 1); }
@Override public ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); return ResponseEntity.ok( new SurveysResponse().items(cohortBuilderService.findSurveyModules(term))); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); return ResponseEntity.ok( new SurveysResponse().items(cohortBuilderService.findSurveyModules(term))); } }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); return ResponseEntity.ok( new SurveysResponse().items(cohortBuilderService.findSurveyModules(term))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); return ResponseEntity.ok( new SurveysResponse().items(cohortBuilderService.findSurveyModules(term))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete( Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue( Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm( Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions( Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId( Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo( Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term) { cdrVersionService.setCdrVersion(cdrVersionId); return ResponseEntity.ok( new SurveysResponse().items(cohortBuilderService.findSurveyModules(term))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete( Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue( Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm( Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions( Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId( Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo( Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }
@Test public void findCriteriaBy() { DbCriteria icd9CriteriaParent = DbCriteria.builder() .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD9CM.toString()) .addCount(0L) .addHierarchy(true) .addStandard(false) .addParentId(0L) .build(); cbCriteriaDao.save(icd9CriteriaParent); DbCriteria icd9Criteria = DbCriteria.builder() .addDomainId(DomainType.CONDITION.toString()) .addType(CriteriaType.ICD9CM.toString()) .addCount(0L) .addHierarchy(true) .addStandard(false) .addParentId(icd9CriteriaParent.getId()) .build(); cbCriteriaDao.save(icd9Criteria); assertEquals( createResponseCriteria(icd9CriteriaParent), controller .findCriteriaBy( 1L, DomainType.CONDITION.toString(), CriteriaType.ICD9CM.toString(), false, 0L) .getBody() .getItems() .get(0)); assertEquals( createResponseCriteria(icd9Criteria), controller .findCriteriaBy( 1L, DomainType.CONDITION.toString(), CriteriaType.ICD9CM.toString(), false, icd9CriteriaParent.getId()) .getBody() .getItems() .get(0)); }
@Override public ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId) { cdrVersionService.setCdrVersion(cdrVersionId); validateDomain(domain); validateType(type); return ResponseEntity.ok( new CriteriaListResponse() .items(cohortBuilderService.findCriteriaBy(domain, type, standard, parentId))); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId) { cdrVersionService.setCdrVersion(cdrVersionId); validateDomain(domain); validateType(type); return ResponseEntity.ok( new CriteriaListResponse() .items(cohortBuilderService.findCriteriaBy(domain, type, standard, parentId))); } }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId) { cdrVersionService.setCdrVersion(cdrVersionId); validateDomain(domain); validateType(type); return ResponseEntity.ok( new CriteriaListResponse() .items(cohortBuilderService.findCriteriaBy(domain, type, standard, parentId))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId) { cdrVersionService.setCdrVersion(cdrVersionId); validateDomain(domain); validateType(type); return ResponseEntity.ok( new CriteriaListResponse() .items(cohortBuilderService.findCriteriaBy(domain, type, standard, parentId))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete( Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue( Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm( Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions( Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId( Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo( Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }
CohortBuilderController implements CohortBuilderApiDelegate { @Override public ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId) { cdrVersionService.setCdrVersion(cdrVersionId); validateDomain(domain); validateType(type); return ResponseEntity.ok( new CriteriaListResponse() .items(cohortBuilderService.findCriteriaBy(domain, type, standard, parentId))); } @Autowired CohortBuilderController( CdrVersionService cdrVersionService, ElasticSearchService elasticSearchService, Provider<WorkbenchConfig> configProvider, CohortBuilderService cohortBuilderService); @Override ResponseEntity<CriteriaListResponse> findCriteriaAutoComplete( Long cdrVersionId, String domain, String term, String type, Boolean standard, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugBrandOrIngredientByValue( Long cdrVersionId, String value, Integer limit); @Override ResponseEntity<CriteriaListResponse> findDrugIngredientByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<AgeTypeCountListResponse> findAgeTypeCounts(Long cdrVersionId); @Override ResponseEntity<Long> countParticipants(Long cdrVersionId, SearchRequest request); @Override ResponseEntity<CriteriaListWithCountResponse> findCriteriaByDomainAndSearchTerm( Long cdrVersionId, String domain, String term, Integer limit); @Override ResponseEntity<CriteriaMenuOptionsListResponse> findCriteriaMenuOptions( Long cdrVersionId); @Override ResponseEntity<DataFiltersResponse> findDataFilters(Long cdrVersionId); @Override ResponseEntity<CriteriaListResponse> findStandardCriteriaByDomainAndConceptId( Long cdrVersionId, String domain, Long conceptId); @Override ResponseEntity<DemoChartInfoListResponse> findDemoChartInfo( Long cdrVersionId, String genderOrSex, String age, SearchRequest request); @Override ResponseEntity<DomainInfoResponse> findDomainInfos(Long cdrVersionId, String term); @Override ResponseEntity<CriteriaAttributeListResponse> findCriteriaAttributeByConceptId( Long cdrVersionId, Long conceptId); @Override ResponseEntity<CriteriaListResponse> findCriteriaBy( Long cdrVersionId, String domain, String type, Boolean standard, Long parentId); @Override ResponseEntity<ParticipantDemographics> findParticipantDemographics(Long cdrVersionId); @Override ResponseEntity<SurveysResponse> findSurveyModules(Long cdrVersionId, String term); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId); @Override ResponseEntity<SurveyVersionListResponse> findSurveyVersionByQuestionConceptIdAndAnswerConceptId( Long cdrVersionId, Long surveyConceptId, Long questionConceptId, Long answerConceptId); }