Unnamed: 0
int64
0
403
cwe_id
stringclasses
1 value
source
stringlengths
56
2.02k
target
stringlengths
50
1.97k
200
public String addOrder(@ModelAttribute("orderDTO") @Valid final OrderDTO orderDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ java.sql.Date startSqlDate = StringToSqlDateParser(orderDTO.getStartDate()); if (orderDTO.getStartDate() != null && !orderDTO.getStartDate().isEmpty() && startSqlDate == null) { bindingResult.rejectValue("startDate", "typeMismatch.order.start", null); } if (orderDTO.getOrderStatusId() != 0 && orderDTO.getManager().contentEquals("-") && !orderStatusSvc.getOrderStatusById(orderDTO.getOrderStatusId()).getOrderStatusName().contentEquals("pending")) { bindingResult.rejectValue("manager", "error.adminpage.managerRequired", null); } if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.orderDTO", bindingResult); redirectAttributes.addFlashAttribute("orderDTO", orderDTO); return "redirect:/adminpageorders#add_new_order"; } Order newOrder = new Order(); newOrder.setStart(startSqlDate); newOrder.setManager(orderDTO.getManager()); if (orderSvc.add(newOrder, orderDTO.getClientId(), orderDTO.getRepairTypeId(), orderDTO.getMachineId(), orderDTO.getOrderStatusId())) { changeSessionScopeAddingInfo(messageSource.getMessage("popup.adminpage.orderAdded", null, locale), ""); } else { changeSessionScopeAddingInfo("", messageSource.getMessage("popup.adminpage.orderNotAdded", null, locale)); } return "redirect:/adminpageorders"; }
public String addOrder(@ModelAttribute("dataObject") @Valid final OrderDTO orderDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ java.sql.Date startSqlDate = StringToSqlDateParser(orderDTO.getStartDate()); if (orderDTO.getStartDate() != null && !orderDTO.getStartDate().isEmpty() && startSqlDate == null) { bindingResult.rejectValue("startDate", "typeMismatch.order.start", null); } if (orderDTO.getOrderStatusId() != 0 && orderDTO.getManager().contentEquals("-") && !orderStatusSvc.getOrderStatusById(orderDTO.getOrderStatusId()).getOrderStatusName().contentEquals("pending")) { bindingResult.rejectValue("manager", "error.adminpage.managerRequired", null); } if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.dataObject", bindingResult); redirectAttributes.addFlashAttribute("dataObject", orderDTO); return "redirect:/adminpageorders#add_new_order"; } Order newOrder = new Order(); newOrder.setStart(startSqlDate); newOrder.setManager(orderDTO.getManager()); addMessages(orderSvc.add(newOrder, orderDTO.getClientId(), orderDTO.getRepairTypeId(), orderDTO.getMachineId(), orderDTO.getOrderStatusId()), "popup.adminpage.orderAdded", "popup.adminpage.orderNotAdded", locale); return "redirect:/adminpageorders"; }
201
private void validateIndex(int i){ checkArgument(i >= 0, "index is negative: " + i); checkArgument(i < maxN, "index >= capacity: " + i); }
private void validateIndex(int i){ checkIndexInRange(i, 0, maxN); }
202
public boolean isValidComponentSelector1ForDataset(String cs1, String dataset){ String datasetPath = String.format("/DatasetSelectors/DatasetSelector/Datasets/Dataset[text()='%s']/../..", dataset); String csAttrPath = String.format("ComponentSelector[@kind='%s'] | ComponentSelector[@minimum <= '%s' and @maximum >= '%s']", cs1, cs1, cs1); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression datasetExp = null; NodeList selector = null; try { datasetExp = xPath.compile(datasetPath); selector = (NodeList) datasetExp.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { return false; } if (selector.getLength() == 0) { return false; } XPathExpression csAttrExp = null; NodeList csNodes = null; try { csAttrExp = xPath.compile(csAttrPath); csNodes = (NodeList) csAttrExp.evaluate(selector.item(0), XPathConstants.NODESET); } catch (XPathExpressionException e) { return false; } if (csNodes.getLength() > 0) { return true; } return false; }
public boolean isValidComponentSelector1ForDataset(String cs1, String dataset){ String datasetPath = String.format(DATASETS_QUERY, dataset); String csAttrPath = String.format("ComponentSelector[@kind='%s'] | ComponentSelector[@minimum <= '%s' and @maximum >= '%s']", cs1, cs1, cs1); NodeList selector = null; try { selector = compileAndEvaluate(datasetPath, doc); } catch (XPathExpressionException e) { return false; } if (selector.getLength() == 0) { return false; } NodeList csNodes = null; try { csNodes = compileAndEvaluate(csAttrPath, selector.item(0)); } catch (XPathExpressionException e) { return false; } if (csNodes.getLength() > 0) { return true; } return false; }
203
private void print(int x, int y, String text, Ansi.Color colour){ if (chess.side != PieceColour.WHITE) { System.out.println(Ansi.ansi().cursor(19 - y, 38 - x).fg(colour).a(text)); System.out.println(Ansi.ansi().cursor(19 - y, 38 - x).fg(colour).a(text)); } else { System.out.println(Ansi.ansi().cursor(1 + y, x).fg(colour).a(text)); System.out.println(Ansi.ansi().cursor(1 + y, x).fg(colour).a(text)); } }
private void print(int x, int y, String text, Ansi.Color colour){ if (chess.side != PieceColour.WHITE) { System.out.println(Ansi.ansi().cursor(19 - y, 38 - x).fg(colour).a(text)); } else { System.out.println(Ansi.ansi().cursor(1 + y, x).fg(colour).a(text)); } }
204
public void requestDistributedSuggestions(long splitId, ModelAggregator modelAggrProc){ this.isSplitting = true; this.suggestionCtr = 0; this.thrownAwayInstance = 0; ComputeContentEvent cce = new ComputeContentEvent(splitId, this.id, this.getObservedClassDistribution()); cce.setEnsembleId(this.ensembleId); modelAggrProc.sendToControlStream(cce); }
public void requestDistributedSuggestions(long splitId, ModelAggregatorProcessor modelAggrProc){ this.isSplitting = true; this.suggestionCtr = 0; this.thrownAwayInstance = 0; ComputeContentEvent cce = new ComputeContentEvent(splitId, this.id, this.getObservedClassDistribution()); modelAggrProc.sendToControlStream(cce); }
205
public void testSelectRequest_Filter_CayenneExp(){ @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = mock(MultivaluedMap.class); when(params.getFirst("cayenneExp")).thenReturn("{\"exp\" : \"address = '1 Main Street'\"}"); when(params.getFirst(SenchaRequestParser.FILTER)).thenReturn("[{\"property\":\"name\",\"value\":\"xyz\"}]"); UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(params); ResourceEntity<E2> resourceEntity = parser.parseSelect(getLrEntity(E2.class), uriInfo, null); assertNotNull(resourceEntity.getQualifier()); assertEquals(exp("address = '1 Main Street' and name likeIgnoreCase 'xyz%'"), resourceEntity.getQualifier()); }
public void testSelectRequest_Filter_CayenneExp(){ @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = mock(MultivaluedMap.class); when(params.get("cayenneExp")).thenReturn(Collections.singletonList("{\"exp\" : \"address = '1 Main Street'\"}")); when(params.get(SenchaRequestParser.FILTER)).thenReturn(Collections.singletonList("[{\"property\":\"name\",\"value\":\"xyz\"}]")); ResourceEntity<E2> resourceEntity = parser.parseSelect(getLrEntity(E2.class), params, null); assertNotNull(resourceEntity.getQualifier()); assertEquals(exp("address = '1 Main Street' and name likeIgnoreCase 'xyz%'"), resourceEntity.getQualifier()); }
206
public void testContactFilterForNo(){ profiles = ProfileUtility.getProfiles(); criteria = new MatchSearchCriteria(); criteria.setPhoto(MatchConstants.NO); List<Profile> filteredProfiles = photoFilter.filter(profiles, criteria); assertEquals(0, filteredProfiles.size()); }
public void testContactFilterForNo(){ criteria = new MatchSearchCriteria(); criteria.setPhoto(MatchConstants.NO); List<Profile> filteredProfiles = photoFilter.filter(profiles, criteria); assertEquals(0, filteredProfiles.size()); }
207
public void addPage(IPage page){ Connection conn = null; try { conn = this.getConnection(); conn.setAutoCommit(false); String pageCode = page.getCode(); this.addPageRecord(page, conn); Date now = new Date(); PageMetadata draftMetadata = page.getMetadata(); if (draftMetadata == null) { draftMetadata = new PageMetadata(); } draftMetadata.setUpdatedAt(now); this.addDraftPageMetadata(pageCode, draftMetadata, conn); this.addWidgetForPage(page, WidgetConfigDest.DRAFT, conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error("Error while adding a new page", t); throw new RuntimeException("Error while adding a new page", t); } finally { closeConnection(conn); } }
public void addPage(IPage page){ Connection conn = null; try { conn = this.getConnection(); conn.setAutoCommit(false); String pageCode = page.getCode(); this.addPageRecord(page, conn); PageMetadata draftMetadata = page.getMetadata(); if (draftMetadata == null) { draftMetadata = new PageMetadata(); } draftMetadata.setUpdatedAt(new Date()); this.addDraftPageMetadata(pageCode, draftMetadata, conn); this.addWidgetForPage(page, WidgetConfigDest.DRAFT, conn); conn.commit(); } catch (Throwable t) { this.executeRollback(conn); _logger.error("Error while adding a new page", t); throw new RuntimeException("Error while adding a new page", t); } finally { closeConnection(conn); } }
208
public User createUser(User newUser){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = "insert into \"user\"(person_id, user_name," + " password, role) values (?,?,?,?) returning user_id;"; PreparedStatement createUserStatement = newConnection.prepareStatement(sql); createUserStatement.setInt(1, newUser.getPersonId()); createUserStatement.setString(2, newUser.getUserName()); createUserStatement.setString(3, newUser.getPassword()); createUserStatement.setString(4, newUser.getRole()); ResultSet result = createUserStatement.executeQuery(); if (result.next()) { newUser.setPersonId(result.getInt("user_Id")); } } catch (SQLException e) { BankAppLauncher.appLogger.catching(e); BankAppLauncher.appLogger.error("Internal error occured in the database"); } return newUser; }
public User createUser(User newUser){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = "insert into \"user\"(person_id, user_name," + " password, role) values (?,?,?,?) returning user_id;"; PreparedStatement createUserStatement = newConnection.prepareStatement(sql); createUserStatement.setInt(1, newUser.getPersonId()); createUserStatement.setString(2, newUser.getUserName()); createUserStatement.setString(3, newUser.getPassword()); createUserStatement.setString(4, newUser.getRole()); ResultSet result = createUserStatement.executeQuery(); if (result.next()) { newUser.setPersonId(result.getInt("user_Id")); } } catch (SQLException e) { BankAppLauncher.appLogger.error("Internal error occured in the database"); } return newUser; }
209
public Parking createParking(ParkingData parkingData){ ParkingBuilder parkingBuilder = new ParkingBuilder().withSquareSize(parkingData.getSize()); for (Integer i : parkingData.getPedestrianExits()) { parkingBuilder.withPedestrianExit(i); } Parking parking = parkingBuilder.build(); parkingRepository.save(parking); return parking; }
public Parking createParking(ParkingData parkingData){ ParkingBuilder parkingBuilder = new ParkingBuilder().withSquareSize(parkingData.getSize()); parkingData.getPedestrianExits().forEach(parkingBuilder::withPedestrianExit); Parking parking = parkingBuilder.build(); parkingRepository.save(parking); return parking; }
210
private static Future<ListMultimap<Thread, T>> grabLocksInThread(final CycleDetectingLock<T> lock1, final CycleDetectingLock<T> lock2, final CyclicBarrier barrier){ FutureTask<ListMultimap<Thread, T>> future = new FutureTask<ListMultimap<Thread, T>>(new Callable<ListMultimap<Thread, T>>() { @Override public ListMultimap<Thread, T> call() throws Exception { assertTrue(lock1.lockOrDetectPotentialLocksCycle().isEmpty()); barrier.await(); ListMultimap<Thread, T> cycle = lock2.lockOrDetectPotentialLocksCycle(); if (cycle == null) { lock2.unlock(); } lock1.unlock(); return cycle; } }); Thread thread = new Thread(future); thread.start(); return future; }
private static Future<ListMultimap<Thread, T>> grabLocksInThread(final CycleDetectingLock<T> lock1, final CycleDetectingLock<T> lock2, final CyclicBarrier barrier){ FutureTask<ListMultimap<Thread, T>> future = new FutureTask<ListMultimap<Thread, T>>(() -> { assertTrue(lock1.lockOrDetectPotentialLocksCycle().isEmpty()); barrier.await(); ListMultimap<Thread, T> cycle = lock2.lockOrDetectPotentialLocksCycle(); if (cycle == null) { lock2.unlock(); } lock1.unlock(); return cycle; }); Thread thread = new Thread(future); thread.start(); return future; }
211
public Builder user_id(final String user_id){ assert (user_id != null); assert (!user_id.equals("")); return setPathParameter("user_id", user_id); }
public Builder user_id(final String user_id){ assertHasAndNotNull(user_id); return setPathParameter("user_id", user_id); }
212
public GetShortUrlsResponse getExistingShortenedUrls(@ParameterObject Pageable pageable){ log.info("Received request to get existing shortened URLs with pageable {}", pageable); GetShortUrlsResponse getShortUrlsResponse = urlShortenerService.getShortUrls(pageable); log.info("Successfully retrieved existing shortened URLs: {}", getShortUrlsResponse); return getShortUrlsResponse; }
public GetShortUrlsResponse getExistingShortenedUrls(@ParameterObject Pageable pageable){ return shortUrlRetrievalService.getShortUrls(pageable); }
213
public void testArgumentList() throws ParseException{ String code = "public class B{ public void foo(){ print(3); } }"; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); ExpressionStmt stmt = (ExpressionStmt) md.getBody().getStmts().get(0); MethodCallExpr expr = (MethodCallExpr) stmt.getExpression(); expr.getArgs().add(new IntegerLiteralExpr("4")); ChangeLogVisitor visitor = new ChangeLogVisitor(); VisitorContext ctx = new VisitorContext(); ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2); visitor.visit((CompilationUnit) cu, ctx); List<Action> actions = visitor.getActionsToApply(); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, "public class B{ public void foo(){ print(3, 4); } }"); }
public void testArgumentList() throws ParseException{ String code = "public class B{ public void foo(){ print(3); } }"; DefaultJavaParser parser = new DefaultJavaParser(); CompilationUnit cu = parser.parse(code, false); CompilationUnit cu2 = parser.parse(code, false); MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); ExpressionStmt stmt = (ExpressionStmt) md.getBody().getStmts().get(0); MethodCallExpr expr = (MethodCallExpr) stmt.getExpression(); expr.getArgs().add(new IntegerLiteralExpr("4")); List<Action> actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); Assert.assertEquals(ActionType.REPLACE, actions.get(0).getType()); assertCode(actions, code, "public class B{ public void foo(){ print(3, 4); } }"); }
214
public OSService[] getServices(){ OSProcess[] process = getChildProcesses(1, 0, OperatingSystem.ProcessSort.PID); File etc = new File("/etc/inittab"); try { File[] files = etc.listFiles(); OSService[] svcArray = new OSService[files.length]; for (int i = 0; i < files.length; i++) { svcArray[i].setName(files[i].getName()); for (int j = 0; j < process.length; j++) { if (process[j].getName().equals(files[i].getName())) { svcArray[i].setProcessID(process[j].getProcessID()); svcArray[i].setState(OSService.State.RUNNING); } else { svcArray[i].setState(OSService.State.STOPPED); } } } return svcArray; } catch (NullPointerException ex) { LOG.error("Directory: /etc/inittab does not exist"); return new OSService[0]; } }
public OSService[] getServices(){ OSProcess[] process = getChildProcesses(1, 0, OperatingSystem.ProcessSort.PID); File etc = new File("/etc/inittab"); if (etc.exists()) { File[] files = etc.listFiles(); OSService[] svcArray = new OSService[files.length]; for (int i = 0; i < files.length; i++) { for (int j = 0; j < process.length; j++) { if (process[j].getName().equals(files[i].getName())) { svcArray[i] = new OSService(process[j].getName(), process[j].getProcessID(), RUNNING); } else { svcArray[i] = new OSService(files[i].getName(), 0, STOPPED); } } } return svcArray; } LOG.error("Directory: /etc/inittab does not exist"); return new OSService[0]; }
215
static int subarraySum(int[] nums, int k){ final int n = nums.length; final Map<Integer, Integer> m = new HashMap<>(); m.put(0, 1); int sum = 0; int c = 0; for (int i = 0; i < n; i++) { sum = sum + nums[i]; if (m.containsKey(sum - k)) c = c + m.getOrDefault(sum - k, 0); m.merge(sum, 1, Integer::sum); } return c; }
static int subarraySum(int[] nums, int k){ final int n = nums.length; final Map<Integer, Integer> m = new HashMap<>(); m.put(0, 1); int sum = 0; int c = 0; for (int i = 0; i < n; i++) { sum = sum + nums[i]; c = c + m.getOrDefault(sum - k, 0); m.merge(sum, 1, Integer::sum); } return c; }
216
public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String message = FxNodeValueUtils.getStringOrThrow(srcObj, "message"); String level = FxNodeValueUtils.getOrDefault(srcObj, "level", "info"); level = level.toLowerCase(); switch(level) { case "trace": logger.trace(message); break; case "debug": logger.debug(message); break; case "info": logger.info(message); break; case "warn": case "warning": logger.warn(message); break; case "error": logger.error(message); break; default: logger.info(message); break; } return null; }
public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String message = FxNodeValueUtils.getStringOrThrow(srcObj, "message"); String level = FxNodeValueUtils.getOrDefault(srcObj, "level", "info"); level = level.toLowerCase(); switch(level) { case "trace": logger.trace(message); break; case "debug": logger.debug(message); break; case "info": logger.info(message); break; case "warn": case "warning": logger.warn(message); break; case "error": logger.error(message); break; default: logger.info(message); break; } }
217
private void calculateBrowsers(String logLine, Context context){ if (logLine.contains("Mozilla")) { context.getCounter("browser", "Mozilla").increment(1); } else if (logLine.contains("MSIE")) { context.getCounter("browser", "MSIE").increment(1); } else if (logLine.contains("Opera")) { context.getCounter("browser", "Opera").increment(1); } else { context.getCounter("browser", "Other").increment(1); } }
private void calculateBrowsers(String logLine, Context context){ if (logLine.contains("Mozilla")) { context.getCounter("browser", "Mozilla").increment(1); } else if (logLine.contains("Opera")) { context.getCounter("browser", "Opera").increment(1); } else { context.getCounter("browser", "Other").increment(1); } }
218
public void execute() throws MojoExecutionException{ if (project.isExecutionRoot()) { String finalSuffix = null; if (backup) { LocalDateTime localDateTime = LocalDateTime.now(); if (suffix == null || suffix.isEmpty()) { finalSuffix = Common.getFormattedTimestamp(localDateTime); } else { finalSuffix = suffix; } } if (mainClass == null || mainClass.isEmpty()) { getLog().error("Unknown main class: use -DmainClass=com.mycompany.app.App\n"); System.exit(1); } else { if (binName == null || binName.isEmpty()) { binName = mainClass; getLog().warn("binary name is set to main class: -DbinName=" + binName); } try { Common.generateBinary(getLog(), project.getBasedir().getAbsolutePath(), mainClass, binName, finalSuffix); } catch (MojoExecutionException e) { getLog().error(e.getMessage()); } } } else { getLog().info("skipping"); } }
public void execute() throws MojoExecutionException{ if (project.isExecutionRoot()) { String finalSuffix = null; if (backup) { finalSuffix = Common.getBackupSuffix(suffix); } if (mainClass == null || mainClass.isEmpty()) { getLog().error("Unknown main class: use -DmainClass=com.mycompany.app.App\n"); System.exit(1); } else { if (binName == null || binName.isEmpty()) { binName = mainClass; getLog().warn("binary name is set to main class: -DbinName=" + binName); } try { Common.generateBinary(getLog(), project.getBasedir().getAbsolutePath(), mainClass, binName, finalSuffix); } catch (MojoExecutionException e) { getLog().error(e.getMessage()); } } } else { getLog().info("skipping"); } }
219
private boolean validate(){ final Optional<String> command = this.arguments.getCommand(); boolean ok = false; if (!command.isPresent()) { this.error = "Missing command"; this.suggestion = "Add one of " + listCommands(); } else if (TraceCommand.COMMAND_NAME.equals(command.get())) { ok = validateTraceCommand(); } else if (ConvertCommand.COMMAND_NAME.equals(command.get())) { ok = validateConvertCommand(); } else { final String nullableCommand = command.isPresent() ? command.get() : null; this.error = "'" + nullableCommand + "' is not an OFT command."; this.suggestion = "Choose one of " + listCommands() + "."; } return ok; }
private boolean validate(){ final Optional<String> command = this.arguments.getCommand(); boolean ok = false; if (!command.isPresent()) { this.error = "Missing command"; this.suggestion = "Add one of " + listCommands(); } else if (TraceCommand.COMMAND_NAME.equals(command.get())) { ok = validateTraceCommand(); } else if (ConvertCommand.COMMAND_NAME.equals(command.get())) { ok = validateConvertCommand(); } else { this.error = "'" + command.orElse(null) + "' is not an OFT command."; this.suggestion = "Choose one of " + listCommands() + "."; } return ok; }
220
public GreenHouse parseXml(String path){ XMLInputFactory factory = XMLInputFactory.newInstance(); FlowerStack flowerStack = new FlowerStack(); GreenHouse greenHouse = new GreenHouse(); flowerStack.push(new AliveFlower()); try { XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(path)); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); elementStart(flowerStack, qName); break; case XMLStreamConstants.CHARACTERS: Characters characters = event.asCharacters(); chars(characters.getData()); break; case XMLStreamConstants.END_ELEMENT: EndElement endElement = event.asEndElement(); elementEnd(flowerStack, endElement.getName().getLocalPart(), greenHouse); break; } } } catch (XMLStreamException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; }
public GreenHouse parseXml(String path){ XMLInputFactory factory = XMLInputFactory.newInstance(); GreenHouse greenHouse = new GreenHouse(); try { XMLEventReader eventReader = factory.createXMLEventReader(new FileReader(path)); while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); switch(event.getEventType()) { case XMLStreamConstants.START_ELEMENT: StartElement startElement = event.asStartElement(); String qName = startElement.getName().getLocalPart(); elementStart(qName); break; case XMLStreamConstants.CHARACTERS: Characters characters = event.asCharacters(); chars(characters.getData()); break; case XMLStreamConstants.END_ELEMENT: EndElement endElement = event.asEndElement(); elementEnd(endElement.getName().getLocalPart(), greenHouse); break; } } } catch (XMLStreamException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return greenHouse; }
221
public void removeBannedDependencies(Collection<Artifact> artifacts){ if (!bannedArtifacts.isEmpty() && artifacts != null) { for (Iterator<Artifact> it = artifacts.iterator(); it.hasNext(); ) { Artifact artifact = it.next(); if (bannedArtifacts.containsKey(artifact)) { it.remove(); } } } }
public void removeBannedDependencies(Collection<Artifact> artifacts){ if (!bannedArtifacts.isEmpty() && artifacts != null) { artifacts.removeIf(artifact -> bannedArtifacts.containsKey(artifact)); } }
222
public void test_getServiceUserID(){ ServiceUserMapperImpl.Config config = mock(ServiceUserMapperImpl.Config.class); when(config.user_mapping()).thenReturn(new String[] { BUNDLE_SYMBOLIC1 + "=" + SAMPLE, BUNDLE_SYMBOLIC2 + "=" + ANOTHER, BUNDLE_SYMBOLIC1 + ":" + SUB + "=" + SAMPLE_SUB, BUNDLE_SYMBOLIC2 + ":" + SUB + "=" + ANOTHER_SUB }); when(config.user_default()).thenReturn(NONE); when(config.user_enable_default_mapping()).thenReturn(false); final ServiceUserMapperImpl sum = new ServiceUserMapperImpl(); sum.configure(null, config); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, null)); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, null)); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, "")); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, "")); TestCase.assertEquals(SAMPLE_SUB, sum.getServiceUserID(BUNDLE1, SUB)); TestCase.assertEquals(ANOTHER_SUB, sum.getServiceUserID(BUNDLE2, SUB)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, null)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, SUB)); }
public void test_getServiceUserID(){ ServiceUserMapperImpl.Config config = mock(ServiceUserMapperImpl.Config.class); when(config.user_mapping()).thenReturn(new String[] { BUNDLE_SYMBOLIC1 + "=" + SAMPLE, BUNDLE_SYMBOLIC2 + "=" + ANOTHER, BUNDLE_SYMBOLIC1 + ":" + SUB + "=" + SAMPLE_SUB, BUNDLE_SYMBOLIC2 + ":" + SUB + "=" + ANOTHER_SUB }); when(config.user_default()).thenReturn(NONE); when(config.user_enable_default_mapping()).thenReturn(false); final ServiceUserMapperImpl sum = new ServiceUserMapperImpl(null, config); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, null)); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, null)); TestCase.assertEquals(SAMPLE, sum.getServiceUserID(BUNDLE1, "")); TestCase.assertEquals(ANOTHER, sum.getServiceUserID(BUNDLE2, "")); TestCase.assertEquals(SAMPLE_SUB, sum.getServiceUserID(BUNDLE1, SUB)); TestCase.assertEquals(ANOTHER_SUB, sum.getServiceUserID(BUNDLE2, SUB)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, null)); TestCase.assertEquals(NONE, sum.getServiceUserID(BUNDLE3, SUB)); }
223
public List<VaccineInfo> calendarByPin(String pincode, String date){ ResponseEntity<CenterData> res = restTemplate.exchange(vaccineServiceHelper.calendarByPinUri(pincode, date), HttpMethod.GET, VaccineServiceHelper.buildHttpEntity(), CenterData.class); System.out.println(res.getBody()); List<VaccineInfo> list = vaccineServiceHelper.vaccineInfoByCenter(res.getBody().getCenters()); return list; }
public List<VaccineInfo> calendarByPin(String pincode, String date){ ResponseEntity<CenterData> res = restTemplate.exchange(vaccineServiceHelper.calendarByPinUri(pincode, date), HttpMethod.GET, VaccineServiceHelper.buildHttpEntity(), CenterData.class); List<VaccineInfo> list = vaccineServiceHelper.vaccineInfoByCenter(res.getBody().getCenters()); return list; }
224
public void reduce(Text docMetaData, Iterator<Text> documentPayloads, OutputCollector<NullWritable, Text> output, Reporter reporter) throws IOException{ String[] pieces = StringUtils.split(docMetaData.toString(), TUPLE_SEPARATOR); String indexName = pieces[0]; String routing = pieces[1]; init(indexName); BulkRequestBuilder bulkRequestBuilder = esEmbededContainer.getNode().client().prepareBulk(); int count = 0; while (documentPayloads.hasNext()) { count++; Text line = documentPayloads.next(); if (line == null) { continue; } pieces = StringUtils.split(line.toString(), TUPLE_SEPARATOR); indexType = pieces[0]; docId = pieces[1]; pre = indexType + TUPLE_SEPARATOR + docId + TUPLE_SEPARATOR; json = line.toString().substring(pre.length()); bulkRequestBuilder.add(esEmbededContainer.getNode().client().prepareIndex(indexName, indexType).setId(docId).setRouting(routing).setSource(json)); if (count % esBatchCommitSize == 0) { bulkRequestBuilder.execute().actionGet(); bulkRequestBuilder = esEmbededContainer.getNode().client().prepareBulk(); count = 0; } } if (count > 0) { long start = System.currentTimeMillis(); bulkRequestBuilder.execute().actionGet(); reporter.incrCounter(JOB_COUNTER.TIME_SPENT_INDEXING_MS, System.currentTimeMillis() - start); } snapshot(indexName, reporter); output.collect(NullWritable.get(), new Text(indexName)); }
public void reduce(Text docMetaData, Iterator<Text> documentPayloads, OutputCollector<NullWritable, Text> output, final Reporter reporter) throws IOException{ String[] pieces = StringUtils.split(docMetaData.toString(), TUPLE_SEPARATOR); String indexName = pieces[0]; String routing = pieces[1]; init(indexName); long start = System.currentTimeMillis(); int count = 0; while (documentPayloads.hasNext()) { count++; Text line = documentPayloads.next(); if (line == null) { continue; } pieces = StringUtils.split(line.toString(), TUPLE_SEPARATOR); indexType = pieces[0]; docId = pieces[1]; pre = indexType + TUPLE_SEPARATOR + docId + TUPLE_SEPARATOR; json = line.toString().substring(pre.length()); IndexResponse response = esEmbededContainer.getNode().client().prepareIndex(indexName, indexType).setId(docId).setRouting(routing).setSource(json).execute().actionGet(); if (response.isCreated()) { reporter.incrCounter(JOB_COUNTER.INDEX_DOC_CREATED, 1l); } else { reporter.incrCounter(JOB_COUNTER.INDEX_DOC_NOT_CREATED, 1l); } } reporter.incrCounter(JOB_COUNTER.TIME_SPENT_INDEXING_MS, System.currentTimeMillis() - start); snapshot(indexName, reporter); output.collect(NullWritable.get(), new Text(indexName)); }
225
public void onSubscribe(final MetaData metaData){ if (RpcTypeEnum.DUBBO.getName().equals(metaData.getRpcType())) { MetaData exist = META_DATA.get(metaData.getPath()); if (Objects.isNull(exist)) { ApacheDubboConfigCache.getInstance().initRef(metaData); } else { ApacheDubboConfigCache.getInstance().get(metaData.getPath()); if (!Objects.equals(metaData.getServiceName(), exist.getServiceName()) || !Objects.equals(metaData.getRpcExt(), exist.getRpcExt()) || !Objects.equals(metaData.getParameterTypes(), exist.getParameterTypes()) || !Objects.equals(metaData.getMethodName(), exist.getMethodName())) { ApacheDubboConfigCache.getInstance().build(metaData); } } META_DATA.put(metaData.getPath(), metaData); } }
public void onSubscribe(final MetaData metaData){ if (RpcTypeEnum.DUBBO.getName().equals(metaData.getRpcType())) { MetaData exist = META_DATA.get(metaData.getPath()); if (Objects.isNull(exist) || Objects.isNull(ApacheDubboConfigCache.getInstance().get(metaData.getPath()))) { ApacheDubboConfigCache.getInstance().initRef(metaData); } else { if (!Objects.equals(metaData.getServiceName(), exist.getServiceName()) || !Objects.equals(metaData.getRpcExt(), exist.getRpcExt()) || !Objects.equals(metaData.getParameterTypes(), exist.getParameterTypes()) || !Objects.equals(metaData.getMethodName(), exist.getMethodName())) { ApacheDubboConfigCache.getInstance().build(metaData); } } META_DATA.put(metaData.getPath(), metaData); } }
226
public String addClient(@ModelAttribute("clientDTO") @Valid final ClientDTO clientDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.clientDTO", bindingResult); redirectAttributes.addFlashAttribute("clientDTO", clientDTO); return "redirect:/adminpageclients#add_new_client"; } if (clientSvc.add(new Client(clientDTO.getClientName()), clientDTO.getUserId())) { changeSessionScopeAddingInfo(messageSource.getMessage("popup.adminpage.clientAdded", null, locale), ""); } else { changeSessionScopeAddingInfo("", messageSource.getMessage("popup.adminpage.clientNotAdded", null, locale)); } return "redirect:/adminpageclients"; }
public String addClient(@ModelAttribute("dataObject") @Valid final ClientDTO clientDTO, final BindingResult bindingResult, final RedirectAttributes redirectAttributes, final Locale locale){ if (bindingResult.hasErrors()) { redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.dataObject", bindingResult); redirectAttributes.addFlashAttribute("dataObject", clientDTO); return "redirect:/adminpageclients#add_new_client"; } addMessages(clientSvc.add(new Client(clientDTO.getClientName()), clientDTO.getUserId()), "popup.adminpage.clientAdded", "popup.adminpage.clientNotAdded", locale); return "redirect:/adminpageclients"; }
227
void viewAnIngredient() throws Exception{ IngredientCommand ingredientCommand = new IngredientCommand(); when(ingredientService.findCommandByIdWithRecipeId(anyString(), anyString())).thenReturn(ingredientCommand); mockMvc.perform(get("/recipe/1L/ingredient/1L/show")).andExpect(status().isOk()).andExpect(view().name("recipe/ingredient/view")).andExpect(model().attributeExists("ingredient")); }
void viewAnIngredient() throws Exception{ when(ingredientService.findCommandByIdWithRecipeId(anyString(), anyString())).thenReturn(Mono.just(new IngredientCommand())); mockMvc.perform(get("/recipe/1L/ingredient/1L/show")).andExpect(status().isOk()).andExpect(view().name("recipe/ingredient/view")).andExpect(model().attributeExists("ingredient")); }
228
public ServerResponse productUpOrDown(HttpServletRequest request, Integer status, Integer productId){ String loginToken = CookieUtil.readLoginLoken(request); if (StringUtils.isBlank(loginToken)) { return ServerResponse.createByErrorMessage("用户未登录"); } String userStr = ShardedRedisPoolUtil.get(loginToken); User existUser = JsonUtil.Json2Obj(userStr, User.class); if (existUser == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录"); } if (iUserService.checkAdmin(existUser).isSuccess()) { return iProductService.productUpOrDown(status, productId); } return ServerResponse.createByErrorMessage("该用户没有权限"); }
public ServerResponse productUpOrDown(HttpServletRequest request, Integer status, Integer productId){ return iProductService.productUpOrDown(status, productId); }
229
private Object convertCellValue(ExcelBeanField beanField, Cell cell, String cellValue, int rowNum){ if (beanField.isCellDataType()) { val cellData = CellData.builder().value(cellValue).row(rowNum).col(cell.getColumnIndex()).sheetIndex(workbook.getSheetIndex(sheet)); applyComment(cell, cellData); return cellData.build(); } else { val type = beanField.getField().getType(); if (type == int.class || type == Integer.class) { return Integer.parseInt(cellValue); } } return cellValue; }
private Object convertCellValue(ExcelBeanField beanField, Cell cell, String cellValue, int rowNum){ if (beanField.isCellDataType()) { val cellData = CellData.builder().value(cellValue).row(rowNum).col(cell.getColumnIndex()).sheetIndex(workbook.getSheetIndex(sheet)); applyComment(cell, cellData); return cellData.build(); } else { return beanField.convert(cellValue); } }
230
void is_rover_moved_right(int posX, int posY, Direction direction, String stringCommands, int expectedPosX, int expectedPosY, Direction expectedDirection){ Rover rover = new Rover(generatePosition(posX, posY, direction, mars), mars); char[] commands = stringCommands.toCharArray(); rover.move(commands); assertThat(rover.getPositionRover().getX()).isEqualTo(expectedPosX); assertThat(rover.getPositionRover().getY()).isEqualTo(expectedPosY); assertThat(rover.getPositionRover().getDirection()).isEqualTo(expectedDirection); }
void is_rover_moved_right(int posX, int posY, Direction direction, String stringCommands, int expectedPosX, int expectedPosY, Direction expectedDirection){ Rover rover = new Rover(generatePosition(posX, posY, direction, mars), mars); rover.move(stringCommands); assertThat(rover.getPositionRover().getX()).isEqualTo(expectedPosX); assertThat(rover.getPositionRover().getY()).isEqualTo(expectedPosY); assertThat(rover.getPositionRover().getDirection()).isEqualTo(expectedDirection); }
231
public ServerResponse updateCategoryName(HttpServletRequest request, String categoryName, Integer categoryId){ String loginToken = CookieUtil.readLoginLoken(request); if (StringUtils.isBlank(loginToken)) { return ServerResponse.createByErrorMessage("用户未登录"); } String userStr = ShardedRedisPoolUtil.get(loginToken); User existUser = JsonUtil.Json2Obj(userStr, User.class); if (existUser == null) { return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录"); } if (iUserService.checkAdmin(existUser).isSuccess()) { return iCategoryService.updateCategoryName(categoryName, categoryId); } return ServerResponse.createByErrorMessage("该用户没有权限"); }
public ServerResponse updateCategoryName(HttpServletRequest request, String categoryName, Integer categoryId){ return iCategoryService.updateCategoryName(categoryName, categoryId); }
232
public String action(HttpServletRequest request, HttpServletResponse response) throws RuntimeException{ DataSource dataSource = DataSourceFactory.getInstance().getDataSource(); Connection connection = null; try { connection = dataSource.getConnection(); DaoFactory daoFactory = DaoFactory.getDaoFactory(connection); BeverageOrderDao beverageOrderDao = daoFactory.createBeverageOrderDao(); BeverageOrder one = beverageOrderDao.findOne(5L); Beverage beverage = one.getBeverage(); Order order = one.getOrder(); Integer amount = one.getAmount(); one.getId(); } catch (SQLException e) { e.printStackTrace(); } Long authToken = (Long) request.getSession().getAttribute(X_AUTH_TOKEN); String commandName = request.getParameter(COMMAND); if (commandName != null && ADMIN.equals(commandName.split("/")[0])) { List<Role> roles = serviceFactory.createUserService().getCurrentUser(request).getRoles(); boolean isAdmin = false; for (Role role : roles) { if (ADMIN_ROLE.equals(role.getName())) { isAdmin = true; break; } } if (!isAdmin) { return ERROR; } commandName = commandName.split("/")[1]; } Command command = commandMap.get(commandName); if (authToken == null && !LOGIN_COMMAND.equals(commandName) && !REGISTRATION_PAGE_COMMAND.equals(commandName) && !REGISTRATION_COMMAND.equals(commandName)) { command = commandMap.get(LOGIN_PAGE_COMMAND); } else if (authToken != null && commandName == null) { command = commandMap.get(INDEX_COMMAND); } return command.execute(request, response); }
public String action(HttpServletRequest request, HttpServletResponse response) throws RuntimeException{ Long authToken = (Long) request.getSession().getAttribute(X_AUTH_TOKEN); String commandName = request.getParameter(COMMAND); if (commandName != null && ADMIN.equals(commandName.split("/")[0])) { List<Role> roles = serviceFactory.createUserService().getCurrentUser(request).getRoles(); boolean isAdmin = false; for (Role role : roles) { if (ADMIN_ROLE.equals(role.getName())) { isAdmin = true; break; } } if (!isAdmin) { return Pages.ERROR; } commandName = commandName.split("/")[1]; } Command command = commandMap.get(commandName); if (authToken == null && !LOGIN_COMMAND.equals(commandName) && !REGISTRATION_PAGE_COMMAND.equals(commandName) && !REGISTRATION_COMMAND.equals(commandName)) { command = commandMap.get(LOGIN_PAGE_COMMAND); } else if (authToken != null && commandName == null) { command = commandMap.get(INDEX_COMMAND); } return command.execute(request, response); }
233
int[] maxSlidingWindowHeap(int[] nums, int k){ if (nums == null || nums.length == 0 || k < 0) return nums; if (k > nums.length) { Arrays.sort(nums); return new int[] { nums[nums.length - 1] }; } int[] result = new int[nums.length - k + 1]; PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, Collections.<Integer>reverseOrder()); for (int i = 0; i < k; i++) { priorityQueue.offer(nums[i]); } result[0] = Objects.requireNonNull(priorityQueue.peek()); priorityQueue.size(); for (int j = k; j < nums.length; j++) { priorityQueue.offer(nums[j]); priorityQueue.remove(nums[j - k]); result[j - k + 1] = Objects.requireNonNull(priorityQueue.peek()); } return result; }
int[] maxSlidingWindowHeap(int[] nums, int k){ if (nums == null || nums.length == 0 || k < 0) return nums; if (k > nums.length) { Arrays.sort(nums); return new int[] { nums[nums.length - 1] }; } int[] result = new int[nums.length - k + 1]; PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(k, Collections.<Integer>reverseOrder()); for (int i = 0; i < k; i++) { priorityQueue.offer(nums[i]); } result[0] = Objects.requireNonNull(priorityQueue.peek()); for (int j = k; j < nums.length; j++) { priorityQueue.offer(nums[j]); priorityQueue.remove(nums[j - k]); result[j - k + 1] = Objects.requireNonNull(priorityQueue.peek()); } return result; }
234
public UserEntity createUser(UserEntity userEntity){ RouteEntity routeToAdd = routeRepository.findByRouteName("Gbg-Sthlm"); userEntity.addRoute(routeToAdd); return userEntity; }
public UserEntity createUser(UserEntity userEntity){ return userEntity; }
235
Set<Integer> generateNeighbours(Ship ship){ Set<Integer> neighbours = new HashSet<>(); List<Integer> occupiedFields = new ArrayList<>(); occupiedFields.addAll(ship.toHit); occupiedFields.addAll(ship.hit); for (Integer field : occupiedFields) { if (field != (((field / COLUMNS) * COLUMNS) + COLUMNS - 1)) { generateNeighboursFromRightSideOfAField(field, neighbours, ship.hit); } if (field != ((field / COLUMNS) * COLUMNS)) { generateNeighboursFromLeftSideOfAField(field, neighbours, ship.hit); } generateNeighboursAboveAndUnderAField(field, neighbours, ship.hit); } return neighbours; }
Set<Integer> generateNeighbours(Ship ship){ Set<Integer> neighbours = new HashSet<>(); List<Integer> occupiedFields = getOccupiedFields(ship); for (Integer field : occupiedFields) { if (field != (((field / COLUMNS) * COLUMNS) + COLUMNS - 1)) { generateNeighboursFromRightSideOfAField(field, neighbours, ship.hit); } if (field != ((field / COLUMNS) * COLUMNS)) { generateNeighboursFromLeftSideOfAField(field, neighbours, ship.hit); } generateNeighboursAboveAndUnderAField(field, neighbours, ship.hit); } return neighbours; }
236
private void clearNotSelectedGrains(){ for (int i = 0; i < space.getSizeY(); i++) { for (int j = 0; j < space.getSizeX(); j++) { Cell cell = space.getCells()[i][j]; if (selectedGrainsById.containsKey(cell.getId())) { continue; } cell.setGrowable(true); cell.setId(0); } } selectedGrainsById.remove(-1); }
private void clearNotSelectedGrains(){ space.getCellsByCoords().values().stream().filter(cell -> !selectedGrainsById.containsKey(cell.getId())).forEach(cell -> { cell.setId(0); cell.setGrowable(true); }); selectedGrainsById.remove(-1); }
237
public boolean equals(Object o){ if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PlaceBetRequestDTO betDTO = (PlaceBetRequestDTO) o; if (Double.compare(betDTO.coefficient, coefficient) != 0) return false; if (betAmount != null ? !betAmount.equals(betDTO.betAmount) : betDTO.betAmount != null) return false; if (betType != betDTO.betType) return false; if (sportsMatchName != null ? !sportsMatchName.equals(betDTO.sportsMatchName) : betDTO.sportsMatchName != null) return false; return true; }
public boolean equals(Object o){ if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PlaceBetRequestDTO betDTO = (PlaceBetRequestDTO) o; if (Double.compare(betDTO.coefficient, coefficient) != 0) return false; if (betAmount != null ? !betAmount.equals(betDTO.betAmount) : betDTO.betAmount != null) return false; if (betType != betDTO.betType) return false; return !(sportsMatchName != null ? !sportsMatchName.equals(betDTO.sportsMatchName) : betDTO.sportsMatchName != null); }
238
public void initVariabls(){ player = new Player("Jozek"); size = input.getIntInputWithMessage("Podaj rozmiar planszy : "); board = new Board(size); board = board.putFoodOnCoreBoard(); snake = new Snake(size); board.putSnakeOnBoard(snake); printer.printBoard(board); counter = new Counter(); mover = new Mover(); }
public void initVariabls(){ player = new Player("Jozek"); size = input.getIntInputWithMessage("Podaj rozmiar planszy : "); board = new Board(size).putFoodOnCoreBoard().putTrapOnCoreBoard(); snake = new Snake(size); board.putSnakeOnBoard(snake); printer.printBoard(board); counter = new Counter(); mover = new Mover(); }
239
public CurrentOfferResult calculateCurrentOffer(RequestAndOffers requestAndOffers){ if (requestAndOffers.getOffers().isEmpty()) { return NO_OFFER; } BigDecimal remainderFromRequest = requestAndOffers.getRequest().getAmount(); BigDecimal weightedInterest = BigDecimal.ZERO; for (LoanOffer offer : requestAndOffers.getOffers()) { if (remainderFromRequest.compareTo(BigDecimal.ZERO) > 0) { BigDecimal availableToTake = remainderFromRequest.min(offer.getAmount()); remainderFromRequest = remainderFromRequest.subtract(availableToTake); weightedInterest = weightedInterest.add(availableToTake.multiply(offer.getInterestRate())); } else break; } BigDecimal amountSatisfied = requestAndOffers.getRequest().getAmount().subtract(remainderFromRequest); return new CurrentOfferResult(amountSatisfied, weightedInterest.divide(amountSatisfied)); }
public CurrentOfferResult calculateCurrentOffer(RequestAndOffers requestAndOffers){ if (requestAndOffers.getOffers().isEmpty()) { return NO_OFFER; } BigDecimal remainderFromRequest = requestAndOffers.getRequest().getAmount(); BigDecimal weightedInterest = BigDecimal.ZERO; Iterator<LoanOffer> offerIt = requestAndOffers.getOffers().iterator(); while (offerIt.hasNext() && remainderFromRequest.compareTo(BigDecimal.ZERO) > 0) { LoanOffer offer = offerIt.next(); BigDecimal availableToTake = remainderFromRequest.min(offer.getAmount()); remainderFromRequest = remainderFromRequest.subtract(availableToTake); weightedInterest = weightedInterest.add(availableToTake.multiply(offer.getInterestRate())); } BigDecimal amountSatisfied = requestAndOffers.getRequest().getAmount().subtract(remainderFromRequest); return new CurrentOfferResult(amountSatisfied, weightedInterest.divide(amountSatisfied)); }
240
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv){ if (annotations.isEmpty()) { return true; } Element ce = null; HashMap<DeltaBuilderTypeModel, Map<String, FieldModel>> modelMap = new HashMap<>(); try { DeltaBuilderTypeModel model = null; for (Element elem : roundEnv.getElementsAnnotatedWith(DeltaForceBuilder.class)) { ce = elem; if (elem.getKind() == ElementKind.CLASS) { createBuilderModel(modelMap, elem); } } if (modelMap.size() > 0) { for (DeltaBuilderTypeModel tm : modelMap.keySet()) { writeBuilder(tm, modelMap.get(tm)); } } } catch (ResourceNotFoundException rnfe) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, rnfe.getLocalizedMessage()); } catch (ParseErrorException pee) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, pee.getLocalizedMessage()); } catch (IOException ioe) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ioe.getLocalizedMessage()); } catch (Exception e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getLocalizedMessage(), ce); } return true; }
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv){ if (annotations.isEmpty()) { return true; } Element ce = null; HashMap<DeltaBuilderTypeModel, Map<String, FieldModel>> modelMap = new HashMap<>(); try { for (Element elem : roundEnv.getElementsAnnotatedWith(DeltaForceBuilder.class)) { ce = elem; if (elem.getKind() == ElementKind.CLASS) { createBuilderModel(modelMap, elem); } } if (modelMap.size() > 0) { for (DeltaBuilderTypeModel tm : modelMap.keySet()) { writeBuilder(tm, modelMap.get(tm)); } } } catch (Exception e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getLocalizedMessage(), ce); } return true; }
241
public TranslationResult visit(final SubstantiveSelection node, final EoVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final ConceptBookEntry conceptBookEntry = this.eoTranslator.getConceptBook().get(node.getSubstantive().getConcept()); List<TranslationTarget> defaultTargets = conceptBookEntry.getDefaultTargets(Language.EO); if (defaultTargets.isEmpty()) { result.setTranslation(conceptBookEntry.getConceptPhrase()); } else if (argument.getArticle() != null) { final TranslationTarget substantiveTarget = defaultTargets.get(0); result.setTranslation("la", EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } else { final TranslationTarget substantiveTarget = defaultTargets.get(0); result.setTranslation(EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } return result; }
public TranslationResult visit(final SubstantiveSelection node, final EoVisitorArgument argument){ final TranslationResult result = new TranslationResult(node); final TranslationTarget substantiveTarget = this.eoTranslator.getFirstDefaultTarget(node.getSubstantive().getConcept()); if (argument.getArticle() != null) { result.setTranslation("la", EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } else { result.setTranslation(EoUtils.getCasedSubstantive(substantiveTarget, argument.getCaseAttribute())); } return result; }
242
public void checkIfRestIsBackwardCompatibleFilteredSpecs() throws Exception{ setProps(); CommandExecutor cmdIss = new MockCommandExecutor(); RESTClient restClient = BDDMockito.mock(RESTClient.class); HttpMethod getHTTPMethod = BDDMockito.mock(HttpMethod.class); RESTSpecLRValidator restSpecLRValidator = new RESTSpecLRValidator(cmdIss, restClient, FILTER_URL); given(restClient.executeMethod(any(HttpMethod.class))).willReturn(RESTSpecLRValidator.HTTP_OK); given(restClient.createGetMethod(anyString())).willReturn(getHTTPMethod); given(getHTTPMethod.getResponseBodyAsString()).willReturn("swagger: 2.0"); restSpecLRValidator.checkIfRestIsBackwardCompatible(); final Collection<String> execs = ((MockCommandExecutor) cmdIss).getExecs(); final String processedFilesPaths = execs.stream().collect(Collectors.joining()); assertThat(execs).hasSize(SPECS_THAT_MATCH_COUNT); assertThat(processedFilesPaths).contains("/spec0_1.json"); assertThat(processedFilesPaths).contains("/spec1_1.json"); assertThat(processedFilesPaths).contains("/spec2_1.json"); }
public void checkIfRestIsBackwardCompatibleFilteredSpecs() throws Exception{ CommandExecutor cmdIss = new MockCommandExecutor(); RESTClient restClient = BDDMockito.mock(RESTClient.class); HttpMethod getHTTPMethod = BDDMockito.mock(HttpMethod.class); RESTSpecLRValidator restSpecLRValidator = new RESTSpecLRValidator(cmdIss, restClient, FILTER_URL); given(restClient.executeMethod(any(HttpMethod.class))).willReturn(RESTSpecLRValidator.HTTP_OK); given(restClient.createGetMethod(anyString())).willReturn(getHTTPMethod); given(getHTTPMethod.getResponseBodyAsString()).willReturn("swagger: 2.0"); restSpecLRValidator.checkIfRestIsBackwardCompatible(); final Collection<String> execs = ((MockCommandExecutor) cmdIss).getExecs(); final String processedFilesPaths = execs.stream().collect(Collectors.joining()); assertThat(execs).hasSize(SPECS_THAT_MATCH_COUNT); assertThat(processedFilesPaths).contains("/spec0_1.json"); assertThat(processedFilesPaths).contains("/spec1_1.json"); assertThat(processedFilesPaths).contains("/spec2_1.json"); }
243
public void run(){ while (true) { moveType = input.getMoveType(input.getIntInput()); snake = mover.moveSnake(snake, moveType, board, counter); board = board.clearBoard(); board = board.putFoodOnCoreBoard(); board = board.putSnakeOnBoard(snake); printer.printBoard(board); printer.printMessage("Counter : " + String.valueOf(counter.getAmount())); printer.goNextLine(); } }
public void run(){ while (true) { moveType = input.getMoveType(input.getIntInput()); snake = mover.moveSnake(snake, moveType, board, counter); printer.printBoard(board.clearBoard().putFoodOnCoreBoard().putSnakeOnBoard(snake)); printer.printMessage("Counter : " + String.valueOf(counter.getAmount())); printer.goNextLine(); } }
244
public SubmissionList getSubmissionByDate(UserSubmissionByDateRequest userSubmissionByDateRequest){ String uri = String.format("https://codeforces.com/api/user.status?handle=%s&from=1&count=100", userSubmissionByDateRequest.getHandle()); SubmissionList result = restTemplate.getForObject(uri, SubmissionList.class); Instant now = Instant.now(); Instant yesterday = now.minus(userSubmissionByDateRequest.getNoOfDays(), ChronoUnit.DAYS); Long epochSecond = yesterday.getEpochSecond(); SubmissionList filteredResult = new SubmissionList(); for (Submission submission : result.getResult()) { if (submission.getCreationTimeSeconds() > epochSecond) { filteredResult.getResult().add(submission); } else { break; } } return filteredResult; }
public SubmissionList getSubmissionByDate(UserSubmissionByDateRequest userSubmissionByDateRequest){ String uri = String.format("https://codeforces.com/api/user.status?handle=%s&from=1&count=100", userSubmissionByDateRequest.getHandle()); SubmissionList result = restTemplate.getForObject(uri, SubmissionList.class); Long epochSecond = TimeUtil.getEpochBeforeNDays(userSubmissionByDateRequest.getNoOfDays()); SubmissionList filteredResult = new SubmissionList(); for (Submission submission : result.getResult()) { if (submission.getCreationTimeSeconds() > epochSecond) { filteredResult.getResult().add(submission); } else { break; } } return filteredResult; }
245
public static int poisson(double lambda){ if (!(lambda > 0.0)) throw new IllegalArgumentException("lambda must be positive: " + lambda); if (Double.isInfinite(lambda)) throw new IllegalArgumentException("lambda must not be infinite: " + lambda); int k = 0; double p = 1.0; double expLambda = Math.exp(-lambda); do { k++; p *= uniform(); } while (p >= expLambda); return k - 1; }
public static int poisson(double lambda){ checkArgument(lambda > 0.0, "lambda must be positive: " + lambda); checkArgument(!Double.isInfinite(lambda), "lambda must not be infinite: " + lambda); int k = 0; double p = 1.0; double expLambda = Math.exp(-lambda); do { k++; p *= uniform(); } while (p >= expLambda); return k - 1; }
246
public static void write(InputStream in, long size, File output) throws IOException{ FileOutputStream out = new FileOutputStream(output); try { byte[] buf = new byte[BYTE_BUFFER_LENGTH]; int read; int left = buf.length; if (left > size) left = (int) size; while ((read = in.read(buf, 0, left)) > 0) { out.write(buf, 0, read); size = size - read; if (left > size) left = (int) size; } } finally { out.close(); } }
public static void write(InputStream in, long size, File output) throws IOException{ try (FileOutputStream out = new FileOutputStream(output)) { byte[] buf = new byte[BYTE_BUFFER_LENGTH]; int read; int left = buf.length; if (left > size) left = (int) size; while ((read = in.read(buf, 0, left)) > 0) { out.write(buf, 0, read); size = size - read; if (left > size) left = (int) size; } } }
247
public PDAppearanceEntry getNormalAppearance(){ COSBase entry = dictionary.getDictionaryObject(COSName.N); if (entry == null) { return null; } else { return new PDAppearanceEntry(entry); } }
public PDAppearanceEntry getNormalAppearance(){ COSBase entry = dictionary.getDictionaryObject(COSName.N); if (nonNull(entry)) { return new PDAppearanceEntry(entry); } return null; }
248
private JSONObject compactConvert(JSONObject jsonObject){ val compactJsonObject = new JSONObject(); for (val entry : jsonObject.entrySet()) { Object value = entry.getValue(); String key = entry.getKey(); if (value instanceof JSONArray) { value = compactConvert((JSONArray) value); } else if (value instanceof JSONObject) { value = compactConvert((JSONObject) value); } compactJsonObject.put(key, value); } return compactJsonObject; }
private JSONObject compactConvert(JSONObject jsonObject){ val compactJsonObject = new JSONObject(); for (val entry : jsonObject.entrySet()) { Object value = entry.getValue(); if (value instanceof JSONArray) { value = compactConvert((JSONArray) value); } else if (value instanceof JSONObject) { value = compactConvert((JSONObject) value); } compactJsonObject.put(entry.getKey(), value); } return compactJsonObject; }
249
public static T newInstance(T obj){ SoapServiceProxy proxy = new SoapServiceProxy(obj); Class<?> clazz = obj.getClass(); T res = (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), proxy); return res; }
public static T newInstance(T obj){ SoapServiceProxy proxy = new SoapServiceProxy(obj); Class<?> clazz = obj.getClass(); return (T) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), proxy); }
250
public static byte[] generateIV(){ Random r = new Random(); byte[] iv = new byte[16]; r.nextBytes(iv); return iv; }
public static byte[] generateIV(){ return generatePasswordSalt(16); }
251
public String myProducts(Model model, Principal principal){ getLoggedUser(principal); List<Product> products = productService.getProducts().stream().filter(product -> product.getUser().getId().equals(getLoggedUser(principal).getId())).collect(Collectors.toList()); model.addAttribute("products", products); return "my-products-page"; }
public String myProducts(Model model, Principal principal){ model.addAttribute("products", productService.getProductByUserId(getLoggedUser(principal).getId())); return "my-products-page"; }
252
public void positiveEvaluateGreaterThanEqualsToOperatorTest() throws Exception{ Map<String, Object> attributes = new HashMap<>(); attributes.put("age", 25); String feature = "Age Greater than EqualsTo Feature"; String expression = "age >= 25"; final GatingValidator validator = new GatingValidator(); Assert.assertTrue(validator.isAllowed(expression, feature, attributes)); }
public void positiveEvaluateGreaterThanEqualsToOperatorTest() throws Exception{ Map<String, Object> attributes = new HashMap<>(); attributes.put("age", 25); String feature = "Age Greater than EqualsTo Feature"; String expression = "age >= 25"; Assert.assertTrue(validator.isAllowed(expression, feature, attributes)); }
253
public void addIdentifier(NodeIdentifier pNode){ LOGGER.trace("Method addIdentifier(" + pNode + ") called."); if (!mMapNode.containsKey(pNode)) { PText vText = new PText(mIdentifierInformationStrategy.getText(pNode.getIdentifier())); vText.setHorizontalAlignment(Component.CENTER_ALIGNMENT); vText.setTextPaint(getColorIdentifierText(pNode)); vText.setFont(new Font(null, Font.PLAIN, mFontSize)); vText.setOffset(-0.5F * (float) vText.getWidth(), -0.5F * (float) vText.getHeight()); final PPath vNode = PPath.createRoundRectangle(-5 - 0.5F * (float) vText.getWidth(), -5 - 0.5F * (float) vText.getHeight(), (float) vText.getWidth() + 10, (float) vText.getHeight() + 10, 20.0f, 20.0f); vNode.setPaint(getColor(vNode, pNode)); vNode.setStrokePaint(getColorIdentifierStroke(pNode)); final PComposite vCom = new PComposite(); vCom.addChild(vNode); vCom.addChild(vText); vCom.setOffset(mAreaOffsetX + pNode.getX() * mAreaWidth, mAreaOffsetY + pNode.getY() * mAreaHeight); vCom.addAttribute("type", NodeType.IDENTIFIER); vCom.addAttribute("position", pNode); vCom.addAttribute("edges", new ArrayList<ArrayList<PPath>>()); mMapNode.put(pNode, vCom); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mLayerNode.addChild(vCom); } }); } }
public void addIdentifier(NodeIdentifier pNode){ LOGGER.trace("Method addIdentifier(" + pNode + ") called."); if (!mMapNode.containsKey(pNode)) { PText vText = new PText(mIdentifierInformationStrategy.getText(pNode.getIdentifier())); vText.setHorizontalAlignment(Component.CENTER_ALIGNMENT); vText.setTextPaint(getColorIdentifierText(pNode)); vText.setFont(new Font(null, Font.PLAIN, mFontSize)); vText.setOffset(-0.5F * (float) vText.getWidth(), -0.5F * (float) vText.getHeight()); final PPath vNode = PPath.createRoundRectangle(-5 - 0.5F * (float) vText.getWidth(), -5 - 0.5F * (float) vText.getHeight(), (float) vText.getWidth() + 10, (float) vText.getHeight() + 10, 20.0f, 20.0f); final PComposite vCom = new PComposite(); vCom.addChild(vNode); vCom.addChild(vText); vCom.setOffset(mAreaOffsetX + pNode.getX() * mAreaWidth, mAreaOffsetY + pNode.getY() * mAreaHeight); vCom.addAttribute("type", NodeType.IDENTIFIER); vCom.addAttribute("position", pNode); vCom.addAttribute("edges", new ArrayList<ArrayList<PPath>>()); paintIdentifierNode(pNode.getIdentifier(), pNode, vNode, vText); mMapNode.put(pNode, vCom); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mLayerNode.addChild(vCom); } }); } }
254
public void testingLeavingTheVehicleWhenSlotIdIsNull() throws Exception{ ParkingService instance = new ParkingServiceImpl(); String output = instance.createParkingLot(1); assertTrue("Createdparkingof1slots".equalsIgnoreCase(output.trim().replace(" ", ""))); VehicleDetails vehicleDetails1 = new CarDetails("KA-01-HH-1234"); DriverDetails driverDetails1 = new DriverDetails(21L); String parkingVehicleOutput = instance.parkVehicle(vehicleDetails1, driverDetails1); assertTrue("CarwithvehicleregistrationNumberKA-01-HH-1234hasbeenparkedatslotnumber1".equalsIgnoreCase(parkingVehicleOutput.trim().replace(" ", ""))); thrownExpectedException.expect(ParkingLotException.class); thrownExpectedException.expectMessage(is("slotId cannot be null or empty")); instance.leaveVehicle(null); instance.destroy(); }
public void testingLeavingTheVehicleWhenSlotIdIsNull() throws Exception{ ParkingService instance = new ParkingServiceImpl(); String output = instance.createParkingLot(1); assertTrue("Createdparkingof1slots".equalsIgnoreCase(output.trim().replace(" ", ""))); VehicleDetails vehicleDetails1 = new CarDetails("KA-01-HH-1234"); DriverDetails driverDetails1 = new DriverDetails(21L); String parkingVehicleOutput = instance.parkVehicle(vehicleDetails1, driverDetails1); assertTrue("CarwithvehicleregistrationNumberKA-01-HH-1234hasbeenparkedatslotnumber1".equalsIgnoreCase(parkingVehicleOutput.trim().replace(" ", ""))); thrownExpectedException.expect(ParkingLotException.class); thrownExpectedException.expectMessage(is("slotId cannot be null or empty")); instance.leaveVehicle(null); }
255
public ASTNode visitExprList(final ExprListContext ctx){ ListExpression result = new ListExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); if (null != ctx.exprList()) { result.getItems().addAll(((ListExpression) visitExprList(ctx.exprList())).getItems()); } result.getItems().add((ExpressionSegment) visit(ctx.aExpr())); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; }
public ASTNode visitExprList(final ExprListContext ctx){ ListExpression result = new ListExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); if (null != ctx.exprList()) { result.getItems().addAll(((ListExpression) visitExprList(ctx.exprList())).getItems()); } result.getItems().add((ExpressionSegment) visit(ctx.aExpr())); return result; }
256
private String formatOrder(Order order){ StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"id\": "); sb.append(order.getOrderId()); sb.append(", "); sb.append("\"products\": ["); for (int j = 0; j < order.getProductsCount(); j++) { Product product = order.getProduct(j); sb.append("{"); sb.append("\"code\": \""); sb.append(product.getCode()); sb.append("\", "); sb.append("\"color\": \""); sb.append(getColorFor(product)); sb.append("\", "); if (product.getSize() != Product.SIZE_NOT_APPLICABLE) { sb.append("\"size\": \""); sb.append(getSizeFor(product)); sb.append("\", "); } sb.append("\"price\": "); sb.append(product.getPrice()); sb.append(", "); sb.append("\"currency\": \""); sb.append(product.getCurrency()); sb.append("\"}, "); } if (order.getProductsCount() > 0) { sb.delete(sb.length() - 2, sb.length()); } sb.append("]"); sb.append("}, "); return sb.toString(); }
private String formatOrder(Order order){ StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append(formatField("id", order.getOrderId())); sb.append(", "); sb.append("\"products\": ["); for (int j = 0; j < order.getProductsCount(); j++) { Product product = order.getProduct(j); sb.append("{"); sb.append(formatField("code", product.getCode())); sb.append(", "); sb.append(formatField("color", getColorFor(product))); sb.append(", "); if (product.getSize() != Product.SIZE_NOT_APPLICABLE) { sb.append(formatField("size", getSizeFor(product))); sb.append(", "); } sb.append(formatField("price", product.getPrice())); sb.append(", "); sb.append(formatField("currency", product.getCurrency())); sb.append("}, "); } if (order.getProductsCount() > 0) { sb.delete(sb.length() - 2, sb.length()); } sb.append("]"); sb.append("}, "); return sb.toString(); }
257
void requestBuildRIDList(){ if (!isBuilt()) { if (!request_processing) { request_processing = true; system.postEvent(10000, system.createEvent(new Runnable() { public void run() { createRIDCache(); } })); } } }
void requestBuildRIDList(){ if (!isBuilt()) { if (!request_processing) { request_processing = true; system.postEvent(10000, system.createEvent(() -> createRIDCache())); } } }
258
public Mono<HttpResponse> send(final HttpRequest request){ Objects.requireNonNull(request.httpMethod()); Objects.requireNonNull(request.url()); Objects.requireNonNull(request.url().getProtocol()); Objects.requireNonNull(this.httpClientConfig); return this.httpClient.port(request.port()).request(HttpMethod.valueOf(request.httpMethod().toString())).uri(request.url().toString()).send(bodySendDelegate(request)).responseConnection(responseDelegate(request)).single(); }
public Mono<HttpResponse> send(final HttpRequest request){ Objects.requireNonNull(request.httpMethod()); Objects.requireNonNull(request.uri()); Objects.requireNonNull(this.httpClientConfig); return this.httpClient.port(request.port()).request(HttpMethod.valueOf(request.httpMethod().toString())).uri(request.uri().toString()).send(bodySendDelegate(request)).responseConnection(responseDelegate(request)).single(); }
259
public static Graph bipartite(int V1, int V2, double p){ if (p < 0.0 || p > 1.0) throw new IllegalArgumentException("Probability must be between 0 and 1"); int[] vertices = new int[V1 + V2]; for (int i = 0; i < V1 + V2; i++) vertices[i] = i; StdRandom.shuffle(vertices); Graph G = new GraphImpl(V1 + V2); for (int i = 0; i < V1; i++) for (int j = 0; j < V2; j++) if (StdRandom.bernoulli(p)) G.addEdge(vertices[i], vertices[V1 + j]); return G; }
public static Graph bipartite(int V1, int V2, double p){ checkArgument(p >= 0.0 && p <= 1.0, "Probability must be between 0 and 1"); int[] vertices = new int[V1 + V2]; for (int i = 0; i < V1 + V2; i++) vertices[i] = i; StdRandom.shuffle(vertices); Graph G = new GraphImpl(V1 + V2); for (int i = 0; i < V1; i++) for (int j = 0; j < V2; j++) if (StdRandom.bernoulli(p)) G.addEdge(vertices[i], vertices[V1 + j]); return G; }
260
private List<List<HarryPotterBook>> fillBookLists(List<HarryPotterBook> books){ List<List<HarryPotterBook>> qttByBook = new ArrayList<>(); for (HarryPotterBook book : books) { boolean added = false; int i = 0; while (!added && i < qttByBook.size()) { added = addIfNotExists(book, qttByBook.get(i)); i++; } if (i == qttByBook.size() && !added) { qttByBook.add(createNewList(book)); } } return qttByBook; }
private List<List<HarryPotterBook>> fillBookLists(List<HarryPotterBook> books){ List<List<HarryPotterBook>> qttByBook = new ArrayList<>(); for (HarryPotterBook book : books) { boolean added = false; for (int i = 0; !added && i < qttByBook.size(); i++) { added = addIfNotExists(book, qttByBook.get(i)); } if (!added) { qttByBook.add(createNewList(book)); } } return qttByBook; }
261
public static void setup() throws InterruptedException{ chain = new BlockchainImpl(MemoryDB.FACTORY); ChannelManager channelMgr = new ChannelManager(); PendingManager pendingMgr = new PendingManager(chain, channelMgr); pendingMgr.start(); bft = SemuxBFT.getInstance(); coinbase = new EdDSA(); bft.init(chain, channelMgr, pendingMgr, coinbase); new Thread(() -> { bft.start(); }, "cons").start(); Thread.sleep(200); }
public static void setup() throws InterruptedException{ chain = new BlockchainImpl(MemoryDB.FACTORY); ChannelManager channelMgr = new ChannelManager(); PendingManager pendingMgr = new PendingManager(chain, channelMgr); pendingMgr.start(); bft = SemuxBFT.getInstance(); coinbase = new EdDSA(); bft.init(chain, channelMgr, pendingMgr, coinbase); new Thread(() -> bft.start(), "cons").start(); Thread.sleep(200); }
262
private void setCell(SetCell setCell){ log().debug("{}", setCell); removeInRow(setCell); removeInCol(setCell); removeInBox(setCell); if (monitoredCells.isEmpty()) { monitoringComplete(); } else if (monitoredCells.size() == 1) { Cell cell = monitoredCells.get(0); String who = String.format("Set by row (%d, %d) = %d", cell.row, cell.col, cell.value); getSender().tell(new SetCell(cell.row, cell.col, monitoredValue, who), getSelf()); monitoringComplete(); } }
private void setCell(SetCell setCell){ removeInRow(setCell); removeInCol(setCell); removeInBox(setCell); if (monitoredCells.isEmpty()) { monitoringComplete(); } else if (monitoredCells.size() == 1) { Cell cell = monitoredCells.get(0); String who = String.format("Set by row (%d, %d) = %d", cell.row, cell.col, cell.value); getSender().tell(new SetCell(cell.row, cell.col, monitoredValue, who), getSelf()); monitoringComplete(); } }
263
public void analyzeWithClassVisitor(File pluginFile, ClassVisitor aClassVisitor) throws IOException{ final WarReader warReader = new WarReader(pluginFile, true); try { String fileName = warReader.nextClass(); while (fileName != null) { analyze(warReader.getInputStream(), aClassVisitor); fileName = warReader.nextClass(); } } finally { warReader.close(); } }
public void analyzeWithClassVisitor(File pluginFile, ClassVisitor aClassVisitor) throws IOException{ try (WarReader warReader = new WarReader(pluginFile, true)) { String fileName = warReader.nextClass(); while (fileName != null) { analyze(warReader.getInputStream(), aClassVisitor); fileName = warReader.nextClass(); } } }
264
public ChannelInstance getRoundRobinChannel(){ if (channelKeyList == null || channelKeyList.size() == 0) { return null; } Channel channel = null; InstanceDetails instanceDetails = null; String channelKey = null; while (channel == null) { try { if (channelKeyList.size() == 0) { return null; } int number = roundRobinLong.getAndIncrement(); int index = number % channelKeyList.size(); System.out.println("index=number/size, [" + number + "/" + channelKeyList.size() + "]" + ", index=" + index); channelKey = channelKeyList.get(index); instanceDetails = channelInstanceMap.get(channelKey); channel = channelMap.get(channelKey); } catch (Exception e) { channel = null; e.printStackTrace(); } } System.out.println("use roundRobin algorithm to find an channel, channelKey=" + channelKey + ", instanceDetails=" + instanceDetails); return new ChannelInstance(channel, instanceDetails); }
public ChannelInstance getRoundRobinChannel(){ if (channelKeyList == null || channelKeyList.size() == 0) { return null; } String channelKey = null; ChannelInstance channelInstance = null; while (channelInstance == null) { try { if (channelKeyList.size() == 0) { return null; } int number = roundRobinLong.getAndIncrement(); int index = number % channelKeyList.size(); System.out.println("index=number/size, [" + number + "/" + channelKeyList.size() + "]" + ", index=" + index); channelKey = channelKeyList.get(index); channelInstance = channelInstanceMap.get(channelKey); } catch (Exception e) { channelInstance = null; e.printStackTrace(); } } System.out.println("use roundRobin algorithm to find an channelInstance=" + channelInstance); return channelInstance; }
265
public Result encode(String sourceFilename, String destinationFilename){ log.info("Start encoding " + sourceFilename); Result res = new Result(); fileEncoder.encode(sourceFilename, destinationFilename, res); if (res.getInf().get(0).getCode() != -1) { log.info("Stop encoding file " + sourceFilename); } else { emailClient.sendFailedMessage(sourceFilename); } return res; }
public Result encode(String sourceFilename, String destinationFilename){ log.info("Start encoding " + sourceFilename); Result res = fileEncoder.encode(sourceFilename, destinationFilename); if (res.isSuccessful()) { log.info("Stop encoding file " + sourceFilename); } else { emailClient.sendFailedMessage(sourceFilename); } return res; }
266
public Optional<DictionaryAttributeValDto> findByProductIdAndAttributeDicId(String attributeValTableName, Long productId, Long attributeDicId){ final String sqlQuery = String.format("select id, value, attribute_dic_id, attribute_link_id, product_id from %s where product_id = ? and attribute_dic_id = ?", attributeValTableName); return jdbcTemplate.queryForObject(sqlQuery, (rs, rowNum) -> { DictionaryAttributeValDto dto = new DictionaryAttributeValDto(); dto.setAttributeId(rs.getLong("id")).setAttributeValue(rs.getString("value")).setAttributeDicId(rs.getLong("attribute_dic_id")).setAttributeLinkId(rs.getLong("attribute_link_id")).setProductId(rs.getLong("product_id")); return Optional.of(dto); }, productId, attributeDicId); }
public Optional<DictionaryAttributeValDto> findByProductIdAndAttributeDicId(String attributeValTableName, Long productId, Long attributeDicId){ final String sqlQuery = String.format("select id, value, attribute_dic_id, attribute_link_id, product_id from %s where product_id = ? and attribute_dic_id = ?", attributeValTableName); return jdbcTemplate.queryForObject(sqlQuery, (rs, rowNum) -> Optional.of(new DictionaryAttributeValDto().setAttributeId(rs.getLong("id")).setAttributeValue(rs.getString("value")).setAttributeDicId(rs.getLong("attribute_dic_id")).setAttributeLinkId(rs.getLong("attribute_link_id")).setProductId(rs.getLong("product_id"))), productId, attributeDicId); }
267
private Single<DatabaseAccount> getDatabaseAccountAsync(URL serviceEndpoint){ HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); UserAgentContainer userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent()); httpHeaders.set(HttpConstants.HttpHeaders.API_TYPE, Constants.Properties.SQL_API_TYPE); String authorizationToken = StringUtils.EMPTY; if (this.hasAuthKeyResourceToken || baseAuthorizationTokenProvider == null) { authorizationToken = HttpUtils.urlEncode(this.authKeyResourceToken); } else { String xDate = Utils.nowAsRFC1123(); httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, xDate); Map<String, String> header = new HashMap<>(); header.put(HttpConstants.HttpHeaders.X_DATE, xDate); try { authorizationToken = baseAuthorizationTokenProvider.generateKeyAuthorizationSignature(HttpConstants.HttpMethods.GET, serviceEndpoint.toURI(), header); } catch (URISyntaxException e) { e.printStackTrace(); } } httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, serviceEndpoint, serviceEndpoint.getPort()).withHeaders(httpHeaders); Mono<HttpResponse> httpResponse = httpClient.send(httpRequest); return toDatabaseAccountObservable(httpResponse); }
private Single<DatabaseAccount> getDatabaseAccountAsync(URI serviceEndpoint){ HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.set(HttpConstants.HttpHeaders.VERSION, HttpConstants.Versions.CURRENT_VERSION); UserAgentContainer userAgentContainer = new UserAgentContainer(); String userAgentSuffix = this.connectionPolicy.getUserAgentSuffix(); if (userAgentSuffix != null && userAgentSuffix.length() > 0) { userAgentContainer.setSuffix(userAgentSuffix); } httpHeaders.set(HttpConstants.HttpHeaders.USER_AGENT, userAgentContainer.getUserAgent()); httpHeaders.set(HttpConstants.HttpHeaders.API_TYPE, Constants.Properties.SQL_API_TYPE); String authorizationToken; if (this.hasAuthKeyResourceToken || baseAuthorizationTokenProvider == null) { authorizationToken = HttpUtils.urlEncode(this.authKeyResourceToken); } else { String xDate = Utils.nowAsRFC1123(); httpHeaders.set(HttpConstants.HttpHeaders.X_DATE, xDate); Map<String, String> header = new HashMap<>(); header.put(HttpConstants.HttpHeaders.X_DATE, xDate); authorizationToken = baseAuthorizationTokenProvider.generateKeyAuthorizationSignature(HttpConstants.HttpMethods.GET, serviceEndpoint, header); } httpHeaders.set(HttpConstants.HttpHeaders.AUTHORIZATION, authorizationToken); HttpRequest httpRequest = new HttpRequest(HttpMethod.GET, serviceEndpoint, serviceEndpoint.getPort(), httpHeaders); Mono<HttpResponse> httpResponse = httpClient.send(httpRequest); return toDatabaseAccountObservable(httpResponse); }
268
private void setTooltip(final T component, final TooltipStateData state){ if (component == null) { throw new IllegalArgumentException("Tooltips4Vaadin requires a non null component in order to set a tooltip"); } final boolean attached = component.getElement().getNode().isAttached(); final Page page = ui.getPage(); if (state.getCssClass() != null) { ensureCssClassIsSet(state); if (attached) { TooltipsUtil.securelyAccessUI(ui, () -> page.executeJs(JS_METHODS.UPDATE_TOOLTIP, state.getCssClass(), state.getTooltipConfig().toJson()).then(json -> setTippyId(state, json))); } } else { String uniqueClassName = CLASS_PREFIX + state.getTooltipId(); component.addClassName(uniqueClassName); state.setCssClass(uniqueClassName); Runnable register = () -> TooltipsUtil.securelyAccessUI(ui, () -> { ensureCssClassIsSet(state); page.executeJs(JS_METHODS.SET_TOOLTIP, state.getCssClass(), state.getTooltipConfig().toJson()).then(json -> setTippyId(state, json), err -> log.fine(() -> "Tooltips: js error: " + err)); }); if (attached) { register.run(); } Registration attachReg = component.addAttachListener(evt -> register.run()); state.setAttachReg(new WeakReference<>(attachReg)); Registration detachReg = component.addDetachListener(evt -> TooltipsUtil.securelyAccessUI(ui, () -> closeFrontendTooltip(state, Optional.empty()))); state.setDetachReg(new WeakReference<>(detachReg)); } }
private void setTooltip(final T component, final TooltipStateData tooltipState){ if (component == null) { throw new IllegalArgumentException("Tooltips4Vaadin requires a non null component in order to set a tooltip"); } if (tooltipState.getCssClass() != null) { updateKnownComponent(component, tooltipState); } else { initiallySetupComponent(component, tooltipState); } }
269
void setUp(){ vc = new VigenereCipher(key); ; }
void setUp(){ vc = new VigenereCipher(key); }
270
public PowerHost findHostForVm(Vm vm, Set<? extends Host> excludedHosts){ Comparator<PowerHost> hostPowerConsumptionComparator = (h1, h2) -> { double h1PowerDiff = getPowerAfterAllocationDifference(h1, vm); double h2PowerDiff = getPowerAfterAllocationDifference(h2, vm); return (int) Math.ceil(h1PowerDiff - h2PowerDiff); }; return this.<PowerHost>getHostList().stream().filter(h -> !excludedHosts.contains(h)).filter(h -> h.isSuitableForVm(vm)).filter(h -> !isHostOverUtilizedAfterAllocation(h, vm)).filter(h -> getPowerAfterAllocation(h, vm) > 0).min(hostPowerConsumptionComparator).orElse(PowerHost.NULL); }
public PowerHost findHostForVm(Vm vm, Set<? extends Host> excludedHosts){ Comparator<PowerHost> hostPowerConsumptionComparator = (h1, h2) -> Double.compare(getPowerAfterAllocationDifference(h1, vm), getPowerAfterAllocationDifference(h2, vm)); return this.<PowerHost>getHostList().stream().filter(h -> !excludedHosts.contains(h)).filter(h -> h.isSuitableForVm(vm)).filter(h -> !isHostOverUtilizedAfterAllocation(h, vm)).filter(h -> getPowerAfterAllocation(h, vm) > 0).min(hostPowerConsumptionComparator).orElse(PowerHost.NULL); }
271
public void createMilestone(Milestone m) throws TracRpcException{ Object[] params = new Object[] { m.getName(), m.getAttribs() }; Integer result = (Integer) this.call("ticket.milestone.create", params); if (result > 0) { throw new TracRpcException("ticket.milestone.create returned error " + result.toString()); } }
public void createMilestone(Milestone m) throws TracRpcException{ this.sendBasicStruct(m, "ticket.milestone.create"); }
272
public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String name = FxNodeValueUtils.getStringOrThrow(srcObj, "name"); FxNode template = FxNodeValueUtils.getOrThrow(srcObj, "template"); FxNode templateCopy = FxNodeCopyVisitor.cloneMemNode(template); FxReplaceTemplateCopyFunc macroFunc = new FxReplaceTemplateCopyFunc(templateCopy); ctx.getFuncRegistry().registerFunc(name, macroFunc); return null; }
public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; String name = FxNodeValueUtils.getStringOrThrow(srcObj, "name"); FxNode template = FxNodeValueUtils.getOrThrow(srcObj, "template"); FxNode templateCopy = FxNodeCopyVisitor.cloneMemNode(template); FxReplaceTemplateCopyFunc macroFunc = new FxReplaceTemplateCopyFunc(templateCopy); ctx.getFuncRegistry().registerFunc(name, macroFunc); }
273
public AppResponse getAccountByAccountNumber(String accountNumber){ Logger.debug("Starting deleteAccountByAccountNumber() in AccountServiceImpl for [{}]", accountNumber); AppResponse resp = null; if (StringUtils.isNullOrEmpty(accountNumber)) { Logger.error("Failed to get the account as the account number is null/empty"); return new AppResponse(false, "Failed to delete the account as the account number is null/empty", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, "Account Number is found null/empty")); } resp = accountDao.getAccountByAccountNumber(accountNumber); if (!resp.isStatus() || resp.getData() == null) { Logger.error("Failed to get as the account is not found"); return new AppResponse(false, "Failed to get as the account is not found", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, "Account is not found in db for requested account number")); } resp = accountDao.deleteAccountByAccountNumber(accountNumber); if (!resp.isStatus()) { return new AppResponse(false, "Account not found in Db", resp.getError()); } Logger.info("Account deleted successfully having account number [{}]", accountNumber); return resp; }
public AppResponse getAccountByAccountNumber(String accountNumber){ Logger.debug("Starting getAccountByAccountNumber() in AccountServiceImpl for [{}]", accountNumber); AppResponse resp = null; if (StringUtils.isNullOrEmpty(accountNumber)) { Logger.error("Failed to get the account as the account number is null/empty"); return new AppResponse(false, "Failed to delete the account as the account number is null/empty", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, "Account Number is found null/empty")); } resp = accountDao.getAccountByAccountNumber(accountNumber); if (!resp.isStatus() || resp.getData() == null) { Logger.error("Failed to get as the account is not found"); return new AppResponse(false, "Failed to get as the account is not found", new ErrorDetails(Constants.ERROR_CODE_VALIDATION, "Account is not found in db for requested account number")); } Account acc = (Account) resp.getData(); Logger.info("Account fetched successfully having account number [{}]", acc); return resp; }
274
public void run(){ System.out.println(getName() + " - start"); try { final String table = createTable(); final String path = getPath(); final Loader loader = new Loader(path, table); loader.write(); } catch (Exception ex) { ex.printStackTrace(); } System.out.println(getName() + " - DONE"); }
public void run(){ System.out.println(getName() + " - start"); try { final String table = createTable(); saveTable(table); } catch (Exception ex) { ex.printStackTrace(); } System.out.println(getName() + " - DONE"); }
275
protected void processStop(){ terminating = true; if (sockets == 0) { sendDone(); poller.removeHandle(mailboxHandle); poller.stop(); } }
protected void processStop(){ terminating = true; if (socketsReaping == 0) { finishTerminating(); } }
276
public Builder id(final String id){ assert (id != null); assert (!id.equals("")); return setPathParameter("id", id); }
public Builder id(final String id){ assertHasAndNotNull(id); return setPathParameter("id", id); }
277
private boolean checkUser(String username, String password){ User user = userDao.getUser(username, 0); if (user == null) { return false; } return BCrypt.checkpw(password, user.getPswd()); }
private boolean checkUser(String username, String password){ User user = userDao.getUser(username, 0); return user != null && BCrypt.checkpw(password, user.getPswd()); }
278
protected void validate(final Task entity) throws ServiceException{ try { Assert.notNull(entity, "The class must not be null"); Assert.hasText(entity.getDescription(), "'description' must not be empty"); Assert.hasText(entity.getType(), "'type' must not be empty"); TaskType.validate(entity.getType()); if (entity.getHelper() != null) RenderType.validate(entity.getHelper().getRenderType()); } catch (final Exception e) { throw new ServiceException(e.getMessage(), e); } }
protected void validate(final Task entity) throws ServiceException{ try { Assert.notNull(entity, "The class must not be null"); Assert.notNull(entity.getType(), "'type' must not be empty"); Assert.hasText(entity.getDescription(), "'description' must not be empty"); if (entity.getHelper() != null) RenderType.validate(entity.getHelper().getRenderType()); } catch (final Exception e) { throw new ServiceException(e.getMessage(), e); } }
279
public boolean mutate(TestCase test, TestFactory factory){ JsonElement oldVal = this.jsonElement; int lim = 4; int current = 0; while (this.jsonElement.equals(oldVal) && current < lim) { if (Randomness.nextDouble() <= Properties.RANDOM_PERTURBATION) { randomize(); } else { delta(); } current++; } this.value = gson.toJson(this.jsonElement); return true; }
public boolean mutate(TestCase test, TestFactory factory){ JsonElement oldVal = this.jsonElement; int current = 0; while (this.jsonElement.equals(oldVal) && current < Properties.GRAMMAR_JSON_MUTATION_RETRY_LIMIT) { if (Randomness.nextDouble() <= Properties.RANDOM_PERTURBATION) { this.randomize(); } else { this.delta(); } current++; } this.value = gson.toJson(this.jsonElement); return true; }
280
protected PStmtKey createKey(final String sql, final String[] columnNames){ String catalog = null; try { catalog = getCatalog(); } catch (final SQLException e) { } return new PStmtKey(normalizeSQL(sql), catalog, columnNames); }
protected PStmtKey createKey(final String sql, final String[] columnNames){ return new PStmtKey(normalizeSQL(sql), getCatalogOrNull(), columnNames); }
281
public Optional<User> create(Map<String, String> fields){ Optional<User> result = Optional.empty(); if (isRegisterFormValid(fields)) { String email = fields.get(RequestParameter.EMAIL); String firstName = fields.get(RequestParameter.FIRST_NAME); String lastName = fields.get(RequestParameter.LAST_NAME); String dateOfBirth = fields.get(RequestParameter.DATE_OF_BIRTH); String phoneNumber = fields.get(RequestParameter.PHONE_NUMBER); User user = new User(DEFAULT_ROLE, DEFAULT_ACTIVE_VALUE, DEFAULT_PHOTO_NAME, firstName, lastName, LocalDate.parse(dateOfBirth), phoneNumber, email); result = Optional.of(user); } return result; }
public Optional<User> create(Map<String, String> fields){ Optional<User> result = Optional.empty(); if (isRegisterFormValid(fields)) { String email = fields.get(RequestParameter.EMAIL); String firstName = fields.get(RequestParameter.FIRST_NAME); String lastName = fields.get(RequestParameter.LAST_NAME); String dateOfBirth = fields.get(RequestParameter.DATE_OF_BIRTH); String phoneNumber = fields.get(RequestParameter.PHONE_NUMBER); result = Optional.of(new User(DEFAULT_ROLE, DEFAULT_ACTIVE_VALUE, DEFAULT_PHOTO_NAME, firstName, lastName, LocalDate.parse(dateOfBirth), phoneNumber, email)); } return result; }
282
protected void addColumnValue(PrintWriter writer, DataTable table, List<UIComponent> components, String tag, UIColumn column) throws IOException{ FacesContext context = FacesContext.getCurrentInstance(); writer.append("\t\t<" + tag + ">"); if (LangUtils.isNotBlank(column.getExportValue())) { writer.append(EscapeUtils.forXml(column.getExportValue())); } else if (column.getExportFunction() != null) { writer.append(EscapeUtils.forXml(exportColumnByFunction(context, column))); } else if (LangUtils.isNotBlank(column.getField())) { String value = table.getConvertedFieldValue(context, column); writer.append(EscapeUtils.forXml(Objects.toString(value, Constants.EMPTY_STRING))); } else { for (UIComponent component : components) { if (component.isRendered()) { String value = exportValue(context, component); if (value != null) { writer.append(EscapeUtils.forXml(value)); } } } } writer.append("</" + tag + ">\n"); }
protected void addColumnValue(PrintWriter writer, DataTable table, List<UIComponent> components, String tag, UIColumn column) throws IOException{ FacesContext context = FacesContext.getCurrentInstance(); writer.append("\t\t<" + tag + ">"); exportColumn(context, table, column, components, false, (s) -> writer.append(EscapeUtils.forXml(s))); writer.append("</" + tag + ">\n"); }
283
public void testConstructor() throws Exception{ Constructor<?> constructor = MoreIterables.class.getDeclaredConstructor(); assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); Throwable thrown = catchThrowable(constructor::newInstance); assertThat(thrown).isInstanceOf(InvocationTargetException.class); assertThat(thrown.getCause()).isExactlyInstanceOf(IllegalStateException.class).hasMessage("This class should not be instantiated"); }
public void testConstructor() throws Exception{ Constructor<?> constructor = MoreIterables.class.getDeclaredConstructor(); assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue(); constructor.setAccessible(true); assertThat(catchThrowable(constructor::newInstance)).isInstanceOf(InvocationTargetException.class).hasCauseExactlyInstanceOf(IllegalStateException.class); }
284
public void execute(){ vertx.runOnContext(action -> { Optional.ofNullable(excecuteEventBusAndReply).ifPresent(evFunction -> { try { evFunction.execute(vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount); } catch (Exception e) { e.printStackTrace(); } }); Optional.ofNullable(byteSupplier).ifPresent(supplier -> { int retry = retryCount; byte[] result = new byte[0]; boolean errorHandling = false; while (retry >= 0) { try { result = supplier.get(); retry = -1; } catch (Throwable e) { retry--; if (retry < 0) { result = RESTExecutionUtil.handleError(result, errorHandler, onFailureRespond, errorMethodHandler, e); errorHandling = true; } else { RESTExecutionUtil.handleError(errorHandler, e); } } } if (errorHandling && result == null) return; repond(result); }); }); }
public void execute(){ vertx.runOnContext(action -> { Optional.ofNullable(excecuteEventBusAndReply).ifPresent(evFunction -> { try { evFunction.execute(vertx, t, errorMethodHandler, context, headers, encoder, errorHandler, onFailureRespond, httpStatusCode, retryCount); } catch (Exception e) { e.printStackTrace(); } }); Optional.ofNullable(byteSupplier).ifPresent(supplier -> { int retry = retryCount; byte[] result = null; Optional.ofNullable(ResponseUtil.createResponse(retry, result, supplier, errorHandler, onFailureRespond, errorMethodHandler)).ifPresent(res -> repond(res)); }); }); }
285
public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; int startIndex = FxNodeValueUtils.getOrDefault(srcObj, "start", 0); int incr = FxNodeValueUtils.getOrDefault(srcObj, "incr", 1); int endIndex = FxNodeValueUtils.getIntOrThrow(srcObj, "end"); String iterIndexName = FxNodeValueUtils.getOrDefault(srcObj, "indexName", "index"); FxNode templateNode = srcObj.get("template"); if (incr == 0 || (incr > 0 && endIndex < startIndex) || (incr < 0 && endIndex > startIndex)) { throw new IllegalArgumentException(); } if (templateNode == null) { return null; } FxArrayNode res = dest.addArray(); FxChildWriter resChildAdder = res.insertBuilder(); FxMemRootDocument tmpDoc = new FxMemRootDocument(); FxObjNode tmpObj = tmpDoc.setContentObj(); FxIntNode tmpIndexNode = tmpObj.put(iterIndexName, 0); FxEvalContext childCtx = ctx.createChildContext(); Map<String, FxNode> replVars = new HashMap<String, FxNode>(); replVars.put(iterIndexName, tmpIndexNode); FxVarsReplaceFunc replaceVarsFunc = new FxVarsReplaceFunc(replVars); for (int index = startIndex; ((incr > 0) ? (index < endIndex) : (index > endIndex)); index += incr) { tmpIndexNode.setValue(index); childCtx.putVariable(iterIndexName, index); replaceVarsFunc.eval(resChildAdder, childCtx, templateNode); } return res; }
public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){ FxObjNode srcObj = (FxObjNode) src; int startIndex = FxNodeValueUtils.getOrDefault(srcObj, "start", 0); int incr = FxNodeValueUtils.getOrDefault(srcObj, "incr", 1); int endIndex = FxNodeValueUtils.getIntOrThrow(srcObj, "end"); String iterIndexName = FxNodeValueUtils.getOrDefault(srcObj, "indexName", "index"); FxNode templateNode = srcObj.get("template"); if (incr == 0 || (incr > 0 && endIndex < startIndex) || (incr < 0 && endIndex > startIndex)) { throw new IllegalArgumentException(); } if (templateNode == null) { return; } FxArrayNode res = dest.addArray(); FxChildWriter resChildAdder = res.insertBuilder(); FxMemRootDocument tmpDoc = new FxMemRootDocument(); FxObjNode tmpObj = tmpDoc.setContentObj(); FxIntNode tmpIndexNode = tmpObj.put(iterIndexName, 0); FxEvalContext childCtx = ctx.createChildContext(); Map<String, FxNode> replVars = new HashMap<String, FxNode>(); replVars.put(iterIndexName, tmpIndexNode); FxVarsReplaceFunc replaceVarsFunc = new FxVarsReplaceFunc(replVars); for (int index = startIndex; ((incr > 0) ? (index < endIndex) : (index > endIndex)); index += incr) { tmpIndexNode.setValue(index); childCtx.putVariable(iterIndexName, index); replaceVarsFunc.eval(resChildAdder, childCtx, templateNode); } }
286
public Builder id(final String id){ assert (id != null); assert (!id.equals("")); return setPathParameter("id", id); }
public Builder id(final String id){ assertHasAndNotNull(id); return setPathParameter("id", id); }
287
private List<Map<String, String>> querySource(String query, int maxResults) throws InternalErrorException, FileNotFoundException, IOException{ List<Map<String, String>> subjects = new ArrayList<>(); int index = query.indexOf("="); int indexContains = query.indexOf("contains"); if (index != -1) { String queryType = query.substring(0, index); String value = query.substring(index + 1); switch(queryType) { case "id": subjects = executeQueryTypeID(value, maxResults); break; case "email": subjects = executeQueryTypeEmail(value, maxResults); break; case "group": subjects = executeQueryTypeGroupSubjects(value, maxResults); break; default: throw new IllegalArgumentException("Word before '=' symbol can be 'id' or 'email' or 'group', nothing else."); } } else { if (indexContains != -1) { String queryType = query.substring(0, indexContains).trim(); String value = query.substring(indexContains + "contains".trim().length()); if (queryType.equals("email")) { subjects = executeQueryTypeContains(value.trim()); } else { throw new IllegalArgumentException("Search for substrings is possible only for 'email' attribute."); } } else { throw new InternalErrorException("Wrong query!"); } } return subjects; }
private void querySource(String query, int maxResults, List<Map<String, String>> subjects) throws InternalErrorException, FileNotFoundException, IOException{ int index = query.indexOf("="); int indexContains = query.indexOf("contains"); if (index != -1) { String queryType = query.substring(0, index); String value = query.substring(index + 1); switch(queryType) { case "id": executeQueryTypeID(value, maxResults, subjects); break; case "email": executeQueryTypeEmail(value, maxResults, subjects); break; case "group": executeQueryTypeGroupSubjects(value, maxResults, subjects); break; default: throw new IllegalArgumentException("Word before '=' symbol can be 'id' or 'email' or 'group', nothing else."); } } else { if (indexContains != -1) { String queryType = query.substring(0, indexContains).trim(); String value = query.substring(indexContains + "contains".trim().length()); if (queryType.equals("email")) { executeQueryTypeContains(value.trim(), subjects); } else { throw new IllegalArgumentException("Search for substrings is possible only for 'email' attribute."); } } else { throw new InternalErrorException("Wrong query!"); } } }
288
public GithubUser getUser(String accessToken){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("https://api.github.com/user?access_token=" + accessToken).build(); try { Response response = client.newCall(request).execute(); String string = response.body().string(); GithubUser githubUser = JSON.parseObject(string, GithubUser.class); return githubUser; } catch (IOException e) { } return null; }
public GithubUser getUser(String accessToken){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("https://api.github.com/user?access_token=" + accessToken).build(); try { Response response = client.newCall(request).execute(); String string = response.body() != null ? response.body().string() : null; return JSON.parseObject(string, GithubUser.class); } catch (IOException ignored) { } return null; }
289
public void recordEvent(int dataId, byte value){ if (weaveStartDataId == -1 || weaveEndDataId == -1) { setDataId(); } if (dataId == weaveStartDataId) isRecord = true; if (isRecord) countOccurrence(dataId); if (dataId == weaveEndDataId) { isRecord = false; this.close(); } }
public void recordEvent(int dataId, byte value){ if (dataId == weaver.getFilteringStartDataId()) isRecord = true; if (isRecord) countOccurrence(dataId); if (dataId == weaver.getFilteringEndDataId()) { isRecord = false; this.close(); } }
290
private Map<Pair<V>, Integer> getDistances(Graph<V, ?> graph){ DijkstraShortestPath<V, ?> dijkstra = new DijkstraShortestPath<>(graph); Map<Pair<V>, Integer> distanceMap = new HashMap<>(); for (V vertex : graph.vertexSet()) { ShortestPathAlgorithm.SingleSourcePaths<V, ?> distances = dijkstra.getPaths(vertex); for (V n : graph.vertexSet()) { GraphPath<V, ?> graphPath = distances.getPath(n); if (graphPath == null) { continue; } Pair<V> pair = Pair.of(vertex, n); if (distanceMap.containsKey(pair)) { log.trace("about to replace {},{} with {},{},{}", pair, distanceMap.get(pair), vertex, n, graphPath.getWeight()); } if (graphPath.getWeight() != 0) { distanceMap.put(Pair.of(vertex, n), (int) graphPath.getWeight()); } } } return distanceMap; }
private Map<Pair<V>, Integer> getDistances(Graph<V, ?> graph){ DijkstraShortestPath<V, ?> dijkstra = new DijkstraShortestPath<>(graph); Map<Pair<V>, Integer> distanceMap = new HashMap<>(); for (V vertex : graph.vertexSet()) { ShortestPathAlgorithm.SingleSourcePaths<V, ?> distances = dijkstra.getPaths(vertex); for (V n : graph.vertexSet()) { GraphPath<V, ?> graphPath = distances.getPath(n); if (graphPath != null && graphPath.getWeight() != 0) { distanceMap.put(Pair.of(vertex, n), (int) graphPath.getWeight()); } } } return distanceMap; }
291
public int[] returnSortedBallsWithSelectionSort(int[] baskets, SortOrder sortOrder){ int sortedIndexPosition = 0; int idx = 0; List<Integer> basketsList = Arrays.stream(baskets).boxed().collect(Collectors.toList()); for (int k = sortedIndexPosition; k < baskets.length; k++) { if (sortOrder.name().equals(SortOrder.ASCENDING.name())) { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) > basketsList.get(j) ? j : i).getAsInt(); } else { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) < basketsList.get(j) ? j : i).getAsInt(); } Collections.swap(basketsList, sortedIndexPosition, idx); sortedIndexPosition++; } return basketsList.stream().mapToInt(Integer::intValue).toArray(); }
public int[] returnSortedBallsWithSelectionSort(int[] baskets, SortOrder sortOrder){ int idx = 0; List<Integer> basketsList = Arrays.stream(baskets).boxed().collect(Collectors.toList()); for (int sortedIndexPosition = 0; sortedIndexPosition < basketsList.size(); sortedIndexPosition++) { if (sortOrder.name().equals(SortOrder.ASCENDING.name())) { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) > basketsList.get(j) ? j : i).getAsInt(); } else { idx = IntStream.range(sortedIndexPosition, basketsList.size()).reduce((i, j) -> basketsList.get(i) < basketsList.get(j) ? j : i).getAsInt(); } Collections.swap(basketsList, sortedIndexPosition, idx); } return basketsList.stream().mapToInt(Integer::intValue).toArray(); }
292
public EbicsRequest buildEbicsRequest() throws EbicsException{ final DataTransferRequestType.OrderData orderData = OBJECT_FACTORY.createDataTransferRequestTypeOrderData(); try { orderData.setValue(IOUtil.read(contentFactory.getContent())); } catch (final IOException e) { throw new EbicsException(e); } final DataTransferRequestType dataTransfer = OBJECT_FACTORY.createDataTransferRequestType(); dataTransfer.setOrderData(orderData); final EbicsRequest.Body body = OBJECT_FACTORY.createEbicsRequestBody(); body.setDataTransfer(dataTransfer); return EbicsXmlFactory.request(session.getConfiguration(), EbicsXmlFactory.header(EbicsXmlFactory.mutableHeader(TransactionPhaseType.TRANSFER, segmentNumber, lastSegment), EbicsXmlFactory.staticHeader(session.getHostId(), transactionId)), body); }
public EbicsRequest buildEbicsRequest() throws EbicsException{ final DataTransferRequestType.OrderData orderData = OBJECT_FACTORY.createDataTransferRequestTypeOrderData(); try { orderData.setValue(IOUtil.read(contentFactory.getContent())); } catch (final IOException e) { throw new EbicsException(e); } final DataTransferRequestType dataTransfer = OBJECT_FACTORY.createDataTransferRequestType(); dataTransfer.setOrderData(orderData); return request(session.getConfiguration(), header(mutableHeader(TransactionPhaseType.TRANSFER, segmentNumber, lastSegment), staticHeader(session.getHostId(), transactionId)), body(dataTransfer)); }
293
private void displayLocalMap(Sprite background, List<Sprite> sprites){ if (sprites.size() > 0) { GraphicsContext gc = context.getLocalMapCanvas().getGraphicsContext2D(); background.draw(gc); List<Sprite> orderedSprites = calcRenderOrder(sprites); orderedSprites.forEach(s -> { s.draw(gc); }); } }
private void displayLocalMap(Sprite background, List<Sprite> sprites){ if (sprites.size() > 0) { GraphicsContext gc = context.getLocalMapCanvas().getGraphicsContext2D(); background.draw(gc); sprites.forEach(s -> s.draw(gc)); } }
294
private ValueNode parseCharacter(final String fieldName) throws SQLException{ final ScannerPosition position = this.token.getPosition(); this.expect(TokenType.CHARACTER); final String fieldAlias = getFieldAlias(fieldName); return new ValueNode(fieldName, fieldAlias, position, Types.VARCHAR); }
private ValueNode parseCharacter(final String fieldName) throws SQLException{ final ScannerPosition position = this.token.getPosition(); this.expect(TokenType.CHARACTER); return new ValueNode(fieldName, fieldName, position, Types.VARCHAR); }
295
public final ASTNode visitExpr(final ExprContext ctx){ if (null != ctx.booleanPrimary()) { return visit(ctx.booleanPrimary()); } if (null != ctx.LP_()) { return visit(ctx.expr(0)); } if (null != ctx.logicalOperator()) { BinaryOperationExpression result = new BinaryOperationExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.expr(0))); result.setRight((ExpressionSegment) visit(ctx.expr(1))); result.setOperator(ctx.logicalOperator().getText()); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; } NotExpression result = new NotExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setExpression((ExpressionSegment) visit(ctx.expr(0))); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; }
public final ASTNode visitExpr(final ExprContext ctx){ if (null != ctx.booleanPrimary()) { return visit(ctx.booleanPrimary()); } if (null != ctx.LP_()) { return visit(ctx.expr(0)); } if (null != ctx.logicalOperator()) { BinaryOperationExpression result = new BinaryOperationExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setLeft((ExpressionSegment) visit(ctx.expr(0))); result.setRight((ExpressionSegment) visit(ctx.expr(1))); result.setOperator(ctx.logicalOperator().getText()); String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex())); result.setText(text); return result; } NotExpression result = new NotExpression(); result.setStartIndex(ctx.start.getStartIndex()); result.setStopIndex(ctx.stop.getStopIndex()); result.setExpression((ExpressionSegment) visit(ctx.expr(0))); return result; }
296
private void checkCurrentConnections(){ int len = server_connections_list.size(); for (int i = len - 1; i >= 0; --i) { ServerConnectionState connection_state = (ServerConnectionState) server_connections_list.get(i); try { if (!connection_state.isProcessingRequest()) { ServerConnection connection = connection_state.getConnection(); if (connection_state.hasPendingCommand() || connection.requestPending()) { connection_state.setPendingCommand(); connection_state.setProcessingRequest(); final ServerConnectionState current_state = connection_state; database.execute(null, null, new Runnable() { public void run() { try { current_state.getConnection().processRequest(); } catch (IOException e) { Debug().writeException(Lvl.INFORMATION, e); } finally { current_state.clearInternal(); } } }); } } } catch (IOException e) { try { connection_state.getConnection().close(); } catch (IOException e2) { } server_connections_list.remove(i); Debug().write(Lvl.INFORMATION, this, "IOException generated while checking connections, " + "removing provider."); Debug().writeException(Lvl.INFORMATION, e); } } }
private void checkCurrentConnections(){ int len = server_connections_list.size(); for (int i = len - 1; i >= 0; --i) { ServerConnectionState connection_state = (ServerConnectionState) server_connections_list.get(i); try { if (!connection_state.isProcessingRequest()) { ServerConnection connection = connection_state.getConnection(); if (connection_state.hasPendingCommand() || connection.requestPending()) { connection_state.setPendingCommand(); connection_state.setProcessingRequest(); final ServerConnectionState current_state = connection_state; database.execute(null, null, () -> { try { current_state.getConnection().processRequest(); } catch (IOException e) { Debug().writeException(Lvl.INFORMATION, e); } finally { current_state.clearInternal(); } }); } } } catch (IOException e) { try { connection_state.getConnection().close(); } catch (IOException e2) { } server_connections_list.remove(i); Debug().write(Lvl.INFORMATION, this, "IOException generated while checking connections, " + "removing provider."); Debug().writeException(Lvl.INFORMATION, e); } } }
297
public synchronized String[] keysComparator(){ Set key_set = properties.keySet(); String[] keys = new String[key_set.size()]; int index = 0; Iterator it = key_set.iterator(); while (it.hasNext()) { keys[index] = (String) it.next(); ++index; } return keys; }
public synchronized String[] keysComparator(){ Set key_set = properties.keySet(); String[] keys = new String[key_set.size()]; int index = 0; for (Object o : key_set) { keys[index] = (String) o; ++index; } return keys; }
298
private String constructSQLInsertStatement(){ String sqlInsertStatement = "INSERT INTO dbo.Role (Name) VALUES "; String valueString = ""; for (String role : roleCollection.getRoles()) { valueString = "(\'" + role + "\'), "; sqlInsertStatement += valueString; } sqlInsertStatement = sqlInsertStatement.substring(0, sqlInsertStatement.length() - 2) + ";"; System.out.println(sqlInsertStatement); return sqlInsertStatement; }
private String constructSQLInsertStatement(){ StringBuilder sqlInsertStatement = new StringBuilder("INSERT INTO dbo.Role (Name) VALUES "); for (String role : roleCollection.getRoles()) { sqlInsertStatement.append("('").append(role).append("'), "); } return sqlInsertStatement.substring(0, sqlInsertStatement.length() - 2) + ";"; }
299
public Person createPerson(Person person){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = "insert into person (first_name, last_name, age, phone_number, email_address)" + " values(?,?,?,?,?) returning person_id;"; PreparedStatement createPersonStatement = newConnection.prepareStatement(sql); createPersonStatement.setString(1, person.getFirstName()); createPersonStatement.setString(2, person.getLastName()); createPersonStatement.setInt(3, person.getAge()); createPersonStatement.setString(4, person.getPhoneNumber()); createPersonStatement.setString(5, person.getEmailAddress()); ResultSet result = createPersonStatement.executeQuery(); if (result.next()) { person.setPersonId(result.getInt("person_Id")); } } catch (SQLException e) { BankAppLauncher.appLogger.catching(e); BankAppLauncher.appLogger.error("Internal error occured in the database"); } return person; }
public Person createPerson(Person person){ Connection newConnection = DbConnection.getDbConnection(); try { String sql = "insert into person (first_name, last_name, age, phone_number, email_address)" + " values(?,?,?,?,?) returning person_id;"; PreparedStatement createPersonStatement = newConnection.prepareStatement(sql); createPersonStatement.setString(1, person.getFirstName()); createPersonStatement.setString(2, person.getLastName()); createPersonStatement.setInt(3, person.getAge()); createPersonStatement.setString(4, person.getPhoneNumber()); createPersonStatement.setString(5, person.getEmailAddress()); ResultSet result = createPersonStatement.executeQuery(); if (result.next()) { person.setPersonId(result.getInt("person_Id")); } } catch (SQLException e) { BankAppLauncher.appLogger.error("Internal error occured in the database"); } return person; }