@Test public void verifyAuthenticateSuccess() throws Exception { assertNotEquals(handler.size(), 0); getEntries().forEach(entry -> { final String username = entry.getAttribute("sAMAccountName").getStringValue(); final String psw = entry.getAttribute("userPassword").getStringValue(); this.handler.forEach(Unchecked.consumer(h -> { final HandlerResult result = h.authenticate(new UsernamePasswordCredential(username, psw)); assertNotNull(result.getPrincipal()); assertEquals(username, result.getPrincipal().getId()); assertEquals( entry.getAttribute("displayName").getStringValue(), result.getPrincipal().getAttributes().get("displayName")); assertEquals( entry.getAttribute("mail").getStringValue(), result.getPrincipal().getAttributes().get("mail")); })); }); }
@ConditionalOnMissingBean(name = "jsonAttributeRepositories") @Bean @RefreshScope public List<IPersonAttributeDao> jsonAttributeRepositories() { final List<IPersonAttributeDao> list = new ArrayList<>(); casProperties.getAuthn().getAttributeRepository().getJson().forEach(Unchecked.consumer(json -> { final Resource r = json.getConfig().getLocation(); if (r != null) { final JsonBackedComplexStubPersonAttributeDao dao = new JsonBackedComplexStubPersonAttributeDao(r); dao.setOrder(json.getOrder()); dao.init(); LOGGER.debug("Configured JSON attribute sources from [{}]", r); list.add(dao); } })); return list; }
public User getUserByEmail(String email) { HttpUrl route = HttpUrl.parse(host + "/users") .newBuilder() .addPathSegment(email) .build(); Request request = new Request.Builder().url(route).get().build(); return Unchecked.supplier(() -> { try (Response response = client.newCall(request).execute()) { // The user exists if (response.isSuccessful()) { User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef()); return user; } /* * 404 Not Found - Either return null or throw your own exception. * We prefer nulls. */ if (response.code() == StatusCodes.NOT_FOUND) { return null; } throw HttpClient.unknownException(response); } }).get(); }
public boolean deleteUserByEmail(String email) { HttpUrl route = HttpUrl.parse(host + "/users") .newBuilder() .addPathSegment(email) .build(); Request request = new Request.Builder().url(route).delete().build(); return Unchecked.booleanSupplier(() -> { try (Response response = client.newCall(request).execute()) { if (response.code() == StatusCodes.NO_CONTENT) { return true; } // Maybe you would throw an exception here? We don't feel the need to. if (response.code() == StatusCodes.NOT_FOUND) { return false; } throw HttpClient.unknownException(response); } }).getAsBoolean(); }
public User createUser(User inputUser) { HttpUrl route = HttpUrl.parse(host + "/users"); Request request = new Request.Builder() .url(route) .post(RequestBodies.jsonObj(inputUser)) .build(); return Unchecked.supplier(() -> { try (Response response = client.newCall(request).execute()) { if (response.code() == StatusCodes.CREATED) { User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef()); return user; } if (response.code() == StatusCodes.BAD_REQUEST) { return null; } throw HttpClient.unknownException(response); } }).get(); }
public User updateUser(User inputUser) { HttpUrl route = HttpUrl.parse(host + "/users"); Request request = new Request.Builder() .url(route) .put(RequestBodies.jsonObj(inputUser)) .build(); return Unchecked.supplier(() -> { try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { User user = Json.serializer().fromInputStream(response.body().byteStream(), User.typeRef()); return user; } if (response.code() == StatusCodes.NOT_FOUND) { return null; } throw HttpClient.unknownException(response); } }).get(); }
static public List<SalonQuestion> getSalonQuestions(long docID, SalonDB salonDB) throws SQLException { String sql = "SELECT * from question where document_id = ?"; try (PreparedStatement stmt = salonDB.prep(sql)) { stmt.setLong(1, docID); Seq<SalonQuestion> docs = SQL.seq(stmt, Unchecked.function(rs -> { SalonQuestion salonq = new SalonQuestion(); salonq.questionID = rs.getLong("question_id"); salonq.assignmentID = rs.getLong("assignment_id"); salonq.questionText = rs.getString("question_text"); salonq.documentID = rs.getLong("document_id"); salonq.questionTitle = rs.getString("question_title"); salonq.createdDate = rs.getTimestamp("created_date"); salonq.userID = rs.getLong("user_id"); return salonq; } )); return docs.toList(); } }
static public SalonInfo getSalonInfo(int salonID, SalonDB salonDB) throws SQLException { String sql = "SELECT * from salons where salon_id=?"; SalonInfo salon = new SalonInfo(); try (PreparedStatement stmt = salonDB.prep(sql)) { stmt.setLong(1, salonID); SQL.seq(stmt, Unchecked.function(rs -> { salon.name = rs.getString("salon_name"); salon.salonID = salonID; salon.ownerID = rs.getInt("owner_id"); salon.mode = rs.getString("salon_mode"); salon.description = rs.getString("salon_description"); salon.created = rs.getTimestamp("salon_created"); salon.salonType = rs.getString("salon_type"); return salon; } )); } catch (Exception e) { throw e; } return salon; }
/** * Returns a single ProsoloUser object * * @param id the id of the followed entity * @return an optional ProsoloFollowedEntity that is empty if the id did not exist * @throws SQLException */ public Optional<ProsoloFollowedEntity> getProsoloFollowedEntity(Long id) throws SQLException { if(id==null){ return Optional.empty(); } Optional<ProsoloFollowedEntity> pFollowedEntity = null; try (Connection c = getConnection()) { String sql = "SELECT * from "+TableConstants.FOLLOWEDENTITY+" where id=?"; try (PreparedStatement stmt = c.prepareStatement(sql)) { stmt.setLong(1, id); pFollowedEntity = SQL.seq(stmt, Unchecked.function(rs -> new ProsoloFollowedEntity( rs.getString("dtype"), rs.getLong("id"), rs.getTimestamp("created"), rs.getBoolean("deleted"), rs.getString("dc_description"), rs.getString("title"), rs.getTimestamp("started_following"), rs.getLong("user"), rs.getLong("followed_node"), rs.getLong("followed_user") ))).findFirst(); } } return pFollowedEntity; }
/** * Returns the edX username for a given ProSolo user id. * * @param id the prosolo user id * @return an Optional containing the edX username of the prosolo user with the provided id, if a mapping exists * @throws SQLException */ public Optional<String> mapProsoloUserIdToedXUsername(Long id) throws SQLException { if(id==null){ return Optional.empty(); } Optional<String> edXid=null; try (Connection c = getConnection()) { String sql = "SELECT validated_id from "+TableConstants.OPENIDACCOUNT+" where user=? and validated_id is not null"; try (PreparedStatement stmt = c.prepareStatement(sql)) { stmt.setLong(1, id); edXid = SQL.seq(stmt, Unchecked.function(rs -> rs.getString("validated_id"))).findFirst(); } } if(!edXid.isPresent()){ return edXid; }else{ return Optional.of(edXid.get().substring(edXid.get().lastIndexOf("/")+1)); } }
/** * Saves a PreferenceData instance in two files for user and item preferences, respectively. The format of the user preferences stream consists on one list per line, starting with the identifier of the user followed by the identifiers of the items related to that. The item preferences stream follows the same format by swapping the roles of users and items. * * @param prefData preferences * @param uo stream of user preferences * @param io stream of user preferences */ public void write(FastPreferenceData<?, ?> prefData, OutputStream uo, OutputStream io) { BiConsumer<FastPreferenceData<?, ?>, OutputStream> saver = Unchecked.biConsumer((prefs, os) -> { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os))) { prefs.getUidxWithPreferences().forEach(Unchecked.intConsumer(uidx -> { String a = prefs.getUidxPreferences(uidx) .mapToInt(IdxPref::v1) .sorted() .mapToObj(Integer::toString) .collect(joining("\t")); writer.write(uidx + "\t" + a); writer.newLine(); })); } }); saver.accept(prefData, uo); saver.accept(new TransposedPreferenceData<>(prefData), io); }
/** * Saves a PreferenceData instance in two files for user and item preferences, respectively. The format of the user preferences stream consists on one list per line, starting with the identifier of the user followed by the identifier-rating pairs of the items related to that. The item preferences stream follows the same format by swapping the roles of users and items. * * @param prefData preferences * @param uo stream of user preferences * @param io stream of user preferences */ public void write(FastPreferenceData<?, ?> prefData, OutputStream uo, OutputStream io) { BiConsumer<FastPreferenceData<?, ?>, OutputStream> saver = Unchecked.biConsumer((prefs, os) -> { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os))) { prefs.getUidxWithPreferences().forEach(Unchecked.intConsumer(uidx -> { String a = prefs.getUidxPreferences(uidx) .sorted((p1, p2) -> Integer.compare(p1.v1, p2.v1)) .map(p -> p.v1 + "\t" + (int) p.v2) .collect(joining("\t")); writer.write(uidx + "\t" + a); writer.newLine(); })); } }); saver.accept(prefData, uo); saver.accept(new TransposedPreferenceData<>(prefData), io); }
private LogicalFlowStatistics calculateStatsForAppIdSelector(IdSelectionOptions options) { checkNotNull(options, "options cannot be null"); Select<Record1<Long>> appIdSelector = appIdSelectorFactory.apply(options); Future<List<TallyPack<String>>> dataTypeCounts = dbExecutorPool.submit(() -> FunctionUtilities.time("DFS.dataTypes", () -> logicalFlowStatsDao.tallyDataTypesByAppIdSelector(appIdSelector))); Future<LogicalFlowMeasures> appCounts = dbExecutorPool.submit(() -> FunctionUtilities.time("DFS.appCounts", () -> logicalFlowStatsDao.countDistinctAppInvolvementByAppIdSelector(appIdSelector))); Future<LogicalFlowMeasures> flowCounts = dbExecutorPool.submit(() -> FunctionUtilities.time("DFS.flowCounts", () -> logicalFlowStatsDao.countDistinctFlowInvolvementByAppIdSelector(appIdSelector))); Supplier<ImmutableLogicalFlowStatistics> statSupplier = Unchecked.supplier(() -> ImmutableLogicalFlowStatistics.builder() .dataTypeCounts(dataTypeCounts.get()) .appCounts(appCounts.get()) .flowCounts(flowCounts.get()) .build()); return statSupplier.get(); }
public List<TallyPack<String>> generateWithNoRollup(Collection<Long> statisticIds, EntityReference entityReference) { checkNotNull(statisticIds, "statisticIds cannot be null"); checkNotNull(entityReference, "entityReference cannot be null"); if (statisticIds.isEmpty()) { return Collections.emptyList(); } List<Future<TallyPack<String>>> summaryFutures = statisticIds.stream() .map(statId -> dbExecutorPool.submit(() -> generateWithNoRollup(statId, entityReference))) .collect(toList()); return summaryFutures.stream() .map(f -> Unchecked.supplier(() -> f.get()) .get()) .collect(toList()); }
private <T> List<TallyPack<String>> generateSummaries(Collection<Long> statisticIds, Select<Record1<Long>> appIdSelector, Field<T> aggregateField, Function<T, Double> toTally) { checkNotNull(statisticIds, "statisticIds cannot be null"); checkNotNull(appIdSelector, "appIdSelector cannot be null"); checkNotNull(aggregateField, "aggregateField cannot be null"); checkNotNull(toTally, "toTally function cannot be null"); if (statisticIds.isEmpty()) { return Collections.emptyList(); } List<Future<TallyPack<String>>> summaryFutures = statisticIds.stream() .map(statId -> dbExecutorPool.submit(() -> generateSummary(statId, appIdSelector, aggregateField, toTally))) .collect(toList()); return summaryFutures.stream() .map(f -> Unchecked.supplier(() -> f.get()) .get()) .collect(toList()); }
public static void main(String[] args) { File dir = new File("."); Arrays.stream(dir.listFiles()).forEach(file -> { try { System.out.println(file.getCanonicalPath()); } catch (IOException e) { throw new RuntimeException(e); } // Ouch, my fingers hurt! All this typing! }); // TODO use Unchecked.consumer from JOOL library // SOLUTION( Arrays.stream(dir.listFiles()).forEach(Unchecked.consumer(file -> { System.out.println(file.getCanonicalPath()); })); // SOLUTION) }
/** * Improvements on inter-operation with JDK 1.0 code */ private static void jdk1_0() { Thread[] threads = { // Pass a lambda to a thread new Thread(() -> { longOperation(); }), // Pass a method reference to a thread new Thread(ThreadGoodies::longOperation), // Wrap lambdas throwing checked exceptions. new Thread(Unchecked.runnable(ThreadGoodies::failingOperation)) }; // Start all threads Arrays.stream(threads).forEach(Thread::start); // Join all threads Arrays.stream(threads).forEach(Unchecked.consumer(t -> t.join())); }
public static void main(String[] args) throws Exception { Class.forName("org.h2.Driver"); try (Connection c = getConnection("jdbc:h2:~/sql-goodies-continued", "sa", "")) { String sql = "select schema_name, is_default from information_schema.schemata order by schema_name"; try (PreparedStatement stmt = c.prepareStatement(sql)) { SQL.stream(stmt, Unchecked.function(r -> new SQLGoodies.Schema( r.getString("SCHEMA_NAME"), r.getBoolean("IS_DEFAULT") ) )) .forEach(System.out::println); } } }
/** * This method recursively lists all * .txt and .java files in a directory */ private static void listRecursive(File dir) { Arrays.stream(dir.listFiles((f, n) -> !n.startsWith(".") && (f.isDirectory() || n.endsWith(".txt") || n.endsWith(".java")) )) .forEach(Unchecked.consumer((file) -> { System.out.println( file.getCanonicalPath() .substring( new File(".") .getCanonicalPath() .length() )); if (file.isDirectory()) { listRecursive(file); } })); }
@Override public void encodeExtensionObject(String field, ExtensionObject value) { if (value != null) { write(field, Unchecked.consumer(w -> { encodeNodeId("TypeId", value.getEncodingTypeId()); Object object = value.getEncoded(); if (object instanceof UaSerializable) { UaSerializable serializable = (UaSerializable) object; encodeSerializable("Body", serializable); } else if (object instanceof ByteString) { ByteString byteString = (ByteString) object; streamWriter.writeStartElement("Body"); encodeByteString("ByteString", byteString); streamWriter.writeEndElement(); } else if (object instanceof XmlElement) { XmlElement xmlElement = (XmlElement) object; encodeXmlElement("Body", xmlElement); } })); } }
@Override public void encodeQualifiedName(String field, QualifiedName value) { if (value != null) { write(field, Unchecked.consumer(w -> { encodeUInt16("NamespaceIndex", value.getNamespaceIndex()); encodeString("Name", value.getName()); })); } else { if (field != null) { try { streamWriter.writeEmptyElement(field); } catch (XMLStreamException e) { throw new UaSerializationException(StatusCodes.Bad_EncodingError, e); } } } }
@Override public void encodeLocalizedText(String field, LocalizedText value) { if (value != null) { write(field, Unchecked.consumer(w -> { encodeString("Locale", value.getLocale()); encodeString("Text", value.getText()); })); } else { if (field != null) { try { streamWriter.writeEmptyElement(field); } catch (XMLStreamException e) { throw new UaSerializationException(StatusCodes.Bad_EncodingError, e); } } } }
@Override public void encodeGuid(String field, UUID value) { if (value != null) { write(field, Unchecked.consumer(w -> { w.writeStartElement("String"); w.writeCharacters(value.toString()); w.writeEndElement(); })); } else { if (field != null) { try { streamWriter.writeEmptyElement(field); } catch (XMLStreamException e) { throw new UaSerializationException(StatusCodes.Bad_EncodingError, e); } } } }
@Override public void encodeNodeId(String field, NodeId value) { if (value != null) { write(field, Unchecked.consumer(w -> { w.writeStartElement("Identifier"); w.writeCharacters(value.toParseableString()); w.writeEndElement(); })); } else { if (field != null) { try { streamWriter.writeEmptyElement(field); } catch (XMLStreamException e) { throw new UaSerializationException(StatusCodes.Bad_EncodingError, e); } } } }
@Override public void encodeExpandedNodeId(String field, ExpandedNodeId value) { if (value != null) { write(field, Unchecked.consumer(w -> { w.writeStartElement("Identifier"); w.writeCharacters(value.toParseableString()); w.writeEndElement(); })); } else { if (field != null) { try { streamWriter.writeEmptyElement(field); } catch (XMLStreamException e) { throw new UaSerializationException(StatusCodes.Bad_EncodingError, e); } } } }
private MetadataResolverAdapter configureAdapter(final AbstractMetadataResolverAdapter adapter) { final Map<Resource, MetadataFilterChain> resources = new HashMap<>(); final MetadataFilterChain chain = new MetadataFilterChain(); casProperties.getSamlMetadataUi().getResources().forEach(Unchecked.consumer(r -> configureResource(resources, chain, r))); adapter.setRequireValidMetadata(casProperties.getSamlMetadataUi().isRequireValidMetadata()); adapter.setMetadataResources(resources); adapter.setConfigBean(openSamlConfigBean); return adapter; }
private void configureResource(final Map<Resource, MetadataFilterChain> resources, final MetadataFilterChain chain, final String r) throws Exception { final String[] splitArray = org.springframework.util.StringUtils.commaDelimitedListToStringArray(r); Arrays.stream(splitArray).forEach(Unchecked.consumer(entry -> { final String[] arr = entry.split(DEFAULT_SEPARATOR); final String metadataFile = arr[0]; final String signingKey = arr.length > 1 ? arr[1] : null; final List<MetadataFilter> filters = new ArrayList<>(); if (casProperties.getSamlMetadataUi().getMaxValidity() > 0) { filters.add(new RequiredValidUntilFilter(casProperties.getSamlMetadataUi().getMaxValidity())); } boolean addResource = true; if (StringUtils.isNotBlank(signingKey)) { final SignatureValidationFilter sigFilter = SamlUtils.buildSignatureValidationFilter(this.resourceLoader, signingKey); if (sigFilter != null) { sigFilter.setRequireSignedRoot(casProperties.getSamlMetadataUi().isRequireSignedRoot()); filters.add(sigFilter); } else { LOGGER.warn("Failed to locate the signing key [{}] for [{}]", signingKey, metadataFile); addResource = false; } } chain.setFilters(filters); final Resource resource = this.resourceLoader.getResource(metadataFile); if (addResource && ResourceUtils.doesResourceExist(resource)) { resources.put(resource, chain); } else { LOGGER.warn("Skipping metadata [{}]; Either the resource cannot be retrieved or its signing key is missing", metadataFile); } })); }
@Test public void verifyAuthenticateFailure() throws Throwable { assertNotEquals(handler.size(), 0); this.thrown.expect(FailedLoginException.class); try { this.getEntries().stream() .map(entry -> entry.getAttribute("sAMAccountName").getStringValue()) .forEach(username -> this.handler.forEach(Unchecked.consumer(h -> { h.authenticate(new UsernamePasswordCredential(username, "badpassword")); }))); } catch (final Exception e) { throw e.getCause(); } }
@Test public void verifyAuthenticateNotFound() throws Throwable { try { this.thrown.expect(AccountNotFoundException.class); this.handler.forEach(Unchecked.consumer(h -> { h.authenticate(new UsernamePasswordCredential("notfound", "badpassword")); })); } catch (final Exception e) { throw e.getCause(); } }
/** * Handle request for jwk set. * * @param request the request * @param response the response * @param model the model * @return the jwk set * @throws Exception the exception */ @GetMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.JWKS_URL, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response, final Model model) throws Exception { Assert.notNull(this.jwksFile, "JWKS file cannot be undefined or null."); try { final String jsonJwks = IOUtils.toString(this.jwksFile.getInputStream(), StandardCharsets.UTF_8); final JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jsonJwks); this.servicesManager.getAllServices() .stream() .filter(s -> s instanceof OidcRegisteredService && StringUtils.isNotBlank(((OidcRegisteredService) s).getJwks())) .forEach( Unchecked.consumer(s -> { final OidcRegisteredService service = (OidcRegisteredService) s; final Resource resource = this.resourceLoader.getResource(service.getJwks()); final JsonWebKeySet set = new JsonWebKeySet(IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8)); set.getJsonWebKeys().forEach(jsonWebKeySet::addJsonWebKey); })); final String body = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY); response.setContentType(MediaType.APPLICATION_JSON_VALUE); return new ResponseEntity<>(body, HttpStatus.OK); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } }
public OidcProfileScopeToAttributesFilter(final PrincipalFactory principalFactory, final ServicesManager servicesManager, final Collection<BaseOidcScopeAttributeReleasePolicy> userScopes, final OidcAttributeToScopeClaimMapper attributeToScopeClaimMapper) { this.attributeToScopeClaimMapper = attributeToScopeClaimMapper; this.filters = new HashMap<>(); final String packageName = BaseOidcScopeAttributeReleasePolicy.class.getPackage().getName(); final Reflections reflections = new Reflections(new ConfigurationBuilder() .filterInputsBy(new FilterBuilder().includePackage(packageName)) .setUrls(ClasspathHelper.forPackage(packageName)) .setScanners(new SubTypesScanner(true))); final Set<Class<? extends BaseOidcScopeAttributeReleasePolicy>> subTypes = reflections.getSubTypesOf(BaseOidcScopeAttributeReleasePolicy.class); subTypes.forEach(Unchecked.consumer(t -> { final BaseOidcScopeAttributeReleasePolicy ex = t.newInstance(); filters.put(ex.getScopeName(), ex); })); userScopes.forEach(t -> filters.put(t.getScopeName(), t)); this.principalFactory = principalFactory; this.servicesManager = servicesManager; this.userScopes = userScopes; }
/** * Create ticket tables. * * @param deleteTables the delete tables */ public void createTicketTables(final boolean deleteTables) { final Collection<TicketDefinition> metadata = this.ticketCatalog.findAll(); metadata.forEach(Unchecked.consumer(r -> { final CreateTableRequest request = new CreateTableRequest() .withAttributeDefinitions(new AttributeDefinition(ColumnNames.ID.getName(), ScalarAttributeType.S)) .withKeySchema(new KeySchemaElement(ColumnNames.ID.getName(), KeyType.HASH)) .withProvisionedThroughput(new ProvisionedThroughput(dynamoDbProperties.getReadCapacity(), dynamoDbProperties.getWriteCapacity())) .withTableName(r.getProperties().getStorageName()); if (deleteTables) { final DeleteTableRequest delete = new DeleteTableRequest(r.getProperties().getStorageName()); LOGGER.debug("Sending delete request [{}] to remove table if necessary", delete); TableUtils.deleteTableIfExists(amazonDynamoDBClient, delete); } LOGGER.debug("Sending delete request [{}] to create table", request); TableUtils.createTableIfNotExists(amazonDynamoDBClient, request); LOGGER.debug("Waiting until table [{}] becomes active...", request.getTableName()); TableUtils.waitUntilActive(amazonDynamoDBClient, request.getTableName()); final DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(request.getTableName()); LOGGER.debug("Sending request [{}] to obtain table description...", describeTableRequest); final TableDescription tableDescription = amazonDynamoDBClient.describeTable(describeTableRequest).getTable(); LOGGER.debug("Located newly created table with description: [{}]", tableDescription); })); }
@Override public void serialize(final X509CertificateCredential value, final JsonGenerator generator, final SerializerProvider serializerProvider) throws IOException { generator.writeArrayFieldStart("certificates"); Arrays.stream(value.getCertificates()).forEach(Unchecked.consumer(c -> generator.writeBinary(c.getEncoded()))); generator.writeEndArray(); }
public List<User> listUsers() { HttpUrl route = HttpUrl.parse(host + "/users"); Request request = new Request.Builder().url(route).get().build(); return Unchecked.supplier(() -> { try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { List<User> users = Json.serializer().fromInputStream(response.body().byteStream(), User.listTypeRef()); return users; } throw HttpClient.unknownException(response); } }).get(); }
private static String parseTableMappings(List<ValueMapping> map, final Database db, JDefaultDict<String, ConcurrentMap<ValueMapping, Tuple2<String, String>>> foreignKeyMapping, ConcurrentMap<ValueMapping, Joiner> joiners) throws IOException { String originTable = map.isEmpty() ? null : db.getTable(CSVUtil.DOT_PATTERN.split(map.get(0).getInputField())[0]).getName(); // for (final ValueMapping nextValueMapping : map) { // Must be a sequential mapping as ordering is important map.stream().sequential().forEach(Unchecked.consumer(nextValueMapping -> { if (nextValueMapping.getLanguage() == ValueMappingLanguage.ACCESS) { final String[] splitDBField = CSVUtil.DOT_PATTERN.split(nextValueMapping.getInputField()); System.out.println(nextValueMapping.getInputField()); final Table nextTable = db.getTable(splitDBField[0]); final String[] splitForeignDBField = CSVUtil.DOT_PATTERN.split(nextValueMapping.getMapping()); final Table nextForeignTable = db.getTable(splitForeignDBField[0]); if (nextForeignTable == null) { throw new RuntimeException( "Could not find table referenced by access mapping: " + nextValueMapping.getMapping()); } foreignKeyMapping.get(splitForeignDBField[0]).put(nextValueMapping, Tuple.tuple(nextTable.getName(), nextForeignTable.getName())); try { final Joiner create = Joiner.create(nextTable, nextForeignTable); if (create != null) { joiners.put(nextValueMapping, create); System.out.println("PK->FK: " + joiners.get(nextValueMapping).toFKString()); } } catch (IllegalArgumentException e) { e.printStackTrace(); } } })); return originTable; }
static void upload(String tableName, List<ValueMapping> map, Reader input, Connection conn) throws IOException, SQLException { final AtomicReference<PreparedStatement> preparedStmt = new AtomicReference<>(); try { final List<String> types = new ArrayList<>(); final List<String> outputFieldNames = new ArrayList<>(); CSVStream.parse(input, Unchecked.consumer(h -> { final StringBuilder insertStatement = new StringBuilder(2048); h.forEach(nextH -> { Optional<ValueMapping> firstMapping = map.stream() .filter(m -> m.getLanguage() == ValueMapping.ValueMappingLanguage.DBSCHEMA) .filter(m -> m.getInputField().equalsIgnoreCase(nextH)).findFirst(); if (firstMapping.isPresent()) { types.add(firstMapping.get().getMapping()); outputFieldNames.add(firstMapping.get().getOutputField()); } else { types.add("TEXT"); outputFieldNames.add(nextH); } }); createTable(tableName, outputFieldNames, types, insertStatement, conn); String insertStatementString = insertStatement.toString(); System.out.println(insertStatementString); preparedStmt.set(conn.prepareStatement(insertStatementString)); }), Unchecked.biFunction((h, l) -> { uploadLine(outputFieldNames, l, types, preparedStmt.get()); return l; }), l -> { }); } finally { PreparedStatement closeable = preparedStmt.get(); if (closeable != null) { closeable.close(); } preparedStmt.set(null); } }