Unnamed: 0
int64
0
403
cwe_id
stringclasses
1 value
source
stringlengths
56
2.02k
target
stringlengths
50
1.97k
300
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception{ if (state() == State.HEADER) { int nLoc = in.bytesBefore((byte) '\n'); ByteBuf headerBuf = in.readBytes(nLoc + 1); String headerLine = headerBuf.toString(UTF8).trim(); nLoc = in.bytesBefore((byte) '\n'); in.readBytes(nLoc); in.readByte(); if (headerLine.startsWith(CONTENT_LENGTH)) { String lenStr = headerLine.substring(CONTENT_LENGTH.length()).trim(); this.length = Integer.parseInt(lenStr); state(State.BODY); } } if (this.length < 0) { System.err.println("LEN LESS THAN 0"); } if (state() == State.BODY) { if (in.readableBytes() < this.length) { return; } ByteBuf jsonBuf = in.slice(in.readerIndex(), this.length); in.readerIndex(in.readerIndex() + this.length); this.length = -1; ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true); JsonNode node = mapper.readTree(new ByteBufInputStream((ByteBuf) jsonBuf)); String type = node.get("type").asText(); if ("request".equals(type)) { String commandStr = node.get("command").asText(); AbstractCommand command = this.debugger.getCommand(commandStr); if (command != null) { ObjectReader reader = mapper.reader().withValueToUpdate(command.newRequest()); Request request = reader.readValue(node); out.add(request); } } state(State.HEADER); } }
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception{ if (state() == State.HEADER) { int nLoc = in.bytesBefore((byte) '\n'); ByteBuf headerBuf = in.readBytes(nLoc + 1); String headerLine = headerBuf.toString(UTF8).trim(); nLoc = in.bytesBefore((byte) '\n'); in.readBytes(nLoc); in.readByte(); if (headerLine.startsWith(CONTENT_LENGTH)) { String lenStr = headerLine.substring(CONTENT_LENGTH.length()).trim(); this.length = Integer.parseInt(lenStr); state(State.BODY); return; } } if (state() == State.BODY) { ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true); JsonNode node = mapper.readTree(new ByteBufInputStream(in, this.length)); String type = node.get("type").asText(); if ("request".equals(type)) { String commandStr = node.get("command").asText(); AbstractCommand command = this.debugger.getCommand(commandStr); if (command != null) { ObjectReader reader = mapper.reader().withValueToUpdate(command.newRequest()); Request request = reader.readValue(node); out.add(request); } } state(State.HEADER); this.length = -1; } }
301
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException{ if (attribute.getValue() == null) { throw new WrongAttributeValueException(attribute); } Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); Attribute facilityAttr = null; try { facilityAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, facility, A_F_homeMountPoints); } catch (AttributeNotExistsException ex) { throw new InternalErrorException(ex); } if (facilityAttr.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, facilityAttr, "Reference attribute have null value."); if (!((List<String>) facilityAttr.getValue()).containsAll((List<String>) attribute.getValue())) { throw new WrongAttributeValueException(attribute); } List<String> homeMountPoints = (List<String>) attribute.getValue(); if (!homeMountPoints.isEmpty()) { Pattern pattern = Pattern.compile("^/[-a-zA-Z.0-9_/]*$"); for (String st : homeMountPoints) { Matcher match = pattern.matcher(st); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad homeMountPoints attribute format " + st); } } } }
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException{ if (attribute.getValue() == null) { throw new WrongAttributeValueException(attribute); } Facility facility = perunSession.getPerunBl().getResourcesManagerBl().getFacility(perunSession, resource); Attribute facilityAttr = null; try { facilityAttr = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, facility, A_F_homeMountPoints); } catch (AttributeNotExistsException ex) { throw new InternalErrorException(ex); } if (facilityAttr.getValue() == null) throw new WrongReferenceAttributeValueException(attribute, facilityAttr, "Reference attribute have null value."); if (!((List<String>) facilityAttr.getValue()).containsAll((List<String>) attribute.getValue())) { throw new WrongAttributeValueException(attribute); } List<String> homeMountPoints = (List<String>) attribute.getValue(); if (!homeMountPoints.isEmpty()) { for (String st : homeMountPoints) { Matcher match = pattern.matcher(st); if (!match.matches()) { throw new WrongAttributeValueException(attribute, "Bad homeMountPoints attribute format " + st); } } } }
302
private ServiceSchedule parseDaySchedule(String strSchedule, TimeInterval timeInterval) throws ParseException{ DayOfWeek dayOfWeek = dayFormat.parse(strSchedule.substring(0, 3)).toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getDayOfWeek(); ServiceSchedule serviceSchedule = new ServiceSchedule(); serviceSchedule.setOpenTime(LocalDateTime.of(LocalDate.of(1970, 1, 4), timeInterval.getInitialTime()).with(TemporalAdjusters.next(dayOfWeek))); LocalDateTime localEndTime = LocalDateTime.of(LocalDate.of(1970, 1, 4), timeInterval.getEndTime()).with(TemporalAdjusters.next(dayOfWeek)); if (timeInterval.getEndTime().isAfter(LocalTime.of(0, 0, 0)) && timeInterval.getEndTime().isBefore(timeInterval.getInitialTime())) { localEndTime = localEndTime.plusDays(1); } serviceSchedule.setCloseTime(localEndTime); return serviceSchedule; }
private ServiceSchedule parseDaySchedule(String strSchedule, TimeInterval timeInterval) throws ParseException{ DayOfWeek dayOfWeek = dayFormat.parse(strSchedule.substring(0, 3)).toInstant().atZone(ZoneId.systemDefault()).toLocalDate().getDayOfWeek(); ServiceSchedule serviceSchedule = setOpenAndCloseTime(timeInterval, dayOfWeek.getValue()); return serviceSchedule; }
303
private List<GeneratedImage> getCrashedImage(BlockUml blockUml, Throwable t, SFile outputFile) throws IOException{ final GeneratedImage image = new GeneratedImageImpl(outputFile, "Crash Error", blockUml, FileImageData.CRASH); OutputStream os = null; try { os = outputFile.createBufferedOutputStream(); UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(), UmlDiagram.getFailureText2(t, blockUml.getFlashData())); } finally { if (os != null) { os.close(); } } return Collections.singletonList(image); }
private List<GeneratedImage> getCrashedImage(BlockUml blockUml, Throwable t, SFile outputFile) throws IOException{ final GeneratedImage image = new GeneratedImageImpl(outputFile, "Crash Error", blockUml, FileImageData.CRASH); try (OutputStream os = outputFile.createBufferedOutputStream()) { UmlDiagram.exportDiagramError(os, t, fileFormatOption, 42, null, blockUml.getFlashData(), UmlDiagram.getFailureText2(t, blockUml.getFlashData())); } return Collections.singletonList(image); }
304
public String addCommentForUserGame(@RequestBody CommentsForGameDTO commentsForGameDTO){ CommentsForGame commentsForGame = new CommentsForGame(); commentsForGame = CommentForGameMapper.toEntity(commentsForGameDTO); commentsForGame.setGameUser(gameUserService.getUserGamesById(commentsForGameDTO.getGameID())); commentsForGame.setUser(userService.getUser(WebUtil.getPrincipalUsername())); commentForGameService.addComment(commentsForGame); return ""; }
public void addCommentForUserGame(@RequestBody CommentsForGameDTO commentsForGameDTO){ CommentsForGame commentsForGame = new CommentsForGame(); commentsForGame = CommentForGameMapper.toEntity(commentsForGameDTO); commentsForGame.setGameUser(gameUserService.getUserGamesById(commentsForGameDTO.getGameID())); commentsForGame.setUser(userService.getUser(WebUtil.getPrincipalUsername())); commentForGameService.addComment(commentsForGame); }
305
public void execute(){ Profiler profiler = new Profiler(); profiler.start(); ConfigHelper.inputConfigValidation(this.configuration.getInputConfig()); ConfigHelper.outputConfigValidation(this.configuration.getOutputConfig()); logger.info("Start execution for input type " + this.configuration.getInputConfig().inputType()); long lastLine = this.dataIteration(); this.printLogToOutput(profiler, lastLine); }
public void execute(){ Profiler profiler = new Profiler(); profiler.start(); this.validation(); logger.info("Start execution for input type " + this.configuration.getInputConfig().inputType()); long lastLine = this.dataIteration(); this.printLogToOutput(profiler, lastLine); }
306
public void parse(ByteBuffer b, Data data){ int size = b.get() & 0xff; ByteBuffer buf = b.slice(); buf.limit(size); b.position(b.position() + size); int count = buf.get() & 0xff; data.putList(); parseChildren(data, buf, count); }
public void parse(ProtonBuffer buffer, Data data){ int size = buffer.readByte() & 0xff; ProtonBuffer buf = buffer.slice(buffer.getReadIndex(), size); buffer.skipBytes(size); int count = buf.readByte() & 0xff; data.putList(); parseChildren(data, buf, count); }
307
private void parseHtmlMarkup(Message resultMessage){ StringBuilder messageBuilder = new StringBuilder(resultMessage.text()); if (messageBuilder.indexOf("-\n") != -1) { MessageEntity[] entityArray = resultMessage.entities(); int globalOffset = 0; String preStart = "<pre>"; String preEnd = "</pre>"; for (int i = 0; i < entityArray.length; i++) { MessageEntity entity = entityArray[i]; switch(entity.type()) { case pre: { messageBuilder.insert(entity.offset() + globalOffset, preStart); globalOffset += preStart.length(); messageBuilder.insert(entity.offset() + entity.length() + globalOffset, preEnd); globalOffset += preEnd.length(); break; } default: break; } } int preStartIndex = messageBuilder.indexOf(preStart); int preEndIndex = messageBuilder.indexOf(preEnd); if (preStartIndex != -1 && preEndIndex != -1) { message = messageBuilder.substring(preStartIndex + preStart.length(), preEndIndex); } LOG.debug("Parsed message: {}", message); } }
private void parseHtmlMarkup(Message resultMessage){ StringBuilder messageBuilder = new StringBuilder(resultMessage.text()); if (messageBuilder.indexOf("-\n") != -1) { MessageEntity[] entityArray = resultMessage.entities(); int globalOffset = 0; String preStart = "<pre>"; String preEnd = "</pre>"; for (int i = 0; i < entityArray.length; i++) { MessageEntity entity = entityArray[i]; switch(entity.type()) { case pre: { messageBuilder.insert(entity.offset() + globalOffset, preStart); globalOffset += preStart.length(); messageBuilder.insert(entity.offset() + entity.length() + globalOffset, preEnd); globalOffset += preEnd.length(); break; } default: break; } } int preStartIndex = messageBuilder.indexOf(preStart); int preEndIndex = messageBuilder.indexOf(preEnd); if (preStartIndex != -1 && preEndIndex != -1) { message = messageBuilder.substring(preStartIndex + preStart.length(), preEndIndex); } } }
308
public String getGameScore(){ if (isDeuce()) score = String.valueOf(TennisPoints.Deuce); else if (isPlayerOneAdvantage()) score = playerOne.getName() + SPACE + TennisPoints.Advantage; else if (isPlayerTwoAdvantage()) score = playerTwo.getName() + SPACE + TennisPoints.Advantage; else if (playerOne.getPointScore() == playerTwo.getPointScore()) score = translateScore(playerOne.getPointScore()) + SPACE + ALL; else if (isPlayerTwoWinner()) score = playerTwo.getName() + SPACE + WINS; else score = translateScore(playerOne.getPointScore()) + SPACE + translateScore(playerTwo.getPointScore()); return score; }
public String getGameScore(){ if (isDeuce()) score = String.valueOf(TennisPoints.Deuce); else if (hasAdvantage()) return advantagePlayerName() + " " + TennisPoints.Advantage; else if (playerOne.getPointScore() == playerTwo.getPointScore()) score = translateScore(playerOne.getPointScore()) + SPACE + ALL; else if (isPlayerTwoWinner()) score = playerTwo.getName() + SPACE + WINS; else score = translateScore(playerOne.getPointScore()) + SPACE + translateScore(playerTwo.getPointScore()); return score; }
309
private void onOutcomeSubmitButtonClicked(){ boolean wasSubmitted = false; if (validationService.isNameValid(outcomeNameTextField.getText()) && validationService.isValueValid(outcomeValueTextField.getText()) && isCategorySelected(outcomeCategoryComboBox)) { outcomeService.getAllPositions().add(new Outcome(outcomeNameTextField.getText(), validationService.returnFormattedValue(outcomeValueTextField.getText()), outcomeCategoryComboBox.getSelectionModel().getSelectedItem())); outcomeObservableList.clear(); outcomeObservableList.addAll(outcomeService.getAllPositions()); outcomeCategoryComboBox.getSelectionModel().clearSelection(); outcomeNameTextField.clear(); outcomeValueTextField.clear(); summaryObservableList.clear(); summaryObservableList.addAll(outcomeObservableList); summaryObservableList.addAll(incomeObservableList); outcomeNameRequiredText.setVisible(false); outcomeWrongValueText.setVisible(false); outcomeSelectCategoryText.setVisible(false); wasSubmitted = true; outcomeTableView.sort(); } if (!wasSubmitted) { validAllMessagesUnderFields(outcomeNameTextField, outcomeNameRequiredText, outcomeValueTextField, outcomeWrongValueText, outcomeCategoryComboBox, outcomeSelectCategoryText); } }
private void onOutcomeSubmitButtonClicked(){ boolean wasSubmitted = false; if (validationService.isNameValid(outcomeNameTextField.getText()) && validationService.isValueValid(outcomeValueTextField.getText()) && isCategorySelected(outcomeCategoryComboBox)) { outcomeService.getAllPositions().add(new Outcome(outcomeNameTextField.getText(), validationService.returnFormattedValue(outcomeValueTextField.getText()), outcomeCategoryComboBox.getSelectionModel().getSelectedItem())); clearPositionAfterSubmitted(outcomeObservableList, outcomeService, outcomeTableView, outcomeCategoryComboBox, outcomeNameTextField, outcomeValueTextField, outcomeNameRequiredText, outcomeWrongValueText, outcomeSelectCategoryText); wasSubmitted = true; } if (!wasSubmitted) { validAllMessagesUnderFields(outcomeNameTextField, outcomeNameRequiredText, outcomeValueTextField, outcomeWrongValueText, outcomeCategoryComboBox, outcomeSelectCategoryText); } }
310
public void run(){ try { synchronized (this) { Starter.addToDb(employeeDAO, subList); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
public void run(){ synchronized (this) { employeeDAO.insertEmployee(subList); } }
311
public T1Entity save(T1Entity entity) throws ClientException, ParseException{ if (entity == null) return null; JsonResponse<? extends T1Entity> finalJsonResponse; StringBuilder uri = getUri(entity); String uriPath = entity.getUri(); if (checkString(uriPath)) uri.append(uriPath); String path = t1Service.constructUrl(uri); Response responseObj = this.connection.post(path, entity.getForm(), this.user); String response = responseObj.readEntity(String.class); T1JsonToObjParser parser = new T1JsonToObjParser(); if (response.isEmpty()) return null; JsonPostErrorResponse error = jsonPostErrorResponseParser(response, responseObj); if (error != null) throwExceptions(error); finalJsonResponse = parsePostData(response, parser, entity); if (finalJsonResponse == null) return null; return finalJsonResponse.getData(); }
public T1Entity save(T1Entity entity) throws ClientException, ParseException{ if (entity == null) return null; JsonResponse<? extends T1Entity> finalJsonResponse; StringBuilder uri = getUri(entity); String uriPath = entity.getUri(); if (checkString(uriPath)) uri.append(uriPath); String path = t1Service.constructUrl(uri); Response responseObj = this.connection.post(path, entity.getForm(), this.user); finalJsonResponse = getJsonResponse(entity, responseObj); if (finalJsonResponse == null) return null; return finalJsonResponse.getData(); }
312
public void showCards(){ programCardsToChooseFrom = roboGame.localPlayer.getReceivedProgramCards(); for (ProgramCard c : programCardsToChooseFrom) { picked.add(c); } int xStart = 800; int yStart = 295; int width = 120; int height = 200; int deltaW = 125; int deltaH = 205; int i = 0; for (int x = xStart; x < xStart + 3 * deltaW; x += deltaW) { for (int y = yStart; y < yStart + 3 * deltaH; y += deltaH) { ProgramCard currentCard = roboGame.localPlayer.getReceivedProgramCards().remove(0); ImageButton imageButton = CardUI.createTextureButton(("/cards/" + currentCard.getProgramCardType().toString())); imageButton.setPosition(x, y); imageButton.setSize(width, height); imageButton.addListener(new CardInputListener(imageButton, this, x, y, width, height, i)); startCardsStage.addActor(imageButton); i++; } } }
public void showCards(){ programCardsToChooseFrom = roboGame.localPlayer.getReceivedProgramCards(); picked.addAll(programCardsToChooseFrom); int xStart = 800; int yStart = 295; int width = 120; int height = 200; int deltaW = 125; int deltaH = 205; int i = 0; for (int x = xStart; x < xStart + 3 * deltaW; x += deltaW) { for (int y = yStart; y < yStart + 3 * deltaH; y += deltaH) { ProgramCard currentCard = roboGame.localPlayer.getReceivedProgramCards().remove(0); ImageButton imageButton = CardUI.createTextureButton(("/cards/" + currentCard.getProgramCardType().toString())); imageButton.setPosition(x, y); imageButton.setSize(width, height); imageButton.addListener(new CardInputListener(imageButton, this, x, y, width, height, i)); startCardsStage.addActor(imageButton); i++; } } }
313
public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; FxObjNode params = (FxObjNode) srcObj.get("params"); if (params != null) { Map<String, FxNode> varReplacements = params.fieldsHashMapCopy(); FxVarsReplaceFunc replFunc = new FxVarsReplaceFunc(varReplacements); replFunc.eval(dest, ctx, template); } else { FxNodeCopyVisitor.copyTo(dest, template); } return null; }
public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; FxObjNode params = (FxObjNode) srcObj.get("params"); if (params != null) { Map<String, FxNode> varReplacements = params.fieldsHashMapCopy(); FxVarsReplaceFunc replFunc = new FxVarsReplaceFunc(varReplacements); replFunc.eval(dest, ctx, template); } else { FxNodeCopyVisitor.copyTo(dest, template); } }
314
public static List<Statement> evaluateCapturedArguments(final List<Statement> statements, final List<CapturedArgument> capturedArguments){ if (capturedArguments.isEmpty()) { return statements; } else { final List<Object> capturedArgValues = capturedArguments.stream().map(a -> a.getValue()).collect(Collectors.toList()); statements.stream().forEach(s -> s.accept(new StatementExpressionsDelegateVisitor(new CapturedArgumentsEvaluator(capturedArgValues)))); return statements; } }
public static List<Statement> evaluateCapturedArguments(final List<Statement> statements, final List<CapturedArgument> capturedArguments){ if (capturedArguments.isEmpty()) { return statements; } final List<Object> capturedArgValues = capturedArguments.stream().map(a -> a.getValue()).collect(Collectors.toList()); statements.stream().forEach(s -> s.accept(new StatementExpressionsDelegateVisitor(new CapturedArgumentsEvaluator(capturedArgValues)))); return statements; }
315
private void generateMetaPropertyMapSetup(){ data.ensureImport(MetaProperty.class); data.ensureImport(DirectMetaPropertyMap.class); insertRegion.add("\t\t/**"); insertRegion.add("\t\t * The meta-properties."); insertRegion.add("\t\t */"); insertRegion.add("\t\tprivate final Map<String, MetaProperty<?>> " + config.getPrefix() + "metaPropertyMap$ = new DirectMetaPropertyMap("); if (data.isSubClass()) { insertRegion.add("\t\t\t\tthis, (DirectMetaPropertyMap) super.metaPropertyMap()" + (properties.size() == 0 ? ");" : ",")); } else { insertRegion.add("\t\t\t\tthis, null" + (properties.size() == 0 ? ");" : ",")); } for (int i = 0; i < properties.size(); i++) { String line = "\t\t\t\t\"" + properties.get(i).getData().getPropertyName() + "\""; line += (i + 1 == properties.size() ? ");" : ","); insertRegion.add(line); } insertRegion.add(""); }
private void generateMetaPropertyMapSetup(){ data.ensureImport(MetaProperty.class); data.ensureImport(DirectMetaPropertyMap.class); insertRegion.add("\t\t/**"); insertRegion.add("\t\t * The meta-properties."); insertRegion.add("\t\t */"); insertRegion.add("\t\tprivate final Map<String, MetaProperty<?>> " + config.getPrefix() + "metaPropertyMap$ = new DirectMetaPropertyMap("); if (data.isSubClass()) { insertRegion.add("\t\t\t\tthis, (DirectMetaPropertyMap) super.metaPropertyMap()" + (properties.size() == 0 ? ");" : ",")); } else { insertRegion.add("\t\t\t\tthis, null" + (properties.size() == 0 ? ");" : ",")); } for (int i = 0; i < properties.size(); i++) { insertRegion.add("\t\t\t\t\"" + properties.get(i).getData().getPropertyName() + "\"" + joinComma(i, properties, ");")); } insertRegion.add(""); }
316
public LoanDetailDTO calculate() throws ResponseException{ if (loanRequestDTO.getNominalRate() == 0) { throw new ResponseException("ERR-01", "Nominal rate can not be zero"); } if (loanRequestDTO.getDuration() == 0) { throw new ResponseException("ERR-03", "Duration can not be zero"); } double rate = loanRequestDTO.getNominalRate() / (12 * 100); BigDecimal borrowerPaymentAmount = BigDecimal.valueOf(rate).multiply(loanRequestDTO.getLoanAmount()).divide(BigDecimal.valueOf((1 - Math.pow(1 + rate, -(loanRequestDTO.getDuration())))), 2, RoundingMode.HALF_UP); LoanDetailDTO loanDetailDTO = new LoanDetailDTO(loanRequestDTO.getLoanAmount(), loanRequestDTO.getNominalRate(), ""); loanDetailDTO.setBorrowerPaymentAmount(borrowerPaymentAmount); loanDetailDTO.setDuration(loanRequestDTO.getDuration()); loanDetailDTO.setStartDate(loanRequestDTO.getStartDate()); LOGGER.info(loanDetailDTO.toString()); return loanDetailDTO; }
public LoanDetailDTO calculate() throws ResponseException{ if (loanRequestDTO.getNominalRate() == 0) { throw new ResponseException("ERR-01", "Nominal rate can not be zero"); } if (loanRequestDTO.getDuration() == 0) { throw new ResponseException("ERR-03", "Duration can not be zero"); } double rate = loanRequestDTO.getNominalRate() / (12 * 100); BigDecimal borrowerPaymentAmount = BigDecimal.valueOf(rate).multiply(loanRequestDTO.getLoanAmount()).divide(BigDecimal.valueOf((1 - Math.pow(1 + rate, -(loanRequestDTO.getDuration())))), 2, RoundingMode.HALF_UP); LoanDetailDTO loanDetailDTO = new LoanDetailDTO(loanRequestDTO.getLoanAmount(), loanRequestDTO.getNominalRate(), loanRequestDTO.getStartDate()); loanDetailDTO.setBorrowerPaymentAmount(borrowerPaymentAmount); loanDetailDTO.setDuration(loanRequestDTO.getDuration()); LOGGER.info(loanDetailDTO.toString()); return loanDetailDTO; }
317
public void validateConformanceOperationAndResponse(TestPoint testPoint){ String testPointUri = new UriBuilder(testPoint).buildUrl(); Response response = null; try { response = init().baseUri(testPointUri).accept(JSON).when().request(GET); } catch (Exception e) { if (e.getMessage().contains("dummydata")) { throw new RuntimeException("No conformance classes found at the /conformance path."); } throw new RuntimeException(e); } validateConformanceOperationResponse(testPointUri, response); }
public void validateConformanceOperationAndResponse(TestPoint testPoint){ String testPointUri = new UriBuilder(testPoint).buildUrl(); if (testPointUri.contains("dummydata")) { throw new RuntimeException("No conformance classes found at the /conformance path."); } Response response = init().baseUri(testPointUri).accept(JSON).when().request(GET); validateConformanceOperationResponse(testPointUri, response); }
318
public Map<String, String> getSubAliasProjectNames(String projectId){ Map<String, String> aliasSubProjects = new LinkedHashMap<String, String>(); jdbcTemplate = new JdbcTemplate(dataSource); String sql; List<Map<String, Object>> rows; if ("" != projectId) { sql = "select SubProjId, AliasSubProjName from subproject where ProjId = ?"; rows = jdbcTemplate.queryForList(sql, new Object[] { projectId }); } else { sql = "select SubProjId, AliasSubProjName from subproject"; rows = jdbcTemplate.queryForList(sql); } for (Map<String, Object> row : rows) { aliasSubProjects.put(String.valueOf(row.get("SubProjId")), (String) row.get("AliasSubProjName")); } return aliasSubProjects; }
public Map<String, String> getSubAliasProjectNames(String projectId){ Map<String, String> aliasSubProjects = new LinkedHashMap<String, String>(); String sql; List<Map<String, Object>> rows; if ("" != projectId) { sql = "select SubProjId, AliasSubProjName from subproject where ProjId = ?"; rows = jdbcTemplate.queryForList(sql, new Object[] { projectId }); } else { sql = "select SubProjId, AliasSubProjName from subproject"; rows = jdbcTemplate.queryForList(sql); } for (Map<String, Object> row : rows) { aliasSubProjects.put(String.valueOf(row.get("SubProjId")), (String) row.get("AliasSubProjName")); } return aliasSubProjects; }
319
private void initFields(){ teamId_ = 0; sinceTime_ = 0L; limit_ = 0; type_ = org.jailbreak.api.representations.Representations.Donation.DonationType.OFFLINE; }
private void initFields(){ teamId_ = 0; sinceTime_ = 0L; type_ = org.jailbreak.api.representations.Representations.Donation.DonationType.OFFLINE; }
320
private void onHandshakeDone(Peer peer){ if (!isHandshakeDone) { consenus.onMessage(channel, new BFTNewHeightMessage(peer.getLatestBlockNumber() + 1)); getNodes = exec.scheduleAtFixedRate(() -> { msgQueue.sendMessage(new GetNodesMessage()); }, channel.isInbound() ? 2 : 0, 2, TimeUnit.MINUTES); pingPong = exec.scheduleAtFixedRate(() -> { msgQueue.sendMessage(new PingMessage()); }, channel.isInbound() ? 1 : 0, 1, TimeUnit.MINUTES); isHandshakeDone = true; } }
private void onHandshakeDone(Peer peer){ if (!isHandshakeDone) { consenus.onMessage(channel, new BFTNewHeightMessage(peer.getLatestBlockNumber() + 1)); getNodes = exec.scheduleAtFixedRate(() -> msgQueue.sendMessage(new GetNodesMessage()), channel.isInbound() ? 2 : 0, 2, TimeUnit.MINUTES); pingPong = exec.scheduleAtFixedRate(() -> msgQueue.sendMessage(new PingMessage()), channel.isInbound() ? 1 : 0, 1, TimeUnit.MINUTES); isHandshakeDone = true; } }
321
public static List<PostDTO> getPostsDTOs(){ PostDTO postOne = new PostDTO(); postOne.setId(1L); postOne.setDateCreated(LocalDateTime.now()); postOne.setDateUpdated(LocalDateTime.now()); postOne.setPostTitle("Test post one title"); postOne.setContent("Test post one content"); postOne.setCover("testPostOne.webp"); postOne.setReadTime(10); postOne.setSlug("test-post-one"); postOne.setPublicationDate(LocalDateTime.now()); PostDTO postTwo = new PostDTO(); postTwo.setId(2L); postTwo.setDateCreated(LocalDateTime.now()); postTwo.setDateUpdated(LocalDateTime.now()); postTwo.setPostTitle("Test post two title"); postTwo.setContent("Test post two content"); postTwo.setCover("testPostTwo.webp"); postTwo.setReadTime(25); postTwo.setSlug("test-post-two"); postTwo.setPublicationDate(LocalDateTime.now()); PostDTO postThree = new PostDTO(); postThree.setId(3L); postThree.setDateCreated(LocalDateTime.now()); postThree.setDateUpdated(LocalDateTime.now()); postThree.setPostTitle("Test post three title"); postThree.setContent("Test post three content"); postThree.setCover("testPostThree.webp"); postThree.setReadTime(5); postThree.setSlug("post-three"); return Arrays.asList(postOne, postTwo, postThree); }
public static List<PostDTO> getPostsDTOs(){ PostDTO postOne = new PostDTO(); postOne.setDateCreated(LocalDateTime.now()); postOne.setDateUpdated(LocalDateTime.now()); postOne.setTitle("Test post one title"); postOne.setContent("Test post one content"); postOne.setCover("testPostOne.webp"); postOne.setReadTime(10); postOne.setSlug("test-post-one"); postOne.setPublicationDate(LocalDateTime.now()); PostDTO postTwo = new PostDTO(); postTwo.setDateCreated(LocalDateTime.now()); postTwo.setDateUpdated(LocalDateTime.now()); postTwo.setTitle("Test post two title"); postTwo.setContent("Test post two content"); postTwo.setCover("testPostTwo.webp"); postTwo.setReadTime(25); postTwo.setSlug("test-post-two"); postTwo.setPublicationDate(LocalDateTime.now()); PostDTO postThree = new PostDTO(); postThree.setDateCreated(LocalDateTime.now()); postThree.setDateUpdated(LocalDateTime.now()); postThree.setTitle("Test post three title"); postThree.setContent("Test post three content"); postThree.setCover("testPostThree.webp"); postThree.setReadTime(5); postThree.setSlug("post-three"); return Arrays.asList(postOne, postTwo, postThree); }
322
public void newGame(){ text = scanner.nextLine(); hands = text.split("\\s+"); for (int i = 0; i < 5; i++) { Card card = new Card(hands[i]); compCards[i] = card; } compHand = new Hand(compCards); for (int i = 5, j = 0; i < 10; i++, j++) { Card card = new Card(hands[i]); oppCards[j] = card; } oppHand = new Hand(oppCards); for (int i = 10, j = 0; i < 13; i++, j++) { Card card = new Card(hands[i]); swapCards[j] = card; System.out.println(card.toString()); } }
public void newGame(){ text = scanner.nextLine(); hands = text.split("\\s+"); for (int i = 0; i < 5; i++) { Card card = new Card(hands[i]); compCards[i] = card; } compHand = new Hand(compCards); for (int i = 5, j = 0; i < 10; i++, j++) { Card card = new Card(hands[i]); oppCards[j] = card; } oppHand = new Hand(oppCards); for (int i = 10, j = 0; i < 13; i++, j++) { Card card = new Card(hands[i]); swapCards[j] = card; } }
323
private boolean isValidSPCFile() throws IOException{ raf.seek(0); final String fileHeader = readStuff(HEADER_OFFSET, HEADER_LENGTH).trim().substring(0, CORRECT_HEADER.length()); return (CORRECT_HEADER.equalsIgnoreCase(fileHeader)); }
private boolean isValidSPCFile() throws IOException{ final String fileHeader = readStuff(HEADER_OFFSET, HEADER_LENGTH).trim().substring(0, CORRECT_HEADER.length()); return (CORRECT_HEADER.equalsIgnoreCase(fileHeader)); }
324
public void setUp() throws Exception{ customerAccount = new CustomerAccount(new AccountRule() { public boolean withdrawPermitted(Double resultingAccountBalance) { return false; } }); }
public void setUp() throws Exception{ customerAccount = new CustomerAccount(new CustomerAccountRule()); }
325
public Mono<RecipeCommand> saveRecipeCommand(RecipeCommand command){ if (command == null) return null; Recipe availableRecipe = recipeRepository.findById(command.getId()).block(); if (availableRecipe == null) { return recipeRepository.save(recipeCommandToRecipe.convert(command)).map(recipeToRecipeCommand::convert); } availableRecipe.setUrl(command.getUrl()); availableRecipe.setServings(command.getServings()); availableRecipe.setCookTime(command.getCookTime()); availableRecipe.setDescription(command.getDescription()); availableRecipe.setDifficulty(command.getDifficulty()); availableRecipe.setDirections(command.getDirections()); availableRecipe.setPrepTime(command.getPrepTime()); availableRecipe.setSource(command.getSource()); availableRecipe.setNotes(notesCommandToNotes.convert(command.getNotes())); command.getCategories().forEach(categoryCommand -> { availableRecipe.getCategories().add(categoryCommandToCategory.convert(categoryCommand)); }); return recipeRepository.save(availableRecipe).map(recipeToRecipeCommand::convert); }
public Mono<RecipeCommand> saveRecipeCommand(RecipeCommand command){ if (command == null) return null; Recipe availableRecipe = recipeRepository.findById(command.getId()).block(); if (availableRecipe == null) { return recipeRepository.save(recipeCommandToRecipe.convert(command)).map(recipeToRecipeCommand::convert); } availableRecipe.setUrl(command.getUrl()); availableRecipe.setServings(command.getServings()); availableRecipe.setCookTime(command.getCookTime()); availableRecipe.setDescription(command.getDescription()); availableRecipe.setDifficulty(command.getDifficulty()); availableRecipe.setDirections(command.getDirections()); availableRecipe.setPrepTime(command.getPrepTime()); availableRecipe.setSource(command.getSource()); availableRecipe.setNotes(notesCommandToNotes.convert(command.getNotes())); availableRecipe.setCategories(command.getCategories().stream().map(categoryCommandToCategory::convert).collect(Collectors.toSet())); return recipeRepository.save(availableRecipe).map(recipeToRecipeCommand::convert); }
326
public T remove(int index){ if (!indexCapacity(index)) { throw new ArrayListIndexOutOfBoundsException("Index are not exist," + " please input right index"); } T value = arrayData[index]; if (indexCapacity(index) && ensureCapacity()) { arrayCopyRemove(index); size--; } else if ((index == size && !ensureCapacity()) || (indexCapacity(index) && !ensureCapacity())) { grow(); arrayCopyRemove(index); size--; } return value; }
public T remove(int index){ if (index < 0 || index >= size) { throw new ArrayListIndexOutOfBoundsException("Index are not exist," + " please input right index"); } T value = arrayData[index]; arrayCopyRemove(index); return value; }
327
public Student updateStudentDetails(Integer studentId, String name, String address, String gender, Date dob, Integer age){ Student student = new Student(); student.setStudentId(studentId); student.setName(name); student.setAge(age); student.setAddress(address); student.setGender(gender); student.setDob(dob); return studentRepository.updateStudentDetails(student); }
public Student updateStudentDetails(Student student){ Boolean isValid = validateStudent(student); if (isValid) { return studentRepository.updateStudentDetails(student); } return null; }
328
private void cleanupEncodeSlotIfNecessary(){ if (encodeSlot != NO_SLOT) { bufferPool.release(encodeSlot); encodeSlot = NO_SLOT; encodeSlotOffset = 0; encodeSlotMarkOffset = 0; if (Http2Configuration.DEBUG_HTTP2_BUDGETS) { System.out.format("[%d] [cleanupEncodeSlotIfNecessary] [0x%016x] [0x%016x] encode encodeSlotOffset => %d\n", System.nanoTime(), 0, budgetId, encodeSlotOffset); } } }
private void cleanupEncodeSlotIfNecessary(){ if (encodeSlot != NO_SLOT) { bufferPool.release(encodeSlot); encodeSlot = NO_SLOT; encodeSlotOffset = 0; if (Http2Configuration.DEBUG_HTTP2_BUDGETS) { System.out.format("[%d] [cleanupEncodeSlotIfNecessary] [0x%016x] [0x%016x] encode encodeSlotOffset => %d\n", System.nanoTime(), 0, budgetId, encodeSlotOffset); } } }
329
public ArrayList<Room> findAll(){ try { float randomDelay = mySqlDelay(); String query = "select rooms.id,rooms.number,rooms.floor,rooms.price,rooms.description,rooms_type.roomType,rooms_type.maxCapacity,rooms_type.roomSize,SLEEP(?)" + " from rooms" + " left join rooms_type" + " on rooms.room_type = rooms_type.id"; ArrayList<Room> rooms = jdbcTemplate.query(query, new Object[] { randomDelay }, new ResultSetExtractor<ArrayList<Room>>() { public ArrayList<Room> extractData(ResultSet rs) throws SQLException, DataAccessException { ArrayList<Room> result = extractDataFromReultSet(rs); return result; } }); return rooms; } catch (Exception ex) { return null; } }
public ArrayList<Room> findAll(){ try { float randomDelay = mySqlDelay(); String query = "select rooms.id,rooms.number,rooms.floor,rooms.price,rooms.description,rooms_type.roomType,rooms_type.maxCapacity,rooms_type.roomSize,SLEEP(?)" + " from rooms" + " left join rooms_type" + " on rooms.room_type = rooms_type.id"; return jdbcTemplate.query(query, new Object[] { randomDelay }, this::extractDataFromReultSet); } catch (Exception ex) { return null; } }
330
public Builder uris(final String uris){ assert (uris != null); assert (!uris.equals("")); assert (uris.split(",").length <= 100); return setQueryParameter("uris", uris); }
public Builder uris(final String uris){ assertHasAndNotNull(uris); assert (uris.split(",").length <= 100); return setQueryParameter("uris", uris); }
331
public Map<String, Variable> detachVariables(boolean deep){ Map<String, Variable> detached = new HashMap(vars.size()); vars.forEach((k, v) -> { switch(v.type) { case JS_FUNCTION: JsFunction jf = new JsFunction(v.getValue()); v = new Variable(jf); break; case MAP: case LIST: if (deep) { Object o = recurseAndDetachAndDeepClone(v.getValue()); v = new Variable(o); } else { recurseAndDetach(v.getValue()); } break; default: } detached.put(k, v); }); return detached; }
protected Map<String, Variable> detachVariables(){ Set<Object> seen = Collections.newSetFromMap(new IdentityHashMap()); Map<String, Variable> detached = new HashMap(vars.size()); vars.forEach((k, v) -> { switch(v.type) { case JS_FUNCTION: JsFunction jf = new JsFunction(v.getValue()); v = new Variable(jf); break; case MAP: case LIST: Object o = recurseAndDetachAndDeepClone(v.getValue(), seen); v = new Variable(o); break; default: } detached.put(k, v); }); return detached; }
332
public CustomerBill generateBill(CustomerBill bill){ bill.setFinalBill(ds.getFinalDiscountPrice(bill)); return bill; }
public void generateBill(CustomerBill bill){ bill.setFinalBill(ds.getFinalPrice(bill.getBasicBill(), bill.getCustomer().getType())); }
333
public void run(String testName, boolean conformingMapping){ try { String directoryName = this.mapTestCaseName.get(testName); String configurationDirectory = mappingDirectory + File.separator; String configurationFile = testName + ".morph.properties"; MorphRDBRunnerFactory runnerFactory = new MorphRDBRunnerFactory(); MorphBaseRunner runner = runnerFactory.createRunner(configurationDirectory, configurationFile); runner.run(); System.out.println("------" + testName + " DONE------"); assertTrue(conformingMapping); } catch (Exception e) { e.printStackTrace(); System.out.println("Error : " + e.getMessage()); System.out.println("------" + testName + " FAILED------\n\n"); assertTrue(e.getMessage(), !conformingMapping); } }
public void run(String testName, boolean conformingMapping){ try { String configurationDirectory = mappingDirectory + File.separator; String configurationFile = testName + ".morph.properties"; MorphRDBRunnerFactory runnerFactory = new MorphRDBRunnerFactory(); MorphBaseRunner runner = runnerFactory.createRunner(configurationDirectory, configurationFile); runner.run(); System.out.println("------" + testName + " DONE------"); assertTrue(conformingMapping); } catch (Exception e) { e.printStackTrace(); System.out.println("Error : " + e.getMessage()); System.out.println("------" + testName + " FAILED------\n\n"); assertTrue(e.getMessage(), !conformingMapping); } }
334
public FastestSlowestWinnerProducerDto fastestSlowestWinnerProducer(){ List<Producer> prod = producerRepository.findAll(); System.out.println("JOEL: " + prod.stream().filter(p -> p.getName().equalsIgnoreCase("Joel Silver")).collect(Collectors.toList())); prod.stream().forEach(p -> p.setIndicateds(p.getIndicateds().stream().filter(i -> i.getWinner().equalsIgnoreCase("yes")).collect(Collectors.toList()))); List<Producer> prodWinners = new ArrayList<Producer>(); prod.stream().filter(p -> p.getIndicateds().size() > 1).forEach(p -> prodWinners.add(p)); HashMap<Integer, List<ProducerIntervalDto>> intervalMap = new HashMap<Integer, List<ProducerIntervalDto>>(); prodWinners.forEach(p -> p.getIndicateds().stream().iterator().forEachRemaining(i1 -> this.difference(p, i1, intervalMap))); return new FastestSlowestWinnerProducerDto(intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).min().getAsInt()), intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).max().getAsInt())); }
public FastestSlowestWinnerProducerDto fastestSlowestWinnerProducer(){ List<Producer> prod = producerRepository.findAll(); prod.stream().forEach(p -> p.setIndicateds(p.getIndicateds().stream().filter(i -> i.getWinner().equalsIgnoreCase(WinnerEnum.YES.getWinner())).collect(Collectors.toList()))); List<Producer> prodWinners = new ArrayList<Producer>(); prod.stream().filter(p -> p.getIndicateds().size() > 1).forEach(p -> prodWinners.add(p)); HashMap<Integer, List<ProducerIntervalDto>> intervalMap = new HashMap<Integer, List<ProducerIntervalDto>>(); prodWinners.forEach(p -> p.getIndicateds().stream().iterator().forEachRemaining(i1 -> this.calculateInterval(p, i1, intervalMap))); return new FastestSlowestWinnerProducerDto(intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).min().getAsInt()), intervalMap.get(intervalMap.keySet().stream().mapToInt(t -> t).max().getAsInt())); }
335
private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException("got insane sequence number"); } int offset = seqNum * DATA_PER_FULL_PACKET_WITH_SEQUENCE_NUM * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException("received more data than expected"); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { if (!checkAllReceived()) { finished |= retransmitMissingSequences(); } else { finished = true; } } }
private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException("got insane sequence number"); } int offset = seqNum * DATA_WORDS_PER_PACKET * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException("received more data than expected"); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { finished = retransmitMissingSequences(); } }
336
private String doConvert(ILoggingEvent event){ boolean maskMeRequired = false; Object[] argumentArray = event.getArgumentArray(); if (argumentArray != null && argumentArray.length > 0) { for (Object obj : argumentArray) { MaskMe annotation = obj.getClass().getAnnotation(MaskMe.class); if (annotation != null) { maskMeRequired = true; break; } } if (maskMeRequired) { List<Object> maskedObjs = mask(argumentArray); return MessageFormatter.arrayFormat(event.getMessage(), maskedObjs.toArray()).getMessage(); } } return event.getFormattedMessage(); }
private String doConvert(ILoggingEvent event){ boolean maskMeRequired = false; Object[] argumentArray = event.getArgumentArray(); if (argumentArray != null && argumentArray.length > 0) { for (Object obj : argumentArray) { if (obj.getClass().isAnnotationPresent(Mask.class)) { maskMeRequired = true; break; } } if (maskMeRequired) { val maskedObjs = mask(argumentArray); return MessageFormatter.arrayFormat(event.getMessage(), maskedObjs.toArray()).getMessage(); } } return event.getFormattedMessage(); }
337
public static int[] findOrder(int numCourses, int[][] prerequisites){ final Deque<Integer> courses = new ArrayDeque<>(numCourses); final COLOR[] discoveryStatus = new COLOR[numCourses]; for (int i = 0; i < numCourses; i++) discoveryStatus[i] = COLOR.WHITE; final Map<Integer, List<Integer>> adjList = new HashMap<>(); for (int[] edge : prerequisites) adjList.merge(edge[1], new ArrayList<>(Arrays.asList(edge[0])), (l1, l2) -> { l1.addAll(l2); return l1; }); for (int u = 0; u < numCourses; u++) { if (discoveryStatus[u] == COLOR.WHITE) { final boolean dependencyFound = findDependencies(u, courses, discoveryStatus, adjList); if (!dependencyFound) return new int[0]; } } final int[] coursesArr = new int[numCourses]; for (int i = 0; i < numCourses; i++) coursesArr[i] = courses.poll(); return coursesArr; }
public static int[] findOrder(int numCourses, int[][] prerequisites){ final Deque<Integer> courses = new ArrayDeque<>(numCourses); final COLOR[] discoveryStatus = new COLOR[numCourses]; for (int i = 0; i < numCourses; i++) discoveryStatus[i] = COLOR.WHITE; final Map<Integer, List<Integer>> adjList = new HashMap<>(); for (int[] edge : prerequisites) adjList.computeIfAbsent(edge[1], unused -> new ArrayList<>()).add(edge[0]); for (int u = 0; u < numCourses; u++) { if (discoveryStatus[u] == COLOR.WHITE) { final boolean dependencyFound = findDependencies(u, courses, discoveryStatus, adjList); if (!dependencyFound) return new int[0]; } } final int[] coursesArr = new int[numCourses]; for (int i = 0; i < numCourses; i++) coursesArr[i] = courses.poll(); return coursesArr; }
338
public Integer divide(Integer a, Integer b){ try { return a / b; } catch (Exception e) { System.out.println("*****Invalid Operation *****"); e.printStackTrace(); System.out.println("****************************"); return 0; } }
public Integer divide(Integer a, Integer b){ try { return a / b; } catch (Exception e) { e.printStackTrace(); return 0; } }
339
public Gender checkGenderByFullName(String name){ String[] split = name.split(" "); int femaleCounter = 0; int maleCounter = 0; for (String element : split) { if (checkIfNameExist(FEMALE_PATH, element)) { femaleCounter++; } else if (checkIfNameExist(MALE_PATH, element)) { maleCounter++; } } return estimateGender(femaleCounter, maleCounter); }
public Gender checkGenderByFullName(String name){ String[] split = name.split(" "); int femaleCounter = 0; int maleCounter = 0; for (String element : split) { if (checkIfNameExist(FEMALE_PATH, element)) femaleCounter++; else if (checkIfNameExist(MALE_PATH, element)) maleCounter++; } return estimateGender(femaleCounter, maleCounter); }
340
public void replaceBody(MilterContext context, byte[] body) throws MilterException{ int length; if (body.length > MILTER_CHUNK_SIZE) { length = MILTER_CHUNK_SIZE; } else { length = body.length; } int offset = 0; while (offset < body.length) { MilterPacket packet = MilterPacket.builder().command(SMFIR_REPLBODY).payload(body, offset, length).build(); context.sendPacket(packet); offset += length; if (offset + length >= body.length) { length = body.length - offset; } } }
public void replaceBody(MilterContext context, byte[] body) throws MilterException{ int length = Math.min(body.length, MILTER_CHUNK_SIZE); int offset = 0; while (offset < body.length) { MilterPacket packet = MilterPacket.builder().command(SMFIR_REPLBODY).payload(body, offset, length).build(); context.sendPacket(packet); offset += length; if (offset + length >= body.length) { length = body.length - offset; } } }
341
public void givenUserWhenPostUserThenUserIsCreatedTest(){ user = UserTestDataGenerator.generateUser(); ApiResponse actualApiResponse = given().contentType("application/json").body(user).when().post("user").then().statusCode(200).extract().as(ApiResponse.class); ApiResponse expectedApiResponse = new ApiResponse(); expectedApiResponse.setCode(200); expectedApiResponse.setType("unknown"); expectedApiResponse.setMessage(user.getId().toString()); Assertions.assertThat(actualApiResponse).describedAs("Send User was different than received by API").usingRecursiveComparison().isEqualTo(expectedApiResponse); }
public void givenUserWhenPostUserThenUserIsCreatedTest(){ user = UserTestDataGenerator.generateUser(); ApiResponse actualApiResponse = given().contentType("application/json").body(user).when().post("user").then().statusCode(200).extract().as(ApiResponse.class); ApiResponse expectedApiResponse = ApiResponse.builder().code(HttpStatus.SC_OK).type("unknown").message(user.getId().toString()).build(); Assertions.assertThat(actualApiResponse).describedAs("Send User was different than received by API").usingRecursiveComparison().isEqualTo(expectedApiResponse); }
342
public Optional<InterviewResult> create(Map<String, String> fields){ Optional<InterviewResult> result = Optional.empty(); if (isInterviewResultFormValid(fields)) { byte rating = Byte.parseByte(fields.get(RequestParameter.INTERVIEW_RESULT_RATING)); String comment = fields.get(RequestParameter.INTERVIEW_RESULT_COMMENT); InterviewResult interviewResult = new InterviewResult(rating, comment); result = Optional.of(interviewResult); } return result; }
public Optional<InterviewResult> create(Map<String, String> fields){ Optional<InterviewResult> result = Optional.empty(); if (isInterviewResultFormValid(fields)) { byte rating = Byte.parseByte(fields.get(RequestParameter.INTERVIEW_RESULT_RATING)); String comment = fields.get(RequestParameter.INTERVIEW_RESULT_COMMENT); result = Optional.of(new InterviewResult(rating, comment)); } return result; }
343
double evaluate(JavaRDD<Vector> evalData){ double totalSquaredDist = 0.0; for (ClusterMetric metric : fetchClusterMetrics(evalData).values().collect()) { totalSquaredDist += metric.getSumSquaredDist(); } return totalSquaredDist; }
double evaluate(JavaRDD<Vector> evalData){ return fetchClusterMetrics(evalData).values().mapToDouble(ClusterMetric::getSumSquaredDist).sum(); }
344
public void delete(int i){ validateIndex(i); if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue"); int index = qp[i]; exch(index, n--); swim(index); sink(index); keys[i] = null; qp[i] = -1; }
public void delete(int i){ validateIndex(i); noSuchElement(!contains(i), "index is not in the priority queue"); int index = qp[i]; exch(index, n--); swim(index); sink(index); keys[i] = null; qp[i] = -1; }
345
protected Object invokeMethod(Object object, Method method, Object... params){ String failMessage = "Could not invoke the method '" + method.getName() + "' in the class " + method.getDeclaringClass().getSimpleName() + BECAUSE; try { return method.invoke(object, params); } catch (@SuppressWarnings("unused") IllegalAccessException iae) { fail(failMessage + " access to the method was denied. Make sure to check the modifiers of the method."); } catch (@SuppressWarnings("unused") IllegalArgumentException iae) { fail(failMessage + " the parameters are not implemented right. Make sure to check the parameters of the method"); } catch (InvocationTargetException e) { fail(failMessage + " of an exception within the method: " + e.getCause()); } return null; }
protected Object invokeMethod(Object object, Method method, Object... params){ String failMessage = "Could not invoke the method '" + method.getName() + "' in the class " + method.getDeclaringClass().getSimpleName() + BECAUSE; try { invokeMethodRethrowing(object, method, params); } catch (Throwable e) { fail(failMessage + " of an exception within the method: " + e); } return null; }
346
public void set(T value, int index){ if (index < size && index >= 0) { elements[index] = value; } else { throw new ArrayIndexOutOfBoundsException(); } }
public void set(T value, int index){ if (index >= size || index < 0) { throw new ArrayIndexOutOfBoundsException(); } elements[index] = value; }
347
public void testUpdateViewTime(){ try { List<User> userList = userService.getUers(); User user = new User("[email protected]", "nobody"); user.setId(userList.size() + 10); User userRe = userService.updateLastviewTime(user); log.info("----- userRe : " + userRe); Assert.fail("Can not update the unregistered user"); } catch (NewsfeedException e) { Assert.assertTrue(e.getMessage().contains("Not Found")); } try { User user = userService.createUser("[email protected]", "abcde"); User userRe = userService.updateLastviewTime(user); Assert.assertEquals(user.getId(), userRe.getId()); Assert.assertEquals(user.getLastViewTime(), userRe.getLastViewTime()); Assert.assertEquals(null, userService.getUser(user.getId()).getLastViewTime()); } catch (NewsfeedException e) { Assert.fail("Fail to update"); } }
public void testUpdateViewTime(){ try { List<User> userList = userService.getUsers(); User user = new User("[email protected]", "nobody"); user.setId(userList.size() + 10); User userRe = userService.updateLastviewTime(user.getId(), System.currentTimeMillis()); log.info("----- userRe : " + userRe); Assert.fail("Can not update the unregistered user"); } catch (NewsfeedException e) { Assert.assertTrue(e.getMessage().contains("Not Found")); } try { User user = userService.createUser("[email protected]", "abcde"); User userRe = userService.updateLastviewTime(user.getId(), 0); Assert.assertEquals(user.getId(), userRe.getId()); Assert.assertEquals(0, userService.getUser(user.getId()).getLastviewTime().getTime()); } catch (NewsfeedException e) { Assert.fail("Fail to update"); } }
348
public void setValue(Object object, String fieldName, Object value){ if (object == null) { throw new NullPointerException("provided object is null"); } if (fieldName == null) { throw new NullPointerException("provided field name is null"); } var objectType = object.getClass(); Field field = util.getFieldSafe(objectType, fieldName); if (field == null) { throw new FieldNotFoundException(String.format("field '%s'.'%s' is not found", objectType.getName(), fieldName)); } var fieldType = field.getType(); try { if (value == null) { field.setAccessible(true); field.set(object, null); } else { var valueType = value.getClass(); if (fieldType.isAssignableFrom(valueType)) { field.setAccessible(true); field.set(object, value); } else { throw new ValueNotAssignException(String.format("field '%s' with class '%s' can not be assign with instance which class '%s'", fieldName, fieldType.getName(), valueType.getName())); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
public void setValue(Object object, String fieldName, Object value){ if (object == null) { throw new NullPointerException("provided object is null"); } if (fieldName == null) { throw new NullPointerException("provided field name is null"); } var objectType = object.getClass(); Field field = util.getFieldSafe(objectType, fieldName); if (field == null) { throw new FieldNotFoundException(String.format("field '%s'.'%s' is not found", objectType.getName(), fieldName)); } var fieldType = field.getType(); try { field.setAccessible(true); if (value == null) { field.set(object, null); } else { var valueType = value.getClass(); if (fieldType.isAssignableFrom(valueType)) { field.set(object, value); } else { throw new ValueNotAssignException(String.format("field '%s' with class '%s' can not be assign with instance which class '%s'", fieldName, fieldType.getName(), valueType.getName())); } } } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
349
public org.jailbreak.api.representations.Representations.Donation.DonationsFilters buildPartial(){ org.jailbreak.api.representations.Representations.Donation.DonationsFilters result = new org.jailbreak.api.representations.Representations.Donation.DonationsFilters(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.teamId_ = teamId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.sinceTime_ = sinceTime_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.limit_ = limit_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.type_ = type_; result.bitField0_ = to_bitField0_; onBuilt(); return result; }
public org.jailbreak.api.representations.Representations.Donation.DonationsFilters buildPartial(){ org.jailbreak.api.representations.Representations.Donation.DonationsFilters result = new org.jailbreak.api.representations.Representations.Donation.DonationsFilters(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.teamId_ = teamId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.sinceTime_ = sinceTime_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.type_ = type_; result.bitField0_ = to_bitField0_; onBuilt(); return result; }
350
public void testSelectRequest_Default(){ UriInfo uriInfo = mock(UriInfo.class); @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = mock(MultivaluedMap.class); when(uriInfo.getQueryParameters()).thenReturn(params); ResourceEntity<E1> resourceEntity = parser.parseSelect(getLrEntity(E1.class), uriInfo, null); assertNotNull(resourceEntity); assertTrue(resourceEntity.isIdIncluded()); assertEquals(3, resourceEntity.getAttributes().size()); assertTrue(resourceEntity.getChildren().isEmpty()); }
public void testSelectRequest_Default(){ @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = mock(MultivaluedMap.class); ResourceEntity<E1> resourceEntity = parser.parseSelect(getLrEntity(E1.class), params, null); assertNotNull(resourceEntity); assertTrue(resourceEntity.isIdIncluded()); assertEquals(3, resourceEntity.getAttributes().size()); assertTrue(resourceEntity.getChildren().isEmpty()); }
351
public SCCSignature sign(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getSigning(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { switch(sccalgorithmID) { case ECDSA_512: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_512); case ECDSA_256: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_256); case ECDSA_384: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_384); default: break; } } } } else { switch(usedAlgorithm) { case ECDSA_512: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_512); case ECDSA_256: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_256); case ECDSA_384: return SecureCryptoConfig.createSignMessage(plaintext, key, AlgorithmID.ECDSA_384); default: break; } } } else { throw new SCCException("The used SCCKey has the wrong KeyType for this use case. ", new InvalidKeyException()); } throw new SCCException(standardError, new CoseException(null)); }
public SCCSignature sign(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getSigning(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { return decideForAlgoSigning(sccalgorithmID, key, plaintext); } } } else { return decideForAlgoSigning(usedAlgorithm, key, plaintext); } } else { throw new SCCException("The used SCCKey has the wrong KeyType for this use case. ", new InvalidKeyException()); } throw new SCCException(standardError, new CoseException(null)); }
352
protected String getSetterName(MetaField f){ StringBuffer methname = new StringBuffer(); methname.append("set"); int c = f.getName().charAt(0); if (c >= 'a' && c <= 'z') { c = c - ('a' - 'A'); } methname.append((char) c); methname.append(f.getName().substring(1)); return methname.toString(); }
protected String getSetterName(MetaField f){ StringBuilder b = new StringBuilder(); b.append("set"); uppercase(b, f.getName()); return b.toString(); }
353
public void cancelQuery(){ SwingUtilities.invokeLater(new Runnable() { public void run() { if (query_finished != 'f') { query_finished = 'c'; block_util.unblock(); } } }); }
public void cancelQuery(){ SwingUtilities.invokeLater(() -> { if (query_finished != 'f') { query_finished = 'c'; block_util.unblock(); } }); }
354
private int benchJavaMath(){ long timeout = BENCH_TIME; long time = System.currentTimeMillis() + (1000 * timeout); double x, y, val, rate; int count = 0; Random rnd = new Random(); while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; return count; }
private int benchJavaMath(){ long time = System.currentTimeMillis() + (1000 * BENCH_TIME); double x, y, val, rate; int count = 0; Random rnd = new Random(); while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } return count; }
355
public String validateAndRegisterNewUser(UserDTO userDTO, BindingResult result) throws MessagingException{ if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); for (ObjectError error : errors) { log.info("Can't register new user, errors occurred during filling form {}", error); } return "register-user-form"; } else { Authorities authority = new Authorities(); User user = createUserForm(userDTO, authority); userService.saveUser(user); sendCredentialsMail(userDTO); log.info("created new user {} sent email on address {}", userDTO.getUsername(), userDTO.getEmail()); return "register-success-page"; } }
public String validateAndRegisterNewUser(UserDTO userDTO, BindingResult result) throws MessagingException{ if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); for (ObjectError error : errors) { log.info("Can't register new user, errors occurred during filling form {}", error); } return "register-user-form"; } else { userService.saveUser(createUserForm(userDTO, new Authorities())); sendCredentialsMail(userDTO); log.info("created new user {} sent email on address {}", userDTO.getUsername(), userDTO.getEmail()); return "register-success-page"; } }
356
public void save(TripRequest tripRequest) throws SQLException, NamingException{ Context ctx = new InitialContext(); Context envContext = (Context) ctx.lookup("java:comp/env"); DataSource dataSource = (DataSource) envContext.lookup("jdbc/TestDB"); Connection con = null; try { con = dataSource.getConnection(); PreparedStatement insertTripRequest = con.prepareStatement("INSERT INTO trip_requests" + "(trip_id, car_id, message, date_of_creation) VALUES (?, ?, ?, NOW())"); insertTripRequest.setLong(1, tripRequest.getTripInfo().getId()); insertTripRequest.setLong(2, tripRequest.getCarInfo().getId()); if (tripRequest.getMessage() != null) { insertTripRequest.setString(3, tripRequest.getMessage()); } else { insertTripRequest.setNull(3, Types.VARCHAR); } insertTripRequest.execute(); insertTripRequest.close(); } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }
public void save(TripRequest tripRequest) throws SQLException, NamingException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement insertTripRequest = con.prepareStatement("INSERT INTO trip_requests" + "(trip_id, car_id, message, date_of_creation) VALUES (?, ?, ?, NOW())"); insertTripRequest.setLong(1, tripRequest.getTripInfo().getId()); insertTripRequest.setLong(2, tripRequest.getCarInfo().getId()); if (tripRequest.getMessage() != null) { insertTripRequest.setString(3, tripRequest.getMessage()); } else { insertTripRequest.setNull(3, Types.VARCHAR); } insertTripRequest.execute(); insertTripRequest.close(); } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }
357
public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException{ Modification modification = Modification.newBuilder().setId(columnFamilyDesc.getNameAsString()).setCreate(tableAdapter2x.toColumnFamily(columnFamilyDesc)).build(); modifyColumns(tableName, columnFamilyDesc.getNameAsString(), "add", modification); }
public void addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamilyDesc) throws IOException{ modifyColumns(tableName, columnFamilyDesc.getNameAsString(), "add", ModifyTableBuilder.create().add(TableAdapter2x.toHColumnDescriptor(columnFamilyDesc))); }
358
public Place build(){ log.info("Creating place {}", CODE); Place p = new Place(); p.setName(CODE); p.setCode(CODE); PlaceBranch main = new PlaceBranch(); main.setPlace(p); main.setName("Shopping Multiplaza Casa Central"); main.setLatitude(-25.3167006); main.setLongitude(-57.572267); main.setImage("http://www.maxicambios.com.py/media/1044/asuncion_multiplaza.jpg"); main.setPhoneNumber("(021) 525105/8"); main.setSchedule("Lunes a Sábados: 8:00 a 21:00 Hs.\n" + "Domingos: 10:00 a 21:00 Hs."); main.setRemoteCode("0"); PlaceBranch cde = new PlaceBranch(); cde.setPlace(p); cde.setName("Casa Central CDE"); cde.setLatitude(-25.5083135); cde.setLongitude(-54.6384264); cde.setImage("http://www.maxicambios.com.py/media/1072/matriz_cde_original.jpg"); cde.setPhoneNumber("(061) 573106-574270-574295-509511/13"); cde.setSchedule("Lunes a viernes: 7:00 a 19:30 Hs. \n Sabados: 7:00 a 12:00 Hs."); cde.setRemoteCode("13"); p.setBranches(Arrays.asList(main, cde)); return p; }
public Place build(){ log.info("Creating place {}", CODE); Place place = new Place(); place.setName(CODE); place.setCode(CODE); PlaceBranch main = new PlaceBranch(); main.setName("Shopping Multiplaza Casa Central"); main.setLatitude(-25.3167006); main.setLongitude(-57.572267); main.setImage("http://www.maxicambios.com.py/media/1044/asuncion_multiplaza.jpg"); main.setPhoneNumber("(021) 525105/8"); main.setSchedule("Lunes a Sábados: 8:00 a 21:00 Hs.\n" + "Domingos: 10:00 a 21:00 Hs."); main.setRemoteCode("0"); PlaceBranch cde = new PlaceBranch(); cde.setName("Casa Central CDE"); cde.setLatitude(-25.5083135); cde.setLongitude(-54.6384264); cde.setImage("http://www.maxicambios.com.py/media/1072/matriz_cde_original.jpg"); cde.setPhoneNumber("(061) 573106-574270-574295-509511/13"); cde.setSchedule("Lunes a viernes: 7:00 a 19:30 Hs. \n Sabados: 7:00 a 12:00 Hs."); cde.setRemoteCode("13"); place.setBranches(Arrays.asList(main, cde)); return place; }
359
protected void createSchema(){ final Session session = configContext.getSession(); final List<Class<?>> manageEntities = configContext.getManageEntities().isEmpty() ? entityClasses : configContext.getManageEntities(); if (configContext.isForceSchemaGeneration()) { for (AbstractUDTClassProperty<?> x : getUdtClassProperties()) { final long udtCountForClass = entityProperties.stream().filter(entityProperty -> manageEntities.contains(entityProperty.entityClass)).flatMap(entityProperty -> entityProperty.allColumns.stream()).filter(property -> property.containsUDTProperty()).filter(property -> property.getUDTClassProperties().contains(x)).count(); if (udtCountForClass > 0) generateUDTAtRuntime(session, x); } final long viewCount = entityProperties.stream().filter(AbstractEntityProperty::isView).count(); if (viewCount > 0) { final Map<Class<?>, AbstractEntityProperty<?>> entityPropertiesMap = entityProperties.stream().filter(AbstractEntityProperty::isTable).collect(Collectors.toMap(x -> x.entityClass, x -> x)); entityProperties.stream().filter(AbstractEntityProperty::isView).map(x -> (AbstractViewProperty<?>) x).forEach(x -> x.setBaseClassProperty(entityPropertiesMap.get(x.getBaseEntityClass()))); } entityProperties.stream().filter(x -> manageEntities.contains(x.entityClass)).forEach(x -> generateSchemaAtRuntime(session, x)); } }
protected void createSchema(){ final Session session = configContext.getSession(); final List<Class<?>> manageEntities = configContext.getManageEntities().isEmpty() ? entityClasses : configContext.getManageEntities(); for (AbstractUDTClassProperty<?> x : getUdtClassProperties()) { final long udtCountForClass = entityProperties.stream().filter(entityProperty -> manageEntities.contains(entityProperty.entityClass)).flatMap(entityProperty -> entityProperty.allColumns.stream()).filter(property -> property.containsUDTProperty()).filter(property -> property.getUDTClassProperties().contains(x)).count(); if (udtCountForClass > 0) generateUDTAtRuntime(session, x); } final long viewCount = entityProperties.stream().filter(AbstractEntityProperty::isView).count(); if (viewCount > 0) { final Map<Class<?>, AbstractEntityProperty<?>> entityPropertiesMap = entityProperties.stream().filter(AbstractEntityProperty::isTable).collect(Collectors.toMap(x -> x.entityClass, x -> x)); entityProperties.stream().filter(AbstractEntityProperty::isView).map(x -> (AbstractViewProperty<?>) x).forEach(x -> x.setBaseClassProperty(entityPropertiesMap.get(x.getBaseEntityClass()))); } entityProperties.stream().filter(x -> manageEntities.contains(x.entityClass)).forEach(x -> generateSchemaAtRuntime(session, x)); }
360
public Map<String, Integer> deleteSpecificUsersInsideTheMap(String userName){ try { pCheckUser.setString(1, userName); pDeleteUser.setString(1, userName); Iterator<String> user = storeData.keySet().iterator(); ResultSet rs = pCheckUser.executeQuery(); if (rs.next()) while (user.hasNext()) if (user.next().contains(userName)) user.remove(); pDeleteUser.executeUpdate(); } catch (SQLException e) { System.out.println("Error: " + e); } return storeData; }
public Map<String, Integer> deleteSpecificUsersInsideTheMap(String userName){ try { pCheckUser.setString(1, userName); pDeleteUser.setString(1, userName); Iterator<String> user = storeData.keySet().iterator(); while (user.hasNext()) if (user.next().contains(userName)) user.remove(); pDeleteUser.executeUpdate(); } catch (SQLException e) { System.out.println("Error: " + e); } return storeData; }
361
public void setDelimiter(String delimiter){ Preconditions.checkTrue(Strings.isNotEmpty(delimiter), "delimiter is null or empty"); this.delimiter = ByteBuffer.wrap(delimiter.getBytes()); if (buf != null) { this.nextScanDelimiterStartPosition = buf.position(); } }
public void setDelimiter(String delimiter){ Preconditions.checkTrue(Strings.isNotEmpty(delimiter), "delimiter is null or empty"); this.delimiter = ByteBuffer.wrap(delimiter.getBytes()); }
362
public synchronized void init(){ String topic = messageAdapter.getDestination().getDestinationName(); int defaultSize = getPartitionNum(topic); if (poolSize == 0 || poolSize > defaultSize) setPoolSize(defaultSize); logger.info("Message receiver pool initializing. poolSize : " + poolSize + " config : " + props.toString()); consumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props)); Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); topicCountMap.put(topic, new Integer(poolSize)); VerifiableProperties verProps = new VerifiableProperties(props); @SuppressWarnings("unchecked") Decoder<K> keyDecoder = (Decoder<K>) RefleTool.newInstance(keyDecoderClass, verProps); @SuppressWarnings("unchecked") Decoder<V> valDecoder = (Decoder<V>) RefleTool.newInstance(valDecoderClass, verProps); Map<String, List<KafkaStream<K, V>>> consumerMap = consumer.createMessageStreams(topicCountMap, keyDecoder, valDecoder); List<KafkaStream<K, V>> streams = consumerMap.get(topic); int threadNumber = 0; for (final KafkaStream<K, V> stream : streams) { pool.submit(new ReceiverThread(stream, messageAdapter, threadNumber)); threadNumber++; } }
public synchronized void init(){ String topic = messageAdapter.getDestination().getDestinationName(); int defaultSize = getReceiver().getPartitionCount(topic); if (poolSize == 0 || poolSize > defaultSize) setPoolSize(defaultSize); logger.info("Message receiver pool initializing. poolSize : " + poolSize + " config : " + props.toString()); consumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props)); Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); topicCountMap.put(topic, new Integer(poolSize)); VerifiableProperties verProps = new VerifiableProperties(props); @SuppressWarnings("unchecked") Decoder<K> keyDecoder = (Decoder<K>) RefleTool.newInstance(keyDecoderClass, verProps); @SuppressWarnings("unchecked") Decoder<V> valDecoder = (Decoder<V>) RefleTool.newInstance(valDecoderClass, verProps); Map<String, List<KafkaStream<K, V>>> consumerMap = consumer.createMessageStreams(topicCountMap, keyDecoder, valDecoder); List<KafkaStream<K, V>> streams = consumerMap.get(topic); for (final KafkaStream<K, V> stream : streams) { pool.submit(new ReceiverThread(stream, messageAdapter)); } }
363
public void negativeEvaluteEqualsToString() throws Exception{ Map<String, Object> attributes = new HashMap<>(); attributes.put("name", "arshu"); String feature = "Name Feature"; String expression = "name == ganesh"; final GatingValidator validator = new GatingValidator(); Assert.assertFalse(validator.isAllowed(expression, feature, attributes)); }
public void negativeEvaluteEqualsToString() throws Exception{ Map<String, Object> attributes = new HashMap<>(); attributes.put("name", "arshu"); String feature = "Name Feature"; String expression = "name == ganesh"; Assert.assertFalse(validator.isAllowed(expression, feature, attributes)); }
364
public ResponseEntity<ResponseDTO<UserDTO>> create(@RequestBody UserRequestDTO userRequestDto){ ResponseDTO<UserDTO> response = new ResponseDTO<UserDTO>(); User user = new User(); try { user = userRequestDto.toUser(); ResponseDTO<User> userResult = this.userService.save(user); if (userResult.getData() != null) { UserDTO userDTO = new UserDTO(); userDTO.copyFrom(userResult.getData()); response.setData(userDTO); } response.setErrorMessage(userResult.getErrorMessage()); } catch (IllegalArgumentException e) { response.setErrorMessage(MessageConst.ERROR_ROLE_INVALID); } return new ResponseEntity<ResponseDTO<UserDTO>>(response, HttpStatus.OK); }
public ResponseEntity<ResponseDTO<Boolean>> create(@RequestBody UserRequestDTO userRequestDto){ ResponseDTO<Boolean> response = new ResponseDTO<Boolean>(); try { User user = userRequestDto.toUser(); ResponseDTO<Boolean> userResult = this.userService.save(user); if (userResult.getData() != null) { response.setData(userResult.getData()); } response.setErrorMessage(userResult.getErrorMessage()); } catch (IllegalArgumentException e) { response.setErrorMessage(MessageConst.ERROR_ROLE_INVALID); } return new ResponseEntity<ResponseDTO<Boolean>>(response, HttpStatus.OK); }
365
final JsonParser createJsonParser(final Object input) throws IOException, NoSuchAlgorithmException{ final JsonFactory f = new JsonFactory(); JsonParser jp = null; InputStream my_is = null; if (input instanceof String) { my_is = new ByteArrayInputStream(((String) input).getBytes(StandardCharsets.UTF_8)); } else if (input instanceof File) { my_is = new FileInputStream((File) input); } else if (input instanceof URL) { my_is = ((URL) input).openStream(); } else if (input instanceof InputStream) { my_is = (InputStream) input; } else { throw new IllegalStateException("cx parser does not know how to handle input of type " + input.getClass()); } if (_calculate_md5_checksum) { _md = MessageDigest.getInstance(CxioUtil.MD5); my_is = new DigestInputStream(my_is, _md); } else { _md = null; } jp = f.createParser(my_is); return jp; }
final JsonParser createJsonParser(final Object input) throws IOException{ final JsonFactory f = new JsonFactory(); JsonParser jp = null; InputStream my_is = null; if (input instanceof String) { my_is = new ByteArrayInputStream(((String) input).getBytes(StandardCharsets.UTF_8)); } else if (input instanceof File) { my_is = new FileInputStream((File) input); } else if (input instanceof URL) { my_is = ((URL) input).openStream(); } else if (input instanceof InputStream) { my_is = (InputStream) input; } else { throw new IllegalStateException("cx parser does not know how to handle input of type " + input.getClass()); } jp = f.createParser(my_is); return jp; }
366
public List allElements(){ ArrayList elems = new ArrayList(); for (int i = 0; i < elements.size(); ++i) { Object ob = elements.get(i); if (ob instanceof Operator) { } else if (ob instanceof FunctionDef) { Expression[] params = ((FunctionDef) ob).getParameters(); for (int n = 0; n < params.length; ++n) { elems.addAll(params[n].allElements()); } } else if (ob instanceof TObject) { TObject tob = (TObject) ob; if (tob.getTType() instanceof TArrayType) { Expression[] exp_list = (Expression[]) tob.getObject(); for (int n = 0; n < exp_list.length; ++n) { elems.addAll(exp_list[n].allElements()); } } else { elems.add(ob); } } else { elems.add(ob); } } return elems; }
public List allElements(){ ArrayList elems = new ArrayList(); for (Object ob : elements) { if (ob instanceof Operator) { } else if (ob instanceof FunctionDef) { Expression[] params = ((FunctionDef) ob).getParameters(); for (Expression param : params) { elems.addAll(param.allElements()); } } else if (ob instanceof TObject) { TObject tob = (TObject) ob; if (tob.getTType() instanceof TArrayType) { Expression[] exp_list = (Expression[]) tob.getObject(); for (Expression expression : exp_list) { elems.addAll(expression.allElements()); } } else { elems.add(ob); } } else { elems.add(ob); } } return elems; }
367
public HamtNode<K, V> assign(@Nonnull CollisionMap<K, V> collisionMap, int hashCode, @Nonnull K hashKey, @Nullable V newValue){ final int thisHashCode = this.hashCode; final K thisKey = key; final V thisValue = this.value; if (thisHashCode == hashCode) { if (thisKey.equals(hashKey)) { if (newValue == thisValue) { return this; } else { return new HamtSingleKeyLeafNode<>(hashCode, thisKey, newValue); } } else { final CollisionMap.Node thisNode = collisionMap.update(collisionMap.emptyNode(), thisKey, thisValue); return new HamtMultiKeyLeafNode<>(hashCode, collisionMap.update(thisNode, hashKey, newValue)); } } else { final CollisionMap.Node thisNode = collisionMap.update(collisionMap.emptyNode(), thisKey, thisValue); final HamtNode<K, V> expanded = HamtBranchNode.forLeafExpansion(collisionMap, thisHashCode, thisNode); return expanded.assign(collisionMap, hashCode, hashKey, newValue); } }
public HamtNode<K, V> assign(@Nonnull CollisionMap<K, V> collisionMap, int hashCode, @Nonnull K hashKey, @Nullable V newValue){ final int thisHashCode = this.hashCode; final K thisKey = this.key; final V thisValue = this.value; if (thisHashCode == hashCode) { if (thisKey.equals(hashKey)) { if (newValue == thisValue) { return this; } else { return new HamtSingleKeyLeafNode<>(hashCode, thisKey, newValue); } } else { final CollisionMap.Node thisNode = collisionMap.single(thisKey, thisValue); return new HamtMultiKeyLeafNode<>(hashCode, collisionMap.update(thisNode, hashKey, newValue)); } } else { final HamtNode<K, V> expanded = HamtBranchNode.forLeafExpansion(collisionMap, thisHashCode, thisKey, thisValue); return expanded.assign(collisionMap, hashCode, hashKey, newValue); } }
368
public TranslationResult visit(final SentenceMeatConjunction node, final FrVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final ConceptBookEntry conceptBookEntry = this.frTranslator.getConceptBook().get(node.getConjunction().getConcept()); final List<TranslationTarget> defaultTargets = conceptBookEntry.getDefaultTargets(Language.FR); if (defaultTargets.isEmpty()) { result.setTranslation(conceptBookEntry.getConceptPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? ", " : "", defaultTargets.get(0).getMainPhrase())); } else { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? " " : "", defaultTargets.get(0).getMainPhrase())); } return result; }
public TranslationResult visit(final SentenceMeatConjunction node, final FrVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final TranslationTarget conjunctionTarget = this.frTranslator.getFirstDefaultTarget(node.getConjunction().getConcept()); if (",".equals(conjunctionTarget.getMainPhrase())) { result.setTranslation(conjunctionTarget.getMainPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? ", " : "", conjunctionTarget.getMainPhrase())); } else { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? " " : "", conjunctionTarget.getMainPhrase())); } return result; }
369
public void testBusinessKeyDboEquals(){ businessKeyDbo11.setBusinessKey(1L); businessKeyDbo12.setBusinessKey(2L); businessKeyDbo21.setBusinessKey(1L); surrogateKeyDbo11.setSurrogateKey(1L); surrogateKeyDbo12.setSurrogateKey(2L); assertTrue(businessKeyDbo11.equals(businessKeyDbo11)); assertTrue(businessKeyDbo12.equals(businessKeyDbo12)); assertFalse(businessKeyDbo11.equals(businessKeyDbo12)); assertFalse(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(null)); businessKeyDbo12.setBusinessKey(1L); assertTrue(businessKeyDbo11.equals(businessKeyDbo12)); assertTrue(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(businessKeyDbo21)); assertFalse(businessKeyDbo11.equals(databaseObject1)); assertFalse(businessKeyDbo11.equals(surrogateKeyDbo11)); }
public void testBusinessKeyDboEquals(){ businessKeyDbo11.setBusinessKey(1L); businessKeyDbo12.setBusinessKey(2L); businessKeyDbo21.setBusinessKey(1L); surrogateKeyDbo11.setSurrogateKey(1L); assertTrue(businessKeyDbo11.equals(businessKeyDbo11)); assertTrue(businessKeyDbo12.equals(businessKeyDbo12)); assertFalse(businessKeyDbo11.equals(businessKeyDbo12)); assertFalse(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(null)); businessKeyDbo12.setBusinessKey(1L); assertTrue(businessKeyDbo11.equals(businessKeyDbo12)); assertTrue(businessKeyDbo12.equals(businessKeyDbo11)); assertFalse(businessKeyDbo11.equals(businessKeyDbo21)); assertFalse(businessKeyDbo11.equals(databaseObject1)); assertFalse(businessKeyDbo11.equals(surrogateKeyDbo11)); }
370
public void updateMemberTest(){ Mockito.when(manager.createQuery(Mockito.anyString())).thenReturn(query); List<Members> members = new ArrayList<Members>(); Members member = new Members(1, "Krystal", "Ryan"); Mockito.when(query.getResultList()).thenReturn(members); Mockito.when(manager.find(Members.class, 1)).thenReturn(member); String reply = repo.updateMember(1, j1.getJSONForObject(member)); Assert.assertEquals("{\"message\": \"Member successfully updated\"}", reply); }
public void updateMemberTest(){ Mockito.when(manager.createQuery(Mockito.anyString())).thenReturn(query); List<Members> members = new ArrayList<Members>(); Mockito.when(query.getResultList()).thenReturn(members); Mockito.when(manager.find(Members.class, 1)).thenReturn(member); String reply = repo.updateMember(1, j1.getJSONForObject(member)); Assert.assertEquals("{\"message\": \"Member successfully updated\"}", reply); }
371
public void updateParameters(NodeList parameters, MenuItem menuItem, Algorithm algorithmInstance){ for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeType() == Node.ELEMENT_NODE) { if (parameters.item(i).getNodeName().equals("parameters")) { final NodeList parametersList = parameters.item(i).getChildNodes(); int row = 1; for (int j = 0; j < parametersList.getLength(); j++) { if (parametersList.item(j).getNodeType() == Node.ELEMENT_NODE) { Element param = (Element) parametersList.item(j); if (param.getAttribute("type").equals("slider")) { String range = param.getAttribute("range"); String[] ranges = range.split("-"); int min = Integer.parseInt(ranges[0]); int max = Integer.parseInt(ranges[1]); menuItem.setOnAction(event -> { sliderZoom.setMin(min); sliderZoom.setMax(max); sliderZoom.setMajorTickUnit(Math.round(max / 4)); choosedAlgorithm = algorithmInstance; }); } } } } } } }
public void updateParameters(NodeList parameters, MenuItem menuItem, Algorithm algorithmInstance){ for (int i = 0; i < parameters.getLength(); i++) { if (parameters.item(i).getNodeType() == Node.ELEMENT_NODE && parameters.item(i).getNodeName().equals("parameters")) { final NodeList parametersList = parameters.item(i).getChildNodes(); int row = 1; for (int j = 0; j < parametersList.getLength(); j++) { if (parametersList.item(j).getNodeType() == Node.ELEMENT_NODE) { Element param = (Element) parametersList.item(j); if (param.getAttribute("type").equals("slider")) { String range = param.getAttribute("range"); String[] ranges = range.split("-"); int min = Integer.parseInt(ranges[0]); int max = Integer.parseInt(ranges[1]); menuItem.setOnAction(event -> { sliderZoom.setMin(min); sliderZoom.setMax(max); sliderZoom.setMajorTickUnit(Math.round(max / 4f)); choosedAlgorithm = algorithmInstance; }); } } } } } }
372
public int updatePersonById(UUID id, Person person){ Optional<Person> personOptional = selectPersonById(id); if (!personOptional.isPresent()) return 0; int index = DB.indexOf(personOptional.get()); PersonUtils.personQualifierUpdate(id, person); DB.set(index, person); return 1; }
public int updatePersonById(UUID id, Person person){ Optional<Person> personOptional = selectPersonById(id); if (!personOptional.isPresent()) return 0; int index = DB.indexOf(personOptional.get()); DB.set(index, person); return 1; }
373
public JsonNode readJsonLocal(String jsonFileLink){ JsonNode jsonNode = null; ObjectMapper mapper = new ObjectMapper(); try { BufferedReader br = new BufferedReader(new FileReader(jsonFileLink)); jsonNode = mapper.readTree(br); } catch (Exception e) { log.error("Hey, could not read local directory: {}", jsonFileLink); } return jsonNode; }
public JsonNode readJsonLocal(String jsonFileLink){ JsonNode jsonNode = null; try { BufferedReader br = new BufferedReader(new FileReader(jsonFileLink)); jsonNode = mapper.readTree(br); } catch (Exception e) { log.error("Hey, could not read local directory: {}", jsonFileLink); } return jsonNode; }
374
public void assertLoad() throws IOException{ AgentPathBuilder builder = new AgentPathBuilder(); ReflectiveUtil.setProperty(builder, "agentPath", new File(getResourceUrl())); AgentConfiguration configuration = AgentConfigurationLoader.load(); assertNotNull(configuration); }
public void assertLoad() throws IOException{ ReflectiveUtil.setStaticField(AgentPathBuilder.class, "agentPath", new File(getResourceUrl())); AgentConfiguration configuration = AgentConfigurationLoader.load(); assertNotNull(configuration); }
375
public List<Angebot> createRandomAngebotList() throws ParseException{ for (int i = 0; i < 10; i++) { Faker faker = new Faker(); long fakeAngebotsID = faker.number().randomNumber(); String fakeAngebotsName = faker.funnyName().name(); long fakeangebotsEinzelpreis = faker.number().randomNumber(); long fakeangebotsGesamtpreis = faker.number().numberBetween(faker.number().randomNumber(), 1500); int fakeMenge = faker.number().randomDigit(); Angebot randomAngebot = new Angebot(); randomAngebot = Angebot.builder().angebotsID(fakeAngebotsID).angebotsName(fakeAngebotsName).angebotsEinzelpreis(fakeangebotsEinzelpreis).angebotsGesamtpreis(fakeangebotsGesamtpreis).menge(fakeMenge).build(); randomAngebotList.add(randomAngebot); angebot_repository.save(randomAngebot); } return randomAngebotList; }
public void createRandomAngebotList(){ for (int i = 0; i < 10; i++) { Faker faker = new Faker(); long fakeAngebotsID = faker.number().randomNumber(); String fakeAngebotsName = faker.funnyName().name(); long fakeangebotsEinzelpreis = faker.number().randomNumber(); long fakeangebotsGesamtpreis = faker.number().numberBetween(faker.number().randomNumber(), 1500); int fakeMenge = faker.number().randomDigit(); Angebot randomAngebot = Angebot.builder().angebotsID(fakeAngebotsID).angebotsName(fakeAngebotsName).angebotsEinzelpreis(fakeangebotsEinzelpreis).angebotsGesamtpreis(fakeangebotsGesamtpreis).menge(fakeMenge).build(); angebot_repository.save(randomAngebot); } }
376
static ListNode<T> removeNthFromEnd(ListNode<T> head, int n){ ListNode<T> nDelay = head; int counter = 0; for (ListNode<T> curr = head; curr != null; curr = curr.next) { counter++; if (counter > n + 1) nDelay = nDelay.next; } if (n == counter) return head.next; nDelay.next = nDelay.next.next; return head; }
static ListNode<T> removeNthFromEnd(ListNode<T> head, int n){ ListNode<T> dummyHead = new ListNode<>(null, head); ListNode<T> nDelay = dummyHead; int counter = 0; for (ListNode<T> curr = head; curr != null; curr = curr.next) { counter++; if (counter > n) nDelay = nDelay.next; } nDelay.next = nDelay.next.next; return dummyHead.next; }
377
private static int placeCardOnStone(VerticalLayout stoneLayout){ if (selectedCard == null || selectedStone == null || selectedStone.isFullFor(activePlayer)) { return 0; } selectedStone.addCardFor(activePlayer, selectedCard); activePlayerHand.removeCard(selectedCard); ClanCardImage clanCardImage = new ClanCardImage(selectedCard, true, activePlayer); if (activePlayer.getId() == 0) { stoneLayout.addComponentAsFirst(clanCardImage); } else { stoneLayout.add(clanCardImage); } activePlayer = game.getBoard().getOpponentPlayer(activePlayer); final Player stoneOwner = selectedStone.getOwnBy(); if (stoneOwner == null) { selectedCard = null; selectedStone = null; return 1; } stoneLayout.getChildren().map(Component::getElement).filter(stoneChildElement -> stoneOwner.getName().equals(stoneChildElement.getAttribute("added-by"))).forEach(ownerCardElement -> ownerCardElement.setAttribute("class", "smallcarte winningArea")); stoneOwner.setScore(stoneOwner.getScore() + 1); int i = 0; int nbAdjacentOwned = border.getNbrAdjacentStones(stoneOwner); if (nbAdjacentOwned >= 3 || stoneOwner.getScore() >= 5) { winningPlayer = stoneOwner; return 2; } else { selectedCard = null; selectedStone = null; return 1; } }
private static GameHandler.ResponseCode placeCardOnStone(VerticalLayout stoneLayout){ GameHandler.ResponseCode responseCode = gameHandler.placeCardOnStone(activePlayer, selectedCard, selectedStone); switch(responseCode) { case NO_ACTION: break; case OK: ClanCardImage clanCardImage = new ClanCardImage(selectedCard, true, activePlayer); if (activePlayer.getId() == 0) { stoneLayout.addComponentAsFirst(clanCardImage); } else { stoneLayout.add(clanCardImage); } activePlayer = game.getBoard().getOpponentPlayer(activePlayer); final Player stoneOwner = selectedStone.getOwnBy(); if (stoneOwner != null) { stoneLayout.getChildren().map(Component::getElement).filter(stoneChildElement -> stoneOwner.getName().equals(stoneChildElement.getAttribute("added-by"))).forEach(ownerCardElement -> ownerCardElement.setAttribute("class", "smallcarte winningArea")); } selectedCard = null; selectedStone = null; break; case GAME_FINISHED: winningPlayer = selectedStone.getOwnBy(); } return responseCode; }
378
public void search(final String startDate, final DurationEnum duration, final int threshold){ final LogDataProcessor logDataProcessor = LogDataProcessorFactory.getInstance().makeLogDataProcessor(); final List<LogEntry> logEntries = new ArrayList<>(); final String searchToken = this.searchTokenExtractionStrategy.extractSearchToken(startDate, duration); final Path logFile = Paths.get(this.sourceFilePath); try (Stream<String> stream = Files.lines(logFile)) { final Map<String, Long> entriesByIp = stream.filter(line -> { String[] split = line.split(SPLIT_PATTERN); logEntries.add(new LogEntry(split[0], split[1], split[2].replaceAll("\"", ""))); return line.contains(searchToken); }).collect(Collectors.groupingBy(l -> l.split(SPLIT_PATTERN)[1], Collectors.counting())); entriesByIp.entrySet().stream().filter(entry -> entry.getValue() > threshold).forEach(System.out::println); logDataProcessor.processData(logEntries); } catch (IOException e) { LOGGER.error("An ERROR occurred while reading the file.", e); throw new RuntimeException(e); } }
public void search(final String startDate, final DurationEnum duration, final int threshold){ final LogDataProcessor logDataProcessor = LogDataProcessorFactory.getInstance().makeLogDataProcessor(); logDataProcessor.processData(this.sourceFilePath); final String searchToken = this.searchTokenExtractionStrategy.extractSearchToken(startDate, duration); final Path logFile = Paths.get(this.sourceFilePath); try (Stream<String> stream = Files.lines(logFile)) { final Map<String, Long> entriesByIp = stream.filter(line -> line.contains(searchToken)).collect(Collectors.groupingBy(l -> l.split(AppConstants.SPLIT_PATTERN)[1], Collectors.counting())); entriesByIp.entrySet().stream().filter(entry -> entry.getValue() > threshold).forEach(System.out::println); } catch (IOException e) { LOGGER.error("An ERROR occurred while reading the file.", e); throw new RuntimeException(e); } }
379
public void deleteComment(BlogPost blogPost, BlogPostComment comment){ this.commentRepository.delete(comment); blogPost.getComments().remove(comment); update(blogPost); }
public void deleteComment(BlogPost blogPost, BlogPostComment comment){ blogPost.getComments().remove(comment); update(blogPost); }
380
public void testJoinVirtualQueueNotHead(){ int position = 2; virtualQueueStatus.setPosition(position); employee.setTotalTimeSpent(5); employee.setNumRegisteredStudents(1); Set<String> employees = Sets.newHashSet(Collections.singleton("e1")); VirtualQueueData virtualQueueData = new VirtualQueueData("vq1", employees); doNothing().when(validationService).checkValidCompanyId(anyString()); doNothing().when(validationService).checkValidStudentId(anyString()); doReturn(virtualQueueStatus).when(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); doReturn(virtualQueueData).when(virtualQueueWorkflow).getVirtualQueueData(anyString(), any()); doReturn(employee).when(employeeHashOperations).get(anyString(), any()); JoinQueueResponse response = queueService.joinVirtualQueue("c1", Role.SWE, student); verify(validationService).checkValidStudentId(anyString()); verify(validationService).checkValidCompanyId(anyString()); verify(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); assertNotNull(response); assertNotNull(response.getQueueStatus()); assertEquals(response.getQueueStatus().getCompanyId(), "c1"); assertEquals(response.getQueueStatus().getQueueId(), "vq1"); assertEquals(response.getQueueStatus().getRole(), Role.SWE); assertEquals(response.getQueueStatus().getPosition(), MAX_EMPLOYEE_QUEUE_SIZE + position); assertEquals(response.getQueueStatus().getQueueType(), QueueType.VIRTUAL); assertNotEquals(response.getQueueStatus().getWaitTime(), 0); assertNull(response.getQueueStatus().getEmployee()); }
public void testJoinVirtualQueueNotHead(){ int position = 2; virtualQueueStatus.setPosition(position); int timeSpent = 5; int numStudents = 2; employee.setTotalTimeSpent(timeSpent); employee.setNumRegisteredStudents(numStudents); Set<String> employees = Sets.newHashSet(Collections.singleton("e1")); VirtualQueueData virtualQueueData = new VirtualQueueData("vq1", employees); int expectedWaitTime = (int) (((position + MAX_EMPLOYEE_QUEUE_SIZE - 1.) * timeSpent / numStudents) / employees.size()); doNothing().when(validationService).checkValidCompanyId(anyString()); doNothing().when(validationService).checkValidStudentId(anyString()); doReturn(virtualQueueStatus).when(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); doReturn(virtualQueueData).when(virtualQueueWorkflow).getVirtualQueueData(anyString(), any()); doReturn(employee).when(employeeHashOperations).get(anyString(), any()); JoinQueueResponse response = queueService.joinVirtualQueue("c1", Role.SWE, student); verify(validationService).checkValidStudentId(anyString()); verify(validationService).checkValidCompanyId(anyString()); verify(virtualQueueWorkflow).joinQueue(anyString(), any(), any()); assertNotNull(response); assertNotNull(response.getQueueStatus()); validateVirtualQueueStatus(response.getQueueStatus(), position, expectedWaitTime); }
381
public IamToken requestToken(){ RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(this.url, OPERATION_PATH)); builder.header(HttpHeaders.CONTENT_TYPE, HttpMediaType.APPLICATION_FORM_URLENCODED); if (StringUtils.isNotEmpty(this.cachedAuthorizationHeader)) { builder.header(HttpHeaders.AUTHORIZATION, this.cachedAuthorizationHeader); } FormBody formBody; final FormBody.Builder formBodyBuilder = new FormBody.Builder().add(GRANT_TYPE, REQUEST_GRANT_TYPE).add(API_KEY, apikey).add(RESPONSE_TYPE, CLOUD_IAM); if (!StringUtils.isEmpty(getScope())) { formBodyBuilder.add(SCOPE, getScope()); } formBody = formBodyBuilder.build(); builder.body(formBody); IamToken token; try { token = invokeRequest(builder, IamToken.class); } catch (Throwable t) { token = new IamToken(t); } return token; }
public IamToken requestToken(){ RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(this.getURL(), OPERATION_PATH)); builder.header(HttpHeaders.CONTENT_TYPE, HttpMediaType.APPLICATION_FORM_URLENCODED); addAuthorizationHeader(builder); FormBody formBody; final FormBody.Builder formBodyBuilder = new FormBody.Builder().add("grant_type", "urn:ibm:params:oauth:grant-type:apikey").add("apikey", getApiKey()).add("response_type", "cloud_iam"); if (!StringUtils.isEmpty(getScope())) { formBodyBuilder.add("scope", getScope()); } formBody = formBodyBuilder.build(); builder.body(formBody); IamToken token; try { token = invokeRequest(builder, IamToken.class); } catch (Throwable t) { token = new IamToken(t); } return token; }
382
public static synchronized void loop(String filename){ if (filename == null) throw new IllegalArgumentException(); final AudioInputStream ais = getAudioInputStreamFromFile(filename); try { Clip clip = AudioSystem.getClip(); clip.open(ais); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (IOException | LineUnavailableException e) { e.printStackTrace(); } new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); }
public static synchronized void loop(String filename){ requiresNotNull(filename); final AudioInputStream ais = getAudioInputStreamFromFile(filename); try { Clip clip = AudioSystem.getClip(); clip.open(ais); clip.loop(Clip.LOOP_CONTINUOUSLY); } catch (IOException | LineUnavailableException e) { e.printStackTrace(); } new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); }
383
public int parseInt(String s) throws NumberFormatException{ if (s == null || s.isEmpty()) { return 0; } if (s.matches("(\\+|-)?[0-9]+")) { return Integer.parseInt(s); } else if (s.matches("(\\+|-)?[0-9a-fA-F]+")) { return Integer.parseInt(s.toUpperCase(), 16); } else if (s.matches("(\\+|-)?(x|$)[0-9a-fA-F]+")) { String upper = s.toUpperCase(); boolean positive = true; if (upper.startsWith("-")) { positive = false; } for (int i = 0; i < upper.length(); i++) { char c = upper.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'A' & c <= 'F')) { int value = Integer.parseInt(s.substring(i), 16); if (!positive) { value *= -1; } return value; } } } throw new NumberFormatException("Could not interpret int value " + s); }
public int parseInt(String s) throws NumberFormatException{ if (s == null || s.isEmpty()) { return 0; } if (s.matches("(\\+|-)?[0-9]+")) { return Integer.parseInt(s); } else { String upper = s.toUpperCase(); boolean positive = true; if (upper.startsWith("-")) { positive = false; upper = upper.substring(1); } for (int i = 0; i < upper.length(); i++) { char c = upper.charAt(i); if ((c >= '0' && c <= '9') || (c >= 'A' & c <= 'F')) { int value = Integer.parseInt(s.substring(i), 16); if (!positive) { value *= -1; } return value; } } } throw new NumberFormatException("Could not interpret int value " + s); }
384
public TranslationResult visit(final SentenceMeatConjunction node, final EsVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final ConceptBookEntry conceptBookEntry = this.esTranslator.getConceptBook().get(node.getConjunction().getConcept()); final List<TranslationTarget> defaultTargets = conceptBookEntry.getDefaultTargets(Language.ES); if (defaultTargets.isEmpty()) { result.setTranslation(conceptBookEntry.getConceptPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? " " : "", defaultTargets.get(0).getMainPhrase())); } else { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? ", " : "", defaultTargets.get(0).getMainPhrase())); } return result; }
public TranslationResult visit(final SentenceMeatConjunction node, final EsVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final TranslationTarget conjunctionTarget = this.esTranslator.getFirstDefaultTarget(node.getConjunction().getConcept()); if (",".equals(conjunctionTarget.getMainPhrase())) { result.setTranslation(conjunctionTarget.getMainPhrase()); } else if (node.getConjunction().getToken().getType() == TokenType.SEPARATOR_SE) { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? " " : "", conjunctionTarget.getMainPhrase())); } else { result.setTranslation(String.format("%s%s", argument.getSentenceMeatIndex() > 0 ? ", " : "", conjunctionTarget.getMainPhrase())); } return result; }
385
private T getSingleResult(String field, Class<T> type){ try (PgClosableConnection closableConnection = this.pool.getConnection()) { DSLContext create = DSL.using(closableConnection.getConnection(), SQLDialect.POSTGRES); return create.selectFrom("example.user").where("id = {0}", this.id).fetchOne(field, type); } catch (Exception e) { throw new DbRuntimeException(e); } }
private T getSingleResult(String field, Class<T> type){ try (PgClosableConnection closableConnection = this.pool.getConnection()) { return closableConnection.context().selectFrom("example.user").where("id = {0}", this.id).fetchOne(field, type); } catch (Exception e) { throw new DbRuntimeException(e); } }
386
public void setDirectorySymbolicLink(CommonFile directory) throws FileSystemException, IllegalArgumentException{ checkFileType(directory); checkSymbolicLink(directory); try { String path = getSymLinkTargetPath(directory); String currWorkingDir = this.directory.getFilePath(); if (directory instanceof LocalFile) { path = UI.resolveLocalPath(path, currWorkingDir).getResolvedPath(); } else { path = UI.resolveRemotePath(path, currWorkingDir, true, this.fileSystem.getFTPConnection()).getResolvedPath(); } CommonFile targetFile = fileSystem.getFile(path); setDirectory(targetFile); refresh(); } catch (IOException ex) { UI.doException(ex, UI.ExceptionType.EXCEPTION, FTPSystem.isDebugEnabled()); } catch (FTPException ex) { UI.doException(ex, UI.ExceptionType.ERROR, FTPSystem.isDebugEnabled()); } }
public void setDirectorySymbolicLink(CommonFile directory) throws FileSystemException, IllegalArgumentException{ checkFileType(directory); checkSymbolicLink(directory); try { String path = getSymLinkTargetPath(directory); CommonFile targetFile = fileSystem.getFile(path); setDirectory(targetFile); refresh(); } catch (IOException ex) { UI.doException(ex, UI.ExceptionType.EXCEPTION, FTPSystem.isDebugEnabled()); } catch (FTPException ex) { UI.doException(ex, UI.ExceptionType.ERROR, FTPSystem.isDebugEnabled()); } }
387
public RevenueExpenseReportRes getRevenueExpenseReportData(ReportReq reportReq){ RevenueExpenseReportRes revenueExpenseReportRes = new RevenueExpenseReportRes(); if (reportReq.getVehicleId() != null) { revenueExpenseReportRes.setRevenueExpenses(reportComponent.getVehicleRevenueExpenseReportData(reportReq)); } else { revenueExpenseReportRes.setRevenueExpenses(reportComponent.getCompanyRevenueExpenseReportData(reportReq)); } return revenueExpenseReportRes; }
public RevenueExpenseReportRes getRevenueExpenseReportData(ReportReq reportReq){ return reportComponent.getRevenueExpenseDetailReportData(reportReq); }
388
public boolean move(Move move, ChessboardState moveFor){ if (!getValidator().isMovementValid(move, this, moveFor)) { return false; } Point start = move.getStart(); Point end = move.getEnd(); ChessboardState originalStartState = getSlotState(start); ChessboardState originalEndState = getSlotState(end); set(start, originalEndState); set(end, moveFor); return true; }
public boolean move(Move move, ChessboardState moveFor){ if (!getValidator().isMovementValid(move, this, moveFor)) { return false; } Point start = move.getStart(); Point end = move.getEnd(); ChessboardState originalEndState = getSlotState(end); set(start, originalEndState); set(end, moveFor); return true; }
389
public void getQuestions() throws Exception{ List<String[]> questions = config.getQuestions(); assertEquals("QA", questions.get(0)[0]); assertEquals(5, questions.get(0).length); assertEquals("Question #1", questions.get(0)[1]); assertEquals("key1", questions.get(0)[2]); assertEquals("P1", questions.get(0)[3]); assertEquals("P2", questions.get(0)[4]); assertEquals("QB", questions.get(1)[0]); assertEquals(4, questions.get(1).length); assertEquals("Question #2", questions.get(1)[1]); assertEquals("key2", questions.get(1)[2]); assertEquals("P3", questions.get(1)[3]); assertEquals("QC", questions.get(2)[0]); assertEquals(3, questions.get(2).length); assertEquals("Question #3", questions.get(2)[1]); assertEquals("key3", questions.get(2)[2]); }
public void getQuestions() throws Exception{ List<Question> questions = config.getQuestions(); assertEquals("QA", questions.get(0).getKey()); assertEquals("Question #1", questions.get(0).getQuestion()); assertEquals("key1", questions.get(0).getResolverKey()); assertEquals("P1", questions.get(0).getParms()[0]); assertEquals("P2", questions.get(0).getParms()[1]); assertEquals("QB", questions.get(1).getKey()); assertEquals("Question #2", questions.get(1).getQuestion()); assertEquals("key2", questions.get(1).getResolverKey()); assertEquals("P3", questions.get(1).getParms()[0]); assertEquals("QC", questions.get(2).getKey()); assertEquals("Question #3", questions.get(2).getQuestion()); assertEquals("key3", questions.get(2).getResolverKey()); }
390
public static long getSiteGroupIdByName(final String siteName, final long company, final String locationName){ long siteGroupId = 0; if (siteName.toLowerCase().equals("global")) { try { siteGroupId = GroupLocalServiceUtil.getCompanyGroup(company).getGroupId(); } catch (PortalException e) { LOG.error("Id of global site could not be retrieved!"); LOG.error((Throwable) e); } catch (SystemException e) { LOG.error("Id of global site could not be retrieved!"); LOG.error((Throwable) e); } } else { try { siteGroupId = GroupLocalServiceUtil.getGroup(company, getSiteName(siteName)).getGroupId(); } catch (PortalException e) { LOG.error(String.format("Id of site %1$s could not be retrieved for %2$s", siteName, locationName)); LOG.error((Throwable) e); } catch (SystemException e) { LOG.error(String.format("Id of site %1$s could not be retrieved for%2$s", siteName, locationName)); LOG.error((Throwable) e); } } return siteGroupId; }
public static long getSiteGroupIdByName(final String siteName, final long company, final String locationName){ long siteGroupId = 0; if (siteName.equalsIgnoreCase("global")) { try { siteGroupId = GroupLocalServiceUtil.getCompanyGroup(company).getGroupId(); } catch (PortalException e) { LOG.error("Id of global site could not be retrieved!"); LOG.error((Throwable) e); } } else { try { siteGroupId = GroupLocalServiceUtil.getGroup(company, getSiteName(siteName)).getGroupId(); } catch (PortalException e) { LOG.error(String.format("Id of site %1$s could not be retrieved for %2$s", siteName, locationName)); LOG.error((Throwable) e); } catch (SystemException e) { LOG.error(String.format("Id of site %1$s could not be retrieved for%2$s", siteName, locationName)); LOG.error((Throwable) e); } } return siteGroupId; }
391
private static Collection<Class<?>> getClassesInPackageAnnotatedBy(String thePackage, Reflections reflections, Class<? extends Annotation> annotation){ Set<Class<?>> classes = reflections.getTypesAnnotatedWith(annotation); for (Iterator<Class<?>> it = classes.iterator(); it.hasNext(); ) { String classPackage = it.next().getPackage().getName(); if (!classPackage.equals(thePackage)) { it.remove(); } } return classes; }
private static Collection<Class<?>> getClassesInPackageAnnotatedBy(String thePackage, Reflections reflections, Class<? extends Annotation> annotation){ return reflections.getTypesAnnotatedWith(annotation).stream().filter(c -> c.getPackage().getName().equals(thePackage)).collect(Collectors.toList()); }
392
public Builder snapshot_id(final String snapshot_id){ assert (snapshot_id != null); assert (!snapshot_id.equals("")); return setBodyParameter("snapshot_id", snapshot_id); }
public Builder snapshot_id(final String snapshot_id){ assertHasAndNotNull(snapshot_id); return setBodyParameter("snapshot_id", snapshot_id); }
393
public UserBO getUser() throws Exception{ LoginBO userLogin = userLoginService.getUserLogin(); Optional<Users> rs = userRepository.findById(userLogin.getUserId()); if (rs.isPresent()) { Users user = rs.get(); UserBO userBO = UserBO.builder().name(user.getName()).surname(user.getSurname()).dateOfBirth(user.getDateOfBirth()).build(); try { List<OrderBO> list = orderService.listOrder(user.getId()); for (OrderBO order : list) { userBO.addBooks(order.getBookId()); } } catch (ExceptionDataNotFound orderNotFound) { log.info(orderNotFound.getMessage()); } return userBO; } throw new ExceptionDataNotFound("user", ""); }
public UserBO getUser() throws Exception{ LoginBO userLogin = userLoginService.getUserLogin(); if (null != userLogin) { UserBO userBO = userLogin.getUserInfo(); try { List<OrderBO> list = orderService.findByUsername(userLogin.getUsername()); for (OrderBO order : list) { userBO.addBooks(order.getBookId()); } } catch (ExceptionDataNotFound orderNotFound) { log.info(orderNotFound.getMessage()); } return userBO; } throw new ExceptionDataNotFound("user", ""); }
394
public void addProject(final File projectRoot){ final File wcRoot = this.determineWorkingCopyRoot(projectRoot); if (wcRoot != null) { boolean wcCreated = false; synchronized (this.projectsPerWcMap) { Set<File> projects = this.projectsPerWcMap.get(wcRoot); if (projects == null) { projects = new LinkedHashSet<>(); this.projectsPerWcMap.put(wcRoot, projects); wcCreated = true; } projects.add(projectRoot); } if (wcCreated) { final Job job = Job.create("Analyzing SVN working copy at " + wcRoot, new IJobFunction() { @Override public IStatus run(final IProgressMonitor monitor) { SvnWorkingCopyManager.getInstance().getWorkingCopy(wcRoot); return Status.OK_STATUS; } }); job.schedule(); } } }
public void addProject(final File projectRoot){ final File wcRoot = this.determineWorkingCopyRoot(projectRoot); if (wcRoot != null) { boolean wcCreated = false; synchronized (this.projectsPerWcMap) { Set<File> projects = this.projectsPerWcMap.get(wcRoot); if (projects == null) { projects = new LinkedHashSet<>(); this.projectsPerWcMap.put(wcRoot, projects); wcCreated = true; } projects.add(projectRoot); } if (wcCreated) { SvnWorkingCopyManager.getInstance().getWorkingCopy(wcRoot); } } }
395
public ApiToken authenticateForToken(String accessKey, String secret){ logger.debug("Obtaining access token for application {} given key {}", stormpathClientHelper.getApplicationName(), accessKey); HttpRequest tokenRequest = buildHttpRequest(accessKey, secret); AccessTokenResult result = (AccessTokenResult) stormpathClientHelper.getApplication().authenticateOauthRequest(tokenRequest).withTtl(3600).execute(); TokenResponse token = result.getTokenResponse(); return buildApiToken(token); }
public OauthTokenResponse authenticateForToken(String accessKey, String secret){ logger.debug("Obtaining access token for application {} given key {}", stormpathClientHelper.getApplicationName(), accessKey); HttpRequest tokenRequest = buildHttpRequest(accessKey, secret); AccessTokenResult result = (AccessTokenResult) stormpathClientHelper.getApplication().authenticateOauthRequest(tokenRequest).withTtl(3600).execute(); return buildOauthTokenResponse(result.getTokenResponse(), result.getAccount()); }
396
public void actionPerformed(ActionEvent e){ ResourceClassSingleton.getInstance().changeStatusIsWindowOpenedUp(); FiguresJoe.figureScript2(driverManager.getCurrentDriver()); TestJobs2dApp testJobs2dApp = new TestJobs2dApp(); testJobs2dApp.getLogger().info("Remaining ink: " + ResourceClassSingleton.getInstance().getInk()); testJobs2dApp.getLogger().info("Remaining usage: " + ResourceClassSingleton.getInstance().getUsage()); }
public void actionPerformed(ActionEvent e){ ResourceClassSingleton.getInstance().changeStatusIsWindowOpenedUp(); FiguresJoe.figureScript2(driverManager.getCurrentDriver()); }
397
public AsyncFuture<T> error(LazyTransform<Throwable, ? extends T> transform){ final int state = sync.state(); if (!isStateReady(state)) return async.error(this, transform); if (state == CANCELLED) return async.cancelled(); if (state == RESOLVED) return async.resolved((T) sync.result(state)); final Throwable cause = (Throwable) sync.result(state); try { return (AsyncFuture<T>) transform.transform(cause); } catch (Exception e) { return async.failed(new TransformException(e)); } }
public AsyncFuture<T> error(LazyTransform<Throwable, ? extends T> transform){ final int state = sync.state(); if (!isStateReady(state)) return async.error(this, transform); if (state == FAILED) { final Throwable cause = (Throwable) sync.result(state); try { return (AsyncFuture<T>) transform.transform(cause); } catch (Exception e) { return async.failed(new TransformException(e)); } } return this; }
398
public static void setOffsets(String zkServers, String groupID, Map<TopicAndPartition, Long> offsets){ try (AutoZkClient zkClient = new AutoZkClient(zkServers)) { for (Map.Entry<TopicAndPartition, Long> entry : offsets.entrySet()) { TopicAndPartition topicAndPartition = entry.getKey(); ZKGroupTopicDirs topicDirs = new ZKGroupTopicDirs(groupID, topicAndPartition.topic()); int partition = topicAndPartition.partition(); long offset = entry.getValue(); String partitionOffsetPath = topicDirs.consumerOffsetDir() + "/" + partition; ZkUtils.updatePersistentPath(zkClient, partitionOffsetPath, Long.toString(offset)); } } }
public static void setOffsets(String zkServers, String groupID, Map<TopicAndPartition, Long> offsets){ try (AutoZkClient zkClient = new AutoZkClient(zkServers)) { offsets.forEach((topicAndPartition, offset) -> { ZKGroupTopicDirs topicDirs = new ZKGroupTopicDirs(groupID, topicAndPartition.topic()); int partition = topicAndPartition.partition(); String partitionOffsetPath = topicDirs.consumerOffsetDir() + "/" + partition; ZkUtils.updatePersistentPath(zkClient, partitionOffsetPath, Long.toString(offset)); }); } }
399
public ResponseEntity<?> importDependencies(@RequestBody Collection<Dependency> dependencies){ System.out.println("Received dependencies from Milla"); List<Dependency> savedDependencies = new ArrayList<>(); for (Dependency dependency : dependencies) { if (dependencyRepository.findById(dependency.getId()) == null) { savedDependencies.add(dependency); } else { System.out.println("Found a duplicate " + dependency.getId()); } } dependencyRepository.save(savedDependencies); System.out.println("Dependencies saved " + dependencyRepository.count()); savedDependencies.clear(); return new ResponseEntity<>("Dependencies saved", HttpStatus.OK); }
public ResponseEntity<?> importDependencies(@RequestBody Collection<Dependency> dependencies){ return updateService.importDependencies(dependencies); }