Unnamed: 0
int64
0
9.45k
cwe_id
stringclasses
1 value
source
stringlengths
37
2.53k
target
stringlengths
19
2.4k
9,100
public void step(){ this.accumulator.step(); if (this.accumulator.getChosenCA() != null) { CrossingAlternative ca = this.accumulator.getChosenCA(); this.addCoordinate(ca.nearestCoord(this.ped.getLoc())); this.addCoordinate(ca.farthestCoord(this.ped.getLoc())); this.currentJunction = this.accumulator.getTargetJunction(); this.currentEdge = this.accumulator.getTargetRouteEdge(); this.ped.setChosenCrossingType(ca.getType()); } }
public void step(){ this.accumulator.step(); if (this.accumulator.getChosenCA() != null) { caChosenUpdateCurrentJunction(); } }
9,101
private void registerListeners(){ grid.addDomHandler(this, MouseDownEvent.getType()); grid.addDomHandler(this, MouseUpEvent.getType()); grid.addDomHandler(this, MouseMoveEvent.getType()); grid.addDomHandler(this, ClickEvent.getType()); grid.addDomHandler(this, DoubleClickEvent.getType()); grid.addDomHandler(this, TouchStartEvent.getType()); grid.addDomHandler(this, TouchMoveEvent.getType()); grid.addDomHandler(this, TouchEndEvent.getType()); }
private void registerListeners(){ grid.addDomHandler(headerController, MouseDownEvent.getType()); grid.addDomHandler(headerController, MouseUpEvent.getType()); grid.addDomHandler(headerController, MouseMoveEvent.getType()); grid.addDomHandler(this, TouchStartEvent.getType()); grid.addDomHandler(this, TouchMoveEvent.getType()); grid.addDomHandler(this, TouchEndEvent.getType()); }
9,102
private boolean finaMatchingEdgeNameWithAnyInEdgeOrOutEdge(final Set<Edge> connectedEdges, final Optional<String> edgeName){ for (final Edge inEdge : connectedEdges) { if (!inEdge.getName().isPresent()) { continue; } final Optional<String> inEdgeName = inEdge.getName(); if (inEdgeName.isPresent() && edgeName.isPresent() && inEdgeName.get().equals(edgeName.get())) { return true; } } return false; }
private boolean finaMatchingEdgeNameWithAnyInEdgeOrOutEdge(final Set<Edge> connectedEdges, final String edgeName){ for (final Edge connectedEdge : connectedEdges) { final Optional<String> connectedEdgeName = connectedEdge.getName(); if (connectedEdgeName.isPresent() && connectedEdgeName.get().equals(edgeName)) { return true; } } return false; }
9,103
public void cleanup(Reducer.Context context) throws IOException, InterruptedException{ end = System.currentTimeMillis(); time = end - time; System.out.println("Reduce() took " + TimeUnit.MILLISECONDS.toSeconds(time) + " sec."); }
public void cleanup(Reducer.Context context) throws IOException, InterruptedException{ FirstMRElapsedTimeInSec = (System.currentTimeMillis() - FirstMRStartTime); System.out.println("Reduce() took " + FirstMRElapsedTimeInSec + " milliseconds."); }
9,104
public int[] alleleCountsByIndex(final int maximumAlleleIndex){ if (maximumAlleleIndex < 0) { throw new IllegalArgumentException("the requested allele count cannot be less than 0"); } final int[] result = new int[maximumAlleleIndex + 1]; copyAlleleCountsByIndex(result, 0, 0, maximumAlleleIndex); return result; }
public int[] alleleCountsByIndex(final int maximumAlleleIndex){ Utils.validateArg(maximumAlleleIndex >= 0, "the requested allele count cannot be less than 0"); final int[] result = new int[maximumAlleleIndex + 1]; copyAlleleCountsByIndex(result, 0, 0, maximumAlleleIndex); return result; }
9,105
public void actionPerformed(NodeActionEvent e){ final Project project = (Project) functionModule.getProject(); AzureSignInAction.signInIfNotSignedIn(project).subscribe((isLoggedIn) -> { if (isLoggedIn && AzureLoginHelper.isAzureSubsAvailableOrReportError(message("common.error.signIn"))) { AzureTaskManager.getInstance().runLater(() -> openDialog(project, null)); } }); }
public void actionPerformed(NodeActionEvent e){ final Project project = (Project) functionModule.getProject(); AzureSignInAction.requireSignedIn(project, () -> this.openDialog(project, null)); }
9,106
public Object getBean(Class<?> genericClassType, CustomBeanScope customBeanScope) throws CustomDiFrameworkException{ if (null == genericClassType) { throw new CustomDiFrameworkException(ErrorConstants.INPUT_PARAMETER_IS_NULL); } if (!isBeanRegistered(genericClassType)) { registerBean(genericClassType); System.out.println("not reg ----------"); } BeanContext beanContext = getBeanContext(genericClassType); if (CustomBeanScope.SINGLETON.equals(customBeanScope)) { if (null == beanContext.getSingletonBeanHolder()) { initBean(beanContext); System.out.println("1----------"); } System.out.println("2----------"); return beanContext.getSingletonBeanHolder().getBean(); } else if (CustomBeanScope.PROTOTYPE.equals(customBeanScope)) { System.out.println("3----------"); return initBean(beanContext); } return null; }
public Object getBean(Class<?> genericClassType, CustomBeanScope customBeanScope) throws CustomDiFrameworkException{ synchronized (CustomDiApplicationContextImpl.class) { if (null == genericClassType) { throw new CustomDiFrameworkException(ErrorConstants.INPUT_PARAMETER_IS_NULL); } if (!isBeanRegistered(genericClassType)) { registerBean(genericClassType); } BeanContext beanContext = getBeanContext(genericClassType); if (CustomBeanScope.SINGLETON.equals(customBeanScope)) { if (null == beanContext.getSingletonBeanHolder()) { initBean(beanContext); } return beanContext.getSingletonBeanHolder().getBean(); } else if (CustomBeanScope.PROTOTYPE.equals(customBeanScope)) { return initBean(beanContext); } return null; } }
9,107
protected void addEdges(Integer graphId, Connection con, ContainerLoader cl, Map<String, Object> graphParam) throws SQLException{ Integer rootNodeId = (Integer) graphParam.get("rootNodeId"); Double upweight = (Double) graphParam.get("upweight"); Double downweight = (Double) graphParam.get("downweight"); ElementDraft.Factory elementDraftFactory = cl.factory(); PreparedStatement ps = con.prepareStatement("select * from gephi.edge where graph = ?"); ps.setInt(1, graphId); ResultSet rs = ps.executeQuery(); while (rs.next()) { Integer num = rs.getInt("num"); Integer source = rs.getInt("source"); Integer target = rs.getInt("target"); Double value = rs.getDouble("value"); if (rootNodeId.equals(source) || rootNodeId.equals(target)) { value *= upweight; } else { value *= downweight; } EdgeDraft ed = elementDraftFactory.newEdgeDraft(num.toString()); ed.setSource(cl.getNode(source.toString())); ed.setTarget(cl.getNode(target.toString())); ed.setWeight(value.floatValue()); cl.addEdge(ed); } ps.close(); }
protected void addEdges(Integer graphId, Connection con, ContainerLoader cl, Map<String, Object> graphParam) throws SQLException{ final Integer rootNodeId = (Integer) graphParam.get("rootNodeId"); final Float upweight = (Float) graphParam.get("up_weight"); final Float downweight = (Float) graphParam.get("down_weight"); final ElementDraft.Factory elementDraftFactory = cl.factory(); graphDataSource.populateEdgesForGraph(con, graphId, (num, source, target, val) -> { if (rootNodeId.equals(source) || rootNodeId.equals(target)) { val *= upweight; } else { val *= downweight; } EdgeDraft ed = elementDraftFactory.newEdgeDraft(num.toString()); ed.setSource(cl.getNode(source.toString())); ed.setTarget(cl.getNode(target.toString())); ed.setWeight(val.floatValue()); cl.addEdge(ed); return true; }); }
9,108
public void givenVehicle_WhenOwnerWantAttendant_ShouldParkTheCar() throws ParkingLotSystemException{ parkingLotSystem = new ParkingLotSystem(owner, attendant); parkingLotSystem.addObserver(owner); vehicle = new Vehicle("MH13AN0808", "McLaren"); parkingLotSystem.park(vehicle); Vehicle vehicle1 = new Vehicle("MH10BQ8109", "Ferari"); parkingLotSystem.park(vehicle); parkingLotSystem.unPark(vehicle1); System.out.println(parkingLotSystem.isVehicleParked(vehicle)); }
public void givenVehicle_WhenOwnerWantAttendant_ShouldParkTheCar() throws ParkingLotSystemException{ parkingLotSystem = new ParkingLotSystem(owner, attendant); parkingLotSystem.addObserver(owner); vehicle = new Vehicle("MH13AN0808", "McLaren"); parkingLotSystem.park(vehicle); Vehicle vehicle1 = new Vehicle("MH10BQ8109", "Ferari"); parkingLotSystem.park(vehicle); parkingLotSystem.unPark(vehicle1); }
9,109
public int hashCode(){ int result = 17; if (key != null) { result = 37 * key.hashCode(); } if (repository != null) { result = 37 * repository.hashCode(); } return result; }
public int hashCode(){ return Objects.hash(key, repository); }
9,110
protected void doit() throws WollMuxFehlerException{ checkPrintPreconditions(documentController); stabilize(); final XPrintModel pmod = PrintModels.createPrintModel(documentController, true); new Thread() { @Override public void run() { pmod.printWithProps(); } }.start(); }
protected void doit() throws WollMuxFehlerException{ stabilize(); final XPrintModel pmod = PrintModels.createPrintModel(documentController, true); new Thread() { @Override public void run() { pmod.printWithProps(); } }.start(); }
9,111
public int save(FriesModel model){ try { if (model.getId() == 0) { String create = "INSERT INTO fries(name, image_url, cost, category, description, size) VALUES (?, ?, ?, ?, ?);"; int id = template.<Integer>updateForId(ds, create, stmt -> { int index = 1; stmt.setString(index++, model.getName()); stmt.setString(index++, model.getImageUrl()); stmt.setInt(index++, model.getCost()); stmt.setString(index++, model.getCategory().toString()); stmt.setString(index++, model.getDescription()); stmt.setString(index, model.getSize().toString()); return stmt; }); return id; } else { String update = "UPDATE fries SET name = ?, image_url = ?, cost = ?, category = ?, description = ?, size = ? WHERE id = ?;"; template.update(ds, update, stmt -> { int index = 1; stmt.setString(index++, model.getName()); stmt.setString(index++, model.getImageUrl()); stmt.setInt(index++, model.getCost()); stmt.setString(index++, model.getCategory().toString()); stmt.setString(index++, model.getDescription()); stmt.setString(index++, model.getSize().toString()); stmt.setInt(index, model.getId()); return stmt; }); return model.getId(); } } catch (SQLException e) { throw new DataAccessException(e); } }
public int save(FriesModel model){ try { if (model.getId() == 0) { String create = "INSERT INTO fries(name, image_url, cost, category, description, size) VALUES (?, ?, ?, ?, ?);"; return template.<Integer>updateForId(ds, create, stmt -> { int index = 1; stmt.setString(index++, model.getName()); stmt.setString(index++, model.getImageUrl()); stmt.setInt(index++, model.getCost()); stmt.setString(index++, model.getCategory().toString()); stmt.setString(index++, model.getDescription()); stmt.setString(index, model.getSize().toString()); return stmt; }); } else { String update = "UPDATE fries SET name = ?, image_url = ?, cost = ?, category = ?, description = ?, size = ? WHERE id = ?;"; template.update(ds, update, stmt -> { int index = 1; stmt.setString(index++, model.getName()); stmt.setString(index++, model.getImageUrl()); stmt.setInt(index++, model.getCost()); stmt.setString(index++, model.getCategory().toString()); stmt.setString(index++, model.getDescription()); stmt.setString(index++, model.getSize().toString()); stmt.setInt(index, model.getId()); return stmt; }); return model.getId(); } } catch (SQLException e) { throw new DataAccessException(e); } }
9,112
public Result queryProjectListPaging(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "searchVal", required = false) String searchVal, @RequestParam("pageSize") Integer pageSize, @RequestParam("pageNo") Integer pageNo){ logger.info("login user {}, query project list paging", loginUser.getUserName()); searchVal = ParameterUtils.handleEscapes(searchVal); Map<String, Object> result = projectService.queryProjectListPaging(loginUser, pageSize, pageNo, searchVal); return returnDataListPaging(result); }
public Result<PageListVO<Project>> queryProjectListPaging(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "searchVal", required = false) String searchVal, @RequestParam("pageSize") Integer pageSize, @RequestParam("pageNo") Integer pageNo){ logger.info("login user {}, query project list paging", loginUser.getUserName()); searchVal = ParameterUtils.handleEscapes(searchVal); return projectService.queryProjectListPaging(loginUser, pageSize, pageNo, searchVal); }
9,113
public boolean remove(){ if (page != null) { page.remove(valueTime); return true; } else { return false; } }
public void remove(){ page.remove(valueTime); }
9,114
public Result<List<WorkFlowLineage>> queryWorkFlowLineageByName(@ApiIgnore @RequestAttribute(value = SESSION_USER) User loginUser, @ApiParam(name = "projectId", value = "PROJECT_ID", required = true, example = "1") @PathVariable int projectId, @ApiIgnore @RequestParam(value = "searchVal", required = false) String searchVal){ try { searchVal = ParameterUtils.handleEscapes(searchVal); Map<String, Object> result = workFlowLineageService.queryWorkFlowLineageByName(searchVal, projectId); return returnDataList(result); } catch (Exception e) { logger.error(QUERY_WORKFLOW_LINEAGE_ERROR.getMsg(), e); return error(QUERY_WORKFLOW_LINEAGE_ERROR.getCode(), QUERY_WORKFLOW_LINEAGE_ERROR.getMsg()); } }
public Result<List<WorkFlowLineage>> queryWorkFlowLineageByName(@ApiIgnore @RequestAttribute(value = SESSION_USER) User loginUser, @ApiParam(name = "projectId", value = "PROJECT_ID", required = true, example = "1") @PathVariable int projectId, @ApiIgnore @RequestParam(value = "searchVal", required = false) String searchVal){ try { searchVal = ParameterUtils.handleEscapes(searchVal); return workFlowLineageService.queryWorkFlowLineageByName(searchVal, projectId); } catch (Exception e) { logger.error(QUERY_WORKFLOW_LINEAGE_ERROR.getMsg(), e); return Result.error(QUERY_WORKFLOW_LINEAGE_ERROR); } }
9,115
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ Player player; if (sender instanceof Player) { player = (Player) sender; } else { sender.sendMessage(LANG.playerOnly); return false; } if (args.length == 0) { balanceMessage(eco.player(player.getUniqueId())); return true; } String command; command = args[0]; double value = 0; if (args.length >= 2) { try { value = Double.parseDouble(args[1]); } catch (NumberFormatException ignored) { return false; } if ("withdraw".equals(command)) { withdraw(player, value); return true; } else if ("deposit".equals(command)) { deposit(player, value); return true; } } return args.length == 3 && "pay".equals(command) && pay(player, value, args); }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){ if (!(sender instanceof Player)) { sender.sendMessage(LANG.playerOnly); return false; } Player player = (Player) sender; if (args.length == 0) { sendBalanceMessage(eco.player(player.getUniqueId())); return true; } String command = args[0]; double value = 0; if (args.length == 2) { try { value = Double.parseDouble(args[1]); } catch (NumberFormatException ignored) { return false; } if ("withdraw".equals(command)) { withdraw(player, value); return true; } else if ("deposit".equals(command)) { deposit(player, value); return true; } } else if (args.length == 3 && "pay".equals(command)) { return pay(player, value, args); } return false; }
9,116
public void run(){ for (Backend backend : backendManager.getIdlingBackends()) { if (SocketUtils.isReachable(backend.getHost(), backend.getPort())) { this.backendManager.getIdlingBackends().remove(backend); this.backendManager.addBackend(backend); this.logger.info("Recovered backend: {} [{}:{}]", backend.getName(), backend.getHost(), backend.getPort()); } } }
public void run(){ backendManager.getIdlingBackends().stream().filter(backend -> SocketUtils.isReachable(backend.getHost(), backend.getPort())).forEach(backend -> { backendManager.getIdlingBackends().remove(backend); backendManager.addBackend(backend); logger.info("Recovered backend: {} [{}:{}]", backend.getName(), backend.getHost(), backend.getPort()); }); }
9,117
public void testConnection() throws Exception{ System.out.println("\n\n\n\n" + CmisInMemoryRunner.getCmisPort() + "\n\n\n\n\n"); URL url = new URL("http://localhost:" + CmisInMemoryRunner.getCmisPort() + "/cmis/atom"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); assertEquals("The Response code should be 200", conn.getResponseCode(), 200); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); Assert.assertNotNull("The return should be null", br.readLine()); conn.disconnect(); }
public void testConnection() throws Exception{ URL url = CmisInMemoryRunner.getCmisURI().toURL(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); assertEquals("The Response code should be 200", conn.getResponseCode(), 200); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); Assert.assertNotNull("The buffered reader should be null", br); conn.disconnect(); }
9,118
public boolean add(T value){ if (size == 0) { Node<T> newNode = new Node<>(null, value, null); first = newNode; last = newNode; size++; } else { Node<T> newNode = new Node<>(last, value, null); last.next = newNode; last = newNode; size++; } return true; }
public boolean add(T value){ if (size == 0) { Node<T> newNode = new Node<>(null, value, null); first = newNode; last = newNode; } else { Node<T> newNode = new Node<>(last, value, null); last.next = newNode; last = newNode; } size++; return true; }
9,119
private org.atlasapi.content.Restriction makeRestriction(Restriction internal){ org.atlasapi.content.Restriction restriction = new org.atlasapi.content.Restriction(); Long id = internal.getId(); if (id != null) { restriction.setId(id); } restriction.setCanonicalUri(internal.getCanonicalUri()); restriction.setCurie(internal.getCurie()); restriction.setAliasUrls(internal.getAliasUrls()); Set<org.atlasapi.content.v2.model.udt.Alias> aliases = internal.getAliases(); if (aliases != null) { restriction.setAliases(aliases.stream().map(a -> new Alias(a.getNamespace(), a.getValue())).collect(Collectors.toSet())); } Set<Ref> equivalentTo = internal.getEquivalentTo(); if (equivalentTo != null) { restriction.setEquivalentTo(equivalentTo.stream().map(ref -> new EquivalenceRef(Id.valueOf(ref.getId()), Publisher.fromKey(ref.getSource()).requireValue())).collect(Collectors.toSet())); } restriction.setLastUpdated(convertDateTime(internal.getLastUpdated())); restriction.setEquivalenceUpdate(convertDateTime(internal.getEquivalenceUpdate())); restriction.setRestricted(internal.getRestricted()); restriction.setMinimumAge(internal.getMinimumAge()); restriction.setMessage(internal.getMessage()); restriction.setAuthority(internal.getAuthority()); restriction.setRating(internal.getRating()); return restriction; }
private org.atlasapi.content.Restriction makeRestriction(Restriction internal){ org.atlasapi.content.Restriction restriction = new org.atlasapi.content.Restriction(); setIdentifiedFields(restriction, internal); restriction.setRestricted(internal.getRestricted()); restriction.setMinimumAge(internal.getMinimumAge()); restriction.setMessage(internal.getMessage()); restriction.setAuthority(internal.getAuthority()); restriction.setRating(internal.getRating()); return restriction; }
9,120
private void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ String page = request.getParameter("page"); String send = request.getParameter("send"); if (page.equals("/main.jsp") && send.equals("redirect")) { RequestManager.redirect(request, response, page, this); } else if (page.equals("/register.jsp") && send.equals("redirect")) { RequestManager.redirect(request, response, page, this); } else if (page.equals("/admin.jsp") && send.equals("redirect")) { RequestManager.showUserData(request, response, this); } else if (page.equals("/main.jsp") && send.equals("signIn")) { RequestManager.redirect(request, response, page, this); } else if (page.equals("/register.jsp") && send.equals("signUp")) { RequestManager.register(request, response, page, this); } else { RequestManager.redirect(request, response, page, this); } }
private void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ SendController controller = new SendController(); InterfaceSend currentSend = controller.defineSend(request); String page = currentSend.executeSend(request); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page); dispatcher.forward(request, response); }
9,121
public void confirmRemoveCover(){ if (mAudioFields.getCover() != null) { Track track = mTrack; track.setProcessing(1); mTrackRepository.update(track); mCorrectionParams = new CoverCorrectionParams(); mCorrectionParams.setCodeRequest(AudioTagger.MODE_REMOVE_COVER); mDataTrackManager.removeCover(mCorrectionParams); } else { Message message = new Message(R.string.does_not_exist_cover); mLiveMessage.setValue(message); } }
public void confirmRemoveCover(){ if (mAudioFields.getCover() != null) { mCorrectionParams = new CoverCorrectionParams(); mCorrectionParams.setTargetFile(mTrack.getPath()); mCorrectionParams.setCodeRequest(AudioTagger.MODE_REMOVE_COVER); mDataTrackManager.removeCover(mCorrectionParams); } else { Message message = new Message(R.string.does_not_exist_cover); mLiveMessage.setValue(message); } }
9,122
public void processEl196Test(){ AnalyzedTestConfiguration context_ = getConfiguration(new StringMap<String>()); addImportingPage(context_); StringMap<LocalVariable> localVars_ = new StringMap<LocalVariable>(); LocalVariable lv_ = new LocalVariable(); lv_.setStruct(new IntStruct(3)); lv_.setClassName(context_.getStandards().getAliasPrimInteger()); localVars_.put("v", lv_); LocalVariable lv2_ = new LocalVariable(); lv2_.setStruct(new IntStruct(12)); lv2_.setClassName(context_.getStandards().getAliasPrimInteger()); localVars_.put("v2", lv2_); CommonRender.setLocalVars(context_.getLastPage(), localVars_); ContextEl ctx_ = context_.getContext(); setupAnalyzing(context_.getAnalyzing(), context_.getLastPage()); String elr_ = "v= ++v2"; Delimiters d_ = checkSyntax(ctx_, elr_); assertTrue(d_.getBadOffset() < 0); String el_ = elr_; OperationsSequence opTwo_ = ElResolver.getOperationsSequence(0, el_, ctx_, d_); OperationNode op_ = OperationNode.createOperationNode(0, CustList.FIRST_INDEX, null, opTwo_, ctx_); assertNotNull(op_); CustList<OperationNode> all_ = getSortedDescNodes(context_, op_); assertTrue(context_.isEmptyErrors()); Argument arg_ = calculate(all_, context_); assertEq(13, ((NumberStruct) lv2_.getStruct()).intStruct()); assertEq(13, ((NumberStruct) lv_.getStruct()).intStruct()); assertEq(13, getNumber(arg_)); }
public void processEl196Test(){ AnalyzedTestConfiguration context_ = getConfiguration(new StringMap<String>()); addImportingPage(context_); StringMap<LocalVariable> localVars_ = new StringMap<LocalVariable>(); LocalVariable lv_ = new LocalVariable(); lv_.setStruct(new IntStruct(3)); lv_.setClassName(context_.getAnaStandards().getAliasPrimInteger()); localVars_.put("v", lv_); LocalVariable lv2_ = new LocalVariable(); lv2_.setStruct(new IntStruct(12)); lv2_.setClassName(context_.getAnaStandards().getAliasPrimInteger()); localVars_.put("v2", lv2_); CommonRender.setLocalVars(context_.getLastPage(), localVars_); setupAnalyzing(context_.getAnalyzing(), context_.getLastPage()); String elr_ = "v= ++v2"; Delimiters d_ = checkSyntax(context_, elr_, 0); assertTrue(d_.getBadOffset() < 0); String el_ = elr_; OperationsSequence opTwo_ = getOperationsSequence(0, el_, context_, d_); OperationNode op_ = getOperationNode(0, CustList.FIRST_INDEX, null, opTwo_, context_); assertNotNull(op_); CustList<OperationNode> all_ = getSortedDescNodes(context_, new AnalyzingDoc(), op_); assertTrue(context_.isEmptyErrors()); Argument arg_ = calculate(all_, context_); assertEq(13, ((NumberStruct) lv2_.getStruct()).intStruct()); assertEq(13, ((NumberStruct) lv_.getStruct()).intStruct()); assertEq(13, getNumber(arg_)); }
9,123
public void boot_noCloud() throws Exception{ when(st.provision(any(TaskListener.class), any(Label.class), any(EnumSet.class))).thenReturn(instance); WorkflowJob boot = r.jenkins.createProject(WorkflowJob.class, "EC2Test"); boot.setDefinition(new CpsFlowDefinition(" node('master') {\n" + " def X = ec2 cloud: 'dummyCloud', template: 'aws-CentOS-7'\n" + " X.boot()\n" + "}", true)); WorkflowRun b = r.assertBuildStatus(Result.FAILURE, boot.scheduleBuild2(0).get()); r.assertLogContains("Error in AWS Cloud. Please review EC2 settings in Jenkins configuration.", b); r.assertLogContains("FAILURE", b); }
public void boot_noCloud() throws Exception{ WorkflowJob boot = r.jenkins.createProject(WorkflowJob.class, "EC2Test"); boot.setDefinition(new CpsFlowDefinition(" node('master') {\n" + " def X = ec2 cloud: 'dummyCloud', template: 'aws-CentOS-7'\n" + " X.boot()\n" + "}", true)); WorkflowRun b = r.assertBuildStatus(Result.FAILURE, boot.scheduleBuild2(0).get()); r.assertLogContains("Error in AWS Cloud. Please review EC2 settings in Jenkins configuration.", b); r.assertLogContains("FAILURE", b); }
9,124
public ResponseEvent<DistributionProtocolDetail> getDistributionProtocol(RequestEvent<Long> req){ try { Long protocolId = req.getPayload(); DistributionProtocol existing = daoFactory.getDistributionProtocolDao().getById(protocolId); if (existing == null) { return ResponseEvent.userError(DistributionProtocolErrorCode.NOT_FOUND); } AccessCtrlMgr.getInstance().ensureReadDpRights(existing); return ResponseEvent.response(DistributionProtocolDetail.from(existing)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } }
public ResponseEvent<DistributionProtocolDetail> getDistributionProtocol(RequestEvent<Long> req){ try { Long protocolId = req.getPayload(); DistributionProtocol existing = getDistributionProtocol(protocolId); AccessCtrlMgr.getInstance().ensureReadDpRights(existing); return ResponseEvent.response(DistributionProtocolDetail.from(existing)); } catch (OpenSpecimenException ose) { return ResponseEvent.error(ose); } catch (Exception e) { return ResponseEvent.serverError(e); } }
9,125
private void init(View view){ ButterKnife.bind(this, view); mActivity = (AppCompatActivity) getActivity(); mActivity.setSupportActionBar(toolbar); ActionBar actionBar = mActivity.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } toolbar.setBackgroundColor(color); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { float[] hsv = new float[3]; Color.colorToHSV(color, hsv); hsv[2] *= 0.8f; int statusBarColor = Color.HSVToColor(hsv); mActivity.getWindow().setStatusBarColor(statusBarColor); } toolbar.setTitle(title); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); SnapHelper snapHelper = new GravitySnapHelper(Gravity.TOP); snapHelper.attachToRecyclerView(recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setMotionEventSplittingEnabled(false); recyclerView.setNestedScrollingEnabled(false); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL)); recyclerView.setAdapter(adapter); }
private void init(View view){ unbinder = ButterKnife.bind(this, view); mActivity = (AppCompatActivity) getActivity(); mActivity.setSupportActionBar(toolbar); ActionBar actionBar = mActivity.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } toolbar.setBackgroundColor(color); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mActivity.getWindow().setStatusBarColor(Utils.getDarkColor(color)); } toolbar.setTitle(title); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); SnapHelper snapHelper = new GravitySnapHelper(Gravity.TOP); snapHelper.attachToRecyclerView(recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setMotionEventSplittingEnabled(false); recyclerView.setNestedScrollingEnabled(false); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL)); recyclerView.setAdapter(adapter); }
9,126
public void build(WordTrie trie){ int limit = 1; for (String s : trie.getWordList()) { HashMap<String, Integer> results = trie.getWeightedAdjStrings(s); for (Entry<String, Integer> entry : results.entrySet()) { this.getVertex(entry.getKey()).addToAdjList(this.table.get(s), entry.getValue()); this.getVertex(s).addToAdjList(this.table.get(entry.getKey()), entry.getValue()); } } }
public void build(WordTrie trie){ for (String s : trie.getWordList()) { HashMap<String, Integer> results = trie.getWeightedAdjStrings(s); for (Entry<String, Integer> entry : results.entrySet()) { this.getVertex(entry.getKey()).addToAdjList(this.table.get(s), entry.getValue()); this.getVertex(s).addToAdjList(this.table.get(entry.getKey()), entry.getValue()); } } }
9,127
public void createApplication(String appName, String appDescription, String version, String fileName, String fileLocation, String iconLocation, List<Map<String, String>> tags, boolean isNewVersion) throws CloudDeploymentException, InvalidTokenException{ Map<String, String> files = new HashMap<>(); files.put("fileupload", fileLocation); if (!iconLocation.isEmpty() && iconLocation != null) { files.put("appIcon", iconLocation); } String createAppUrl = CloudServiceConstants.ServiceEndpoints.APPLICATION_URL; Map<String, String> data = new HashMap<>(); data.put("action", "createApplication"); data.put("applicationName", appName); if (!appDescription.isEmpty() && appDescription != null) { data.put("applicationDescription", appDescription); } data.put("appTypeName", CloudServiceConstants.AppConfigs.ESB); data.put("applicationRevision", version); data.put("uploadedFileName", fileName); data.put("runtimeProperties", "[]"); data.put("tags", JsonUtils.getJsonArrayFromList(tags)); data.put("isFileAttached", "true"); data.put("conSpec", "5"); data.put("isNewVersion", Boolean.toString(isNewVersion)); data.put("appCreationMethod", "default"); data.put("setDefaultVersion", "true"); data.put("runtime", CloudServiceConstants.AppConfigs.RUNTIME); String response = HTTPClientUtil.sendPostWithMulipartFormData(createAppUrl, data, files, cookieStore); mapResponse(response); if (response.equals(NO_RESOURCES_ERROR)) { throw new CloudDeploymentException(NO_RESOURCES_ERROR); } else if (response.equals(VERSION_EXISTS_ERROR)) { throw new CloudDeploymentException(VERSION_EXISTS_ERROR); } }
public void createApplication(String appName, String appDescription, String version, String fileName, String fileLocation, String iconLocation, List<Map<String, String>> tags, boolean isNewVersion) throws CloudDeploymentException, InvalidTokenException{ Map<String, String> files = new HashMap<>(); files.put("fileupload", fileLocation); if (!iconLocation.isEmpty() && iconLocation != null) { files.put("appIcon", iconLocation); } String createAppUrl = CloudServiceConstants.ServiceEndpoints.APPLICATION_URL; Map<String, String> data = new HashMap<>(); data.put("action", CloudServiceConstants.Actions.CREATE_APPLICATION); data.put("applicationName", appName); if (!appDescription.isEmpty() && appDescription != null) { data.put("applicationDescription", appDescription); } data.put("appTypeName", CloudServiceConstants.AppConfigs.ESB); data.put("applicationRevision", version); data.put("uploadedFileName", fileName); data.put("runtimeProperties", "[]"); data.put("tags", JsonUtils.getJsonArrayFromList(tags)); data.put("isFileAttached", "true"); data.put("conSpec", CloudServiceConstants.AppConfigs.CON_SPEC); data.put("isNewVersion", Boolean.toString(isNewVersion)); data.put("appCreationMethod", "default"); data.put("setDefaultVersion", "true"); data.put("runtime", CloudServiceConstants.AppConfigs.RUNTIME); String response = HTTPClientUtil.sendPostWithMulipartFormData(createAppUrl, data, files, cookieStore); mapResponse(response); }
9,128
private Map<String, Object> checkProjectAndAuth(){ Map<String, Object> result = new HashMap<>(); result.put(Constants.STATUS, Status.SUCCESS); return result; }
private CheckParamResult checkProjectAndAuth(){ return new CheckParamResult(Status.SUCCESS); }
9,129
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View rootView = inflater.inflate(R.layout.fragment_main, container, false); String[] forecastArray = { "Today - Sunny - 88/63", "Tomorrow - Foggy - 70/40", "Weds - Cloudy - 72/65", "Thursday - Asteroids - 75/65", "Fri - Heavy Rain - 65/56", "Sat - HELP TRAPPED IN WEATHERSTATION - 60/51", "Sun - Sunny - 80/68" }; List<String> weekForecast = new ArrayList<>(Arrays.asList(forecastArray)); mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast); ListView mListView = (ListView) rootView.findViewById(R.id.listview_forecast); mListView.setAdapter(mForecastAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String forecast = mForecastAdapter.getItem(position); Intent myIntent = new Intent(getActivity(), DetailActivity.class); myIntent.putExtra("Forecast", forecast); startActivity(myIntent); } }); return rootView; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View rootView = inflater.inflate(R.layout.fragment_main, container, false); List<String> weekForecast = new ArrayList<>(Arrays.asList(forecastArray)); mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast); ListView mListView = (ListView) rootView.findViewById(R.id.listview_forecast); mListView.setAdapter(mForecastAdapter); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String forecast = mForecastAdapter.getItem(position); Intent myIntent = new Intent(getActivity(), DetailActivity.class); myIntent.putExtra("Forecast", forecast); startActivity(myIntent); } }); return rootView; }
9,130
public void startMonster(){ CountDownTimer countDownTimer = new CountDownTimer(3000000, 30000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { } }.start(); }
public void startMonster(){ }
9,131
public void onNewHouseholdSolarPowerGeneration(HouseholdSolarPowerGeneration solar){ super.onNewHouseholdSolarPowerGeneration(solar); Log.d(Constants.ECHO_TAG, "onNewBattery: " + solar); MySolarReceiver mySolarReceiver = new MySolarReceiver(); mySolarReceiver.setContinuousTask(new TimerTask() { @Override public void run() { try { solar.get().reqGetMeasuredCumulativeAmountOfElectricityGenerated().send(); } catch (Exception e) { Log.e(Constants.ECHO_TAG, "Solar Adapter: Device Disconnected" + e.getMessage()); if (mySolarReceiver.getOnGetListener() != null) mySolarReceiver.getOnGetListener().controlResult(false, new EchoProperty(HouseholdSolarPowerGeneration.EPC_MEASURED_CUMULATIVE_AMOUNT_OF_ELECTRICITY_GENERATED)); } } }); solar.setReceiver(mySolarReceiver); mySolarReceiver.startContinuousTask(); try { solar.get().reqGetOperationStatus().send(); solar.get().reqGetMeasuredInstantaneousAmountOfElectricityGenerated().send(); solar.get().reqGetMeasuredCumulativeAmountOfElectricityGenerated().send(); } catch (IOException e) { Log.e(Constants.ECHO_TAG, "Solar Adapter: Device Disconnected", e); } }
public void onNewHouseholdSolarPowerGeneration(HouseholdSolarPowerGeneration solar){ super.onNewHouseholdSolarPowerGeneration(solar); Log.d(Constants.ECHO_TAG, "onNewBattery: " + solar); MySolarReceiver mySolarReceiver = new MySolarReceiver(solar); mySolarReceiver.setUpdateTask(new TimerTask() { @Override public void run() { try { solar.get().reqGetMeasuredCumulativeAmountOfElectricityGenerated().send(); } catch (Exception e) { Log.e(Constants.ECHO_TAG, "Solar Adapter: Device Disconnected" + e.getMessage()); if (mySolarReceiver.getOnGetListener() != null) mySolarReceiver.getOnGetListener().controlResult(false, new EchoProperty(HouseholdSolarPowerGeneration.EPC_MEASURED_CUMULATIVE_AMOUNT_OF_ELECTRICITY_GENERATED)); } } }); solar.setReceiver(mySolarReceiver); mySolarReceiver.update(exception -> { Log.e(Constants.ECHO_TAG, "onNewHouseholdSolarPowerGeneration: Device disconnected.", exception); }); mySolarReceiver.startUpdateTask(); }
9,132
public Map<String, Object> run(String username, String password, String eauth, String client, String target, String function, List<String> args, Map<String, String> kwargs) throws SaltStackException{ JsonObject json = new JsonObject(); json.addProperty("username", username); json.addProperty("password", password); json.addProperty("eauth", eauth); json.addProperty("client", client); json.addProperty("tgt", target); json.addProperty("fun", function); if (args != null) { JsonArray argsArray = new JsonArray(); for (String arg : args) { argsArray.add(new JsonPrimitive(arg)); } json.add("arg", argsArray); } if (kwargs != null) { for (String key : kwargs.keySet()) { json.addProperty(key, kwargs.get(key)); } } JsonArray jsonArray = new JsonArray(); jsonArray.add(json); Result<List<Map<String, Object>>> result = connectionFactory.create("/run", JsonParser.RETVALS, config).getResult(jsonArray.toString()); return result.getResult().get(0); }
public Map<String, Object> run(final String username, final String password, final String eauth, final String client, final String target, final String function, List<String> args, Map<String, String> kwargs) throws SaltStackException{ Map<String, String> allKwags = new LinkedHashMap() { { put("username", username); put("password", password); put("eauth", eauth); put("client", client); put("tgt", target); put("fun", function); } }; if (kwargs != null) { allKwags.putAll(kwargs); } JsonArray jsonArray = new JsonArray(); jsonArray.add(ClientUtils.makeJsonData(allKwags, args)); Result<List<Map<String, Object>>> result = connectionFactory.create("/run", JsonParser.RETVALS, config).getResult(jsonArray.toString()); return result.getResult().get(0); }
9,133
public Builder snapshot_id(final String snapshot_id){ assert (snapshot_id != null); assert (!snapshot_id.equals("")); return setBodyParameter("snapshot_id", snapshot_id); }
public Builder snapshot_id(final String snapshot_id){ assertHasAndNotNull(snapshot_id); return setBodyParameter("snapshot_id", snapshot_id); }
9,134
private void setupListeners(){ menu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { appController.menu(); } }); tryAgain.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { appController.scramble(); } }); menu.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent onClick) { menu.setForeground(Color.LIGHT_GRAY); } public void mouseReleased(MouseEvent offClick) { menu.setForeground(Color.WHITE); } public void mouseEntered(MouseEvent enter) { menu.setBorder(new LineBorder(Color.WHITE, 5)); } public void mouseExited(MouseEvent exit) { menu.setBorder(new LineBorder(Color.BLACK, 5)); } }); tryAgain.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent onClick) { tryAgain.setForeground(Color.LIGHT_GRAY); } public void mouseReleased(MouseEvent offClick) { tryAgain.setForeground(Color.WHITE); } public void mouseEntered(MouseEvent enter) { tryAgain.setBorder(new LineBorder(Color.WHITE, 5)); } public void mouseExited(MouseEvent exit) { tryAgain.setBorder(new LineBorder(Color.BLACK, 5)); } }); }
private void setupListeners(){ menu.addActionListener(click -> appController.menu()); tryAgain.addActionListener(click -> appController.scramble()); menu.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent onClick) { menu.setForeground(Color.LIGHT_GRAY); } public void mouseReleased(MouseEvent offClick) { menu.setForeground(Color.WHITE); } public void mouseEntered(MouseEvent enter) { menu.setBorder(new LineBorder(Color.WHITE, 5)); } public void mouseExited(MouseEvent exit) { menu.setBorder(new LineBorder(Color.BLACK, 5)); } }); tryAgain.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent onClick) { tryAgain.setForeground(Color.LIGHT_GRAY); } public void mouseReleased(MouseEvent offClick) { tryAgain.setForeground(Color.WHITE); } public void mouseEntered(MouseEvent enter) { tryAgain.setBorder(new LineBorder(Color.WHITE, 5)); } public void mouseExited(MouseEvent exit) { tryAgain.setBorder(new LineBorder(Color.BLACK, 5)); } }); }
9,135
public Result viewUIUdfFunction(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("id") int id){ logger.info("login user {}, query udf{}", loginUser.getUserName(), id); Map<String, Object> map = udfFuncService.queryUdfFuncDetail(id); return returnDataList(map); }
public Result<UdfFunc> viewUIUdfFunction(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("id") int id){ logger.info("login user {}, query udf{}", loginUser.getUserName(), id); return udfFuncService.queryUdfFuncDetail(id); }
9,136
public void syncBookAndTypeDataWithFile(@PathVariable String fileName) throws IOException{ Resource r = storageService.loadAsResource(fileName); if (!r.exists()) { throw new StorageFileNotFoundException(fileName); } List<BookAndTypeData> data = dataSource.getBookAndTypeData(r.getFile()); if (data != null) { processes.processForBookAndType(data); } }
public void syncBookAndTypeDataWithFile(@PathVariable String fileName) throws IOException{ Resource r = storageService.loadAsResource(fileName); if (!r.exists()) { throw new StorageFileNotFoundException(fileName); } dataSource.importBookAndTypeData(r.getFile()); }
9,137
public void consume(FastqSpot iSpot) throws DataConsumerException{ try { Matcher matcher = VALID_DNA_CHARSET_PATTERN.matcher(iSpot.bases); if (!matcher.matches()) handleInvalidDnaCharset(iSpot.bases, matcher); if (iSpot.bases.length() != iSpot.quals.length()) throw new IllegalArgumentException(String.format("FATAL: Spot bases and qualities length do not match. Malformed spot\n%s\n", iSpot)); if (isPaired(iSpot)) { SAMRecord rec1 = createSamRecord(true, iSpot.name, getForwardBases(iSpot), getForwardQualities(iSpot)); rec1.setFirstOfPairFlag(true); rec1.setSecondOfPairFlag(false); writer.addAlignment(rec1); SAMRecord rec2 = createSamRecord(true, iSpot.name, getReverseBases(iSpot), getReverseQualities(iSpot)); rec2.setFirstOfPairFlag(false); rec2.setSecondOfPairFlag(true); writer.addAlignment(rec2); } else { SAMRecord rec = createSamRecord(false, iSpot.name, iSpot.bases, iSpot.quals); rec.setReadPairedFlag(false); writer.addAlignment(rec); } } catch (InvalidBaseCharacterException ex) { isOk = false; throw ex; } catch (Exception ex) { isOk = false; throw new DataConsumerException(ex); } }
public void consume(FastqSpot iSpot) throws DataConsumerException{ try { validate(iSpot); if (iSpot.isPaired()) { SAMRecord rec1 = createSamRecord(true, iSpot.name, iSpot.forward.bases, iSpot.forward.quals); rec1.setFirstOfPairFlag(true); rec1.setSecondOfPairFlag(false); writer.addAlignment(rec1); SAMRecord rec2 = createSamRecord(true, iSpot.name, iSpot.reverse.bases, iSpot.reverse.quals); rec2.setFirstOfPairFlag(false); rec2.setSecondOfPairFlag(true); writer.addAlignment(rec2); } else { DataSpot unpaired = iSpot.getUnpaired(); SAMRecord rec = createSamRecord(false, iSpot.name, unpaired.bases, unpaired.quals); rec.setReadPairedFlag(false); writer.addAlignment(rec); } } catch (InvalidBaseCharacterException ex) { isOk = false; throw ex; } catch (Exception ex) { isOk = false; throw new DataConsumerException(ex); } }
9,138
public Result batchDeleteProcessInstanceByIds(@RequestAttribute(value = Constants.SESSION_USER) User loginUser, @PathVariable String projectName, @RequestParam("processInstanceIds") String processInstanceIds){ logger.info("delete process instance by ids, login user:{}, project name:{}, process instance ids :{}", loginUser.getUserName(), projectName, processInstanceIds); Map<String, Object> result = new HashMap<>(); List<String> deleteFailedIdList = new ArrayList<>(); if (StringUtils.isNotEmpty(processInstanceIds)) { String[] processInstanceIdArray = processInstanceIds.split(","); for (String strProcessInstanceId : processInstanceIdArray) { int processInstanceId = Integer.parseInt(strProcessInstanceId); try { Map<String, Object> deleteResult = processInstanceService.deleteProcessInstanceById(loginUser, projectName, processInstanceId); if (!Status.SUCCESS.equals(deleteResult.get(Constants.STATUS))) { deleteFailedIdList.add(strProcessInstanceId); logger.error((String) deleteResult.get(Constants.MSG)); } } catch (Exception e) { deleteFailedIdList.add(strProcessInstanceId); } } } if (!deleteFailedIdList.isEmpty()) { putMsg(result, Status.BATCH_DELETE_PROCESS_INSTANCE_BY_IDS_ERROR, String.join(",", deleteFailedIdList)); } else { putMsg(result, Status.SUCCESS); } return returnDataList(result); }
public Result<Void> batchDeleteProcessInstanceByIds(@RequestAttribute(value = Constants.SESSION_USER) User loginUser, @PathVariable String projectName, @RequestParam("processInstanceIds") String processInstanceIds){ logger.info("delete process instance by ids, login user:{}, project name:{}, process instance ids :{}", loginUser.getUserName(), projectName, processInstanceIds); List<String> deleteFailedIdList = new ArrayList<>(); if (StringUtils.isNotEmpty(processInstanceIds)) { String[] processInstanceIdArray = processInstanceIds.split(","); for (String strProcessInstanceId : processInstanceIdArray) { int processInstanceId = Integer.parseInt(strProcessInstanceId); try { Result<Void> deleteResult = processInstanceService.deleteProcessInstanceById(loginUser, projectName, processInstanceId); if (Status.SUCCESS.getCode() != (deleteResult.getCode())) { deleteFailedIdList.add(strProcessInstanceId); logger.error(deleteResult.getMsg()); } } catch (Exception e) { deleteFailedIdList.add(strProcessInstanceId); } } } if (!deleteFailedIdList.isEmpty()) { return Result.errorWithArgs(Status.BATCH_DELETE_PROCESS_INSTANCE_BY_IDS_ERROR, String.join(",", deleteFailedIdList)); } else { return Result.success(null); } }
9,139
public void waddnstr(final int w, final int n, final byte[] cp){ synchronized (display_lock) { TermWindow t = state.getWin(w); if (t != null && state.windowIsVisible(t)) { t.cursor_visible = false; int x0 = t.col; int y0 = t.row; t.addnstr(n, cp); } } }
public void waddnstr(final int w, final int n, final byte[] cp){ synchronized (display_lock) { TermWindow t = state.getWin(w); if (t != null && state.windowIsVisible(t)) { t.cursor_visible = false; t.addnstr(n, cp); } } }
9,140
public Map<String, Object> unauthorizedFile(User loginUser, Integer userId){ Map<String, Object> result = new HashMap<>(); if (isNotAdmin(loginUser, result)) { return result; } List<Resource> resourceList = resourcesMapper.queryResourceExceptUserId(userId); List<Resource> list; if (resourceList != null && !resourceList.isEmpty()) { Set<Resource> resourceSet = new HashSet<>(resourceList); List<Resource> authedResourceList = resourcesMapper.queryAuthorizedResourceList(userId); getAuthorizedResourceList(resourceSet, authedResourceList); list = new ArrayList<>(resourceSet); } else { list = new ArrayList<>(0); } Visitor visitor = new ResourceTreeVisitor(list); result.put(Constants.DATA_LIST, visitor.visit().getChildren()); putMsg(result, Status.SUCCESS); return result; }
public Result<List<ResourceComponent>> unauthorizedFile(User loginUser, Integer userId){ if (isNotAdmin(loginUser)) { return Result.error(Status.USER_NO_OPERATION_PERM); } List<Resource> resourceList = resourcesMapper.queryResourceExceptUserId(userId); List<Resource> list; if (resourceList != null && !resourceList.isEmpty()) { Set<Resource> resourceSet = new HashSet<>(resourceList); List<Resource> authedResourceList = resourcesMapper.queryAuthorizedResourceList(userId); getAuthorizedResourceList(resourceSet, authedResourceList); list = new ArrayList<>(resourceSet); } else { list = new ArrayList<>(0); } Visitor visitor = new ResourceTreeVisitor(list); return Result.success(visitor.visit().getChildren()); }
9,141
public void start(Stage primaryStage) throws IOException{ FXMLLoader loader = new FXMLLoader(getClass().getResource("jetpack.fxml")); Region root = loader.load(); primaryStage.setTitle("Jetpack"); Scene scene = new Scene(root); scene.setOnKeyPressed(e -> root.getOnKeyPressed().handle(e)); scene.setOnKeyReleased(e -> root.getOnKeyReleased().handle(e)); primaryStage.setScene(scene); primaryStage.show(); PhysicsGame game = new PhysicsGame(); game.load(root); game.startGame(); }
public void start(Stage primaryStage) throws IOException{ FXMLLoader loader = new FXMLLoader(getClass().getResource("overlay.fxml")); Region root = loader.load(); primaryStage.setTitle("Jetpack"); Scene scene = new Scene(root); scene.setOnKeyPressed(e -> root.getOnKeyPressed().handle(e)); scene.setOnKeyReleased(e -> root.getOnKeyReleased().handle(e)); primaryStage.setScene(scene); primaryStage.show(); }
9,142
private void setBodyPanel(){ int height = this.getHeight() - LayoutConstants.HEADER_PANEL_HEIGHT - LayoutConstants.FOOTER_PANEL_HEIGHT; Rectangle bounds = new Rectangle(0, LayoutConstants.HEADER_PANEL_HEIGHT, this.getWidth(), height); this.bodyPanel = new BodyPanel(bounds); this.setSloganPane(); this.setBodyScrollPane(); this.bodyPanel.add(this.sloganPane); this.bodyPanel.add(this.bodyScrollPane); }
private void setBodyPanel(){ int height = this.getHeight() - LayoutConstants.HEADER_PANEL_HEIGHT - LayoutConstants.FOOTER_PANEL_HEIGHT; Rectangle bounds = new Rectangle(0, LayoutConstants.HEADER_PANEL_HEIGHT, this.getWidth(), height); this.bodyPanel = new BodyPanel(bounds); this.setSloganPane(); this.setBodyScrollPane(); this.getContentPane().add(this.bodyPanel); }
9,143
private int getKingCouldEscapeHeuristic(int kingCouldEscape, int row, int column){ int i; int heuristicsValue = 0; if (board[0][column].equals(Pawn.ESCAPE)) { for (i = row - 1; i >= 0; i--) { if (!board[i][column].equals(Pawn.EMPTY)) break; } heuristicsValue += (i == 0 ? kingCouldEscape : 0); } if (board[8][column].equals(Pawn.ESCAPE)) { for (i = row + 1; i < board.length; i++) { if (!board[i][column].equals(Pawn.EMPTY)) break; } heuristicsValue += (i == 8 ? kingCouldEscape : 0); } if (board[row][0].equals(Pawn.ESCAPE)) { for (i = column - 1; i >= 0; i--) { if (!board[row][i].equals(Pawn.EMPTY)) break; } heuristicsValue += (i == 0 ? kingCouldEscape : 0); } if (board[row][8].equals(Pawn.ESCAPE)) { for (i = column + 1; i < board.length; i++) { if (!board[row][i].equals(Pawn.EMPTY)) break; } heuristicsValue += (i == 8 ? kingCouldEscape : 0); } return heuristicsValue; }
private int getKingCouldEscapeHeuristic(int kingCouldEscape, int row, int column){ int i; int heuristicsValue = 0; heuristicsValue += (canKingEscapeTop(row, column) ? kingCouldEscape : 0); heuristicsValue += (canKingEscapeBottom(row, column) ? kingCouldEscape : 0); heuristicsValue += (canKingEscapeLeft(row, column) ? kingCouldEscape : 0); heuristicsValue += (canKingEscapeRight(row, column) ? kingCouldEscape : 0); return heuristicsValue; }
9,144
public static PersistentResource<T> loadRecord(Class<T> loadClass, String id, RequestScope requestScope) throws InvalidObjectIdentifierException{ Preconditions.checkNotNull(loadClass); Preconditions.checkNotNull(id); Preconditions.checkNotNull(requestScope); DataStoreTransaction tx = requestScope.getTransaction(); EntityDictionary dictionary = requestScope.getDictionary(); ObjectEntityCache cache = requestScope.getObjectEntityCache(); @SuppressWarnings("unchecked") Object obj = cache.get(dictionary.getJsonAliasFor(loadClass), id); if (obj == null) { Optional<FilterExpression> permissionFilter = getPermissionFilterExpression(loadClass, requestScope); Class<?> idType = dictionary.getIdType(loadClass); obj = tx.loadObject(loadClass, (Serializable) CoerceUtil.coerce(id, idType), permissionFilter, requestScope); if (obj == null) { throw new InvalidObjectIdentifierException(id, loadClass.getSimpleName()); } } PersistentResource<T> resource = new PersistentResource(obj, requestScope); if (!requestScope.getNewResources().contains(resource)) { resource.checkFieldAwarePermissions(ReadPermission.class); } return resource; }
public static PersistentResource<T> loadRecord(Class<T> loadClass, String id, RequestScope requestScope) throws InvalidObjectIdentifierException{ Preconditions.checkNotNull(loadClass); Preconditions.checkNotNull(id); Preconditions.checkNotNull(requestScope); DataStoreTransaction tx = requestScope.getTransaction(); EntityDictionary dictionary = requestScope.getDictionary(); @SuppressWarnings("unchecked") Object obj = requestScope.getObjectById(dictionary.getJsonAliasFor(loadClass), id); if (obj == null) { Optional<FilterExpression> permissionFilter = getPermissionFilterExpression(loadClass, requestScope); Class<?> idType = dictionary.getIdType(loadClass); obj = tx.loadObject(loadClass, (Serializable) CoerceUtil.coerce(id, idType), permissionFilter, requestScope); if (obj == null) { throw new InvalidObjectIdentifierException(id, loadClass.getSimpleName()); } } PersistentResource<T> resource = new PersistentResource(obj, null, requestScope.getUUIDFor(obj), requestScope); if (!requestScope.getNewResources().contains(resource)) { resource.checkFieldAwarePermissions(ReadPermission.class); } return resource; }
9,145
public void replaceAll(UnaryOperator<T> operator){ this.acquireWriteLock(); try { this.delegate.replaceAll(operator); } finally { this.unlockWriteLock(); } }
public void replaceAll(UnaryOperator<T> operator){ this.withWriteLockRun(() -> this.delegate.replaceAll(operator)); }
9,146
protected void execute(){ if (defaultDriveMode != null && defaultDriveMode.doesRequire(drivebase)) { defaultDriveMode.start(); } else { Init.halostrafedrive.start(); defaultDriveMode = DEFAULT; } }
protected void execute(){ if (defaultDriveMode == null || !defaultDriveMode.doesRequire(drivebase)) { defaultDriveMode = DEFAULT; } defaultDriveMode.start(); }
9,147
public static boolean isEmpty(List list){ if (list == null || list.size() == 0) { return true; } return false; }
public static boolean isEmpty(List list){ return list == null || list.size() == 0; }
9,148
private void loadRecipe(long recipeId){ mViewModel.getIngredients(recipeId).observe(this, ingredients -> { if (ingredients == null) { } else { mRecipeAdapter.setIngredientsData(ingredients); } }); mViewModel.getSteps(recipeId).observe(this, steps -> { if (steps == null) { } else { mRecipeAdapter.setStepsData(steps); if (mSelectedItem != RecyclerView.NO_POSITION) { mRecipeAdapter.setSelected(mSelectedItem); } } }); }
private void loadRecipe(long recipeId){ mViewModel.getIngredients(recipeId).observe(this, ingredients -> { if (ingredients != null) { mRecipeAdapter.setIngredientsData(ingredients); } }); mViewModel.getSteps(recipeId).observe(this, steps -> { if (steps != null) { mRecipeAdapter.setStepsData(steps); if (mSelectedItem != RecyclerView.NO_POSITION) { mRecipeAdapter.setSelected(mSelectedItem); } } }); }
9,149
public int getAntiPoisonBlockCount(World world, Vector3 startingPosition, Vector3 endingPosition){ Vector3 delta = endingPosition.clone().subtract(startingPosition).normalize(); Vector3 targetPosition = startingPosition.clone(); double totalDistance = startingPosition.distance(endingPosition); int count = 0; if (totalDistance > 1.0D) { while (targetPosition.distance(endingPosition) <= totalDistance) { Block block = targetPosition.getBlock(world); if (block instanceof IAntiPoisonBlock) { if (((IAntiPoisonBlock) block).isPoisonPrevention(world, targetPosition.intX(), targetPosition.intY(), targetPosition.intZ(), name)) { count++; } } targetPosition.add(delta); } } return count; }
public int getAntiPoisonBlockCount(World world, Position startingPosition, Position endingPosition){ Position delta = endingPosition.subtract(startingPosition).normalize(); double totalDistance = startingPosition.distance(endingPosition); int count = 0; if (totalDistance > 1.0D) { while (startingPosition.distance(endingPosition) <= totalDistance) { Block block = startingPosition.getBlock(world); if (block instanceof IAntiPoisonBlock) { if (((IAntiPoisonBlock) block).isPoisonPrevention(world, startingPosition.getIntX(), startingPosition.getIntY(), startingPosition.getIntZ(), name)) { count++; } } startingPosition.add(delta); } } return count; }
9,150
public void fail3Test(){ DefaultInitializer di_ = new DefaultInitializer(); KeyWords kw_ = new KeyWords(); LgNames lgName_ = new CustLgNames(); InitializationLgNames.basicStandards(lgName_); kw_.setKeyWordAbstract("<"); AnalyzedTestContext s_ = getCtx(di_, kw_, lgName_); StringMap<String> keyWords_ = kw_.allKeyWords(); validateKeyWordContents(kw_, s_, keyWords_); assertTrue(s_.getAnalyzing().getMessages().displayStdErrors(), !s_.getAnalyzing().isEmptyStdError()); }
public void fail3Test(){ KeyWords kw_ = new KeyWords(); LgNames lgName_ = new CustLgNames(); InitializationLgNames.basicStandards(lgName_); kw_.setKeyWordAbstract("<"); AnalyzedTestContext s_ = getCtx(kw_, lgName_); StringMap<String> keyWords_ = kw_.allKeyWords(); validateKeyWordContents(kw_, s_, keyWords_); assertTrue(s_.getAnalyzing().getMessages().displayStdErrors(), !s_.getAnalyzing().isEmptyStdError()); }
9,151
public boolean equals(Object obj){ if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CategorieProduit other = (CategorieProduit) obj; if (categorieParent == null) { if (other.categorieParent != null) return false; } else if (!categorieParent.equals(other.categorieParent)) return false; if (categorieProduitId == null) { if (other.categorieProduitId != null) return false; } else if (!categorieProduitId.equals(other.categorieProduitId)) return false; return true; }
public boolean equals(Object obj){ if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CategorieProduit other = (CategorieProduit) obj; if (categorieProduitId == null) { if (other.categorieProduitId != null) return false; } else if (!categorieProduitId.equals(other.categorieProduitId)) return false; return true; }
9,152
public void viewBookDetails() throws ServletException, IOException{ int bookId = Integer.parseInt(request.getParameter("id")); List<Category> listCategory = categoryDAO.listAll(); request.setAttribute("listCategory", listCategory); Book book = bookDAO.get(bookId); String destPage = "frontend/book_detail.jsp"; if (book != null) { request.setAttribute("book", book); } else { destPage = "frontend/message.jsp"; String message = "Sorry, the book with ID " + bookId + " is not available."; request.setAttribute("message", message); } RequestDispatcher requestDispatcher = request.getRequestDispatcher(destPage); requestDispatcher.forward(request, response); }
public void viewBookDetails() throws ServletException, IOException{ int bookId = Integer.parseInt(request.getParameter("id")); Book book = bookDAO.get(bookId); String destPage = "frontend/book_detail.jsp"; if (book != null) { request.setAttribute("book", book); } else { destPage = "frontend/message.jsp"; String message = "Sorry, the book with ID " + bookId + " is not available."; request.setAttribute("message", message); } RequestDispatcher requestDispatcher = request.getRequestDispatcher(destPage); requestDispatcher.forward(request, response); }
9,153
public void batchExportProcessDefinitionByIds(User loginUser, String projectName, String processDefinitionIds, HttpServletResponse response){ if (StringUtils.isEmpty(processDefinitionIds)) { return; } Project project = projectMapper.queryByName(projectName); Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); Status resultStatus = (Status) checkResult.get(Constants.STATUS); if (resultStatus != Status.SUCCESS) { return; } List<ProcessMeta> processDefinitionList = getProcessDefinitionList(processDefinitionIds); if (CollectionUtils.isNotEmpty(processDefinitionList)) { downloadProcessDefinitionFile(response, processDefinitionList); } }
public void batchExportProcessDefinitionByIds(User loginUser, String projectName, String processDefinitionIds, HttpServletResponse response){ if (StringUtils.isEmpty(processDefinitionIds)) { return; } Project project = projectMapper.queryByName(projectName); CheckParamResult checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); if (!Status.SUCCESS.equals(checkResult.getStatus())) { return; } List<ProcessMeta> processDefinitionList = getProcessDefinitionList(processDefinitionIds); if (CollectionUtils.isNotEmpty(processDefinitionList)) { downloadProcessDefinitionFile(response, processDefinitionList); } }
9,154
private URLStreamHandler findHandler(String protocol){ URLStreamHandler streamHandler = null; String packageList = System.getProperty("java.protocol.handler.pkgs"); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (packageList != null && contextClassLoader != null) { for (String packageName : packageList.split("\\|")) { String className = packageName + "." + protocol + ".Handler"; try { Class<?> c = contextClassLoader.loadClass(className); streamHandler = (URLStreamHandler) c.newInstance(); if (streamHandler != null) { return streamHandler; } } catch (IllegalAccessException ignored) { } catch (InstantiationException ignored) { } catch (ClassNotFoundException ignored) { } catch (Throwable e) { } } } if (Build.VERSION.SDK_INT >= 19) { if (protocol.equals("http")) { streamHandler = createStreamHandler("com.android.okhttp.HttpHandler"); } else if (protocol.equals("https")) { streamHandler = createStreamHandler("com.android.okhttp.HttpsHandler"); } } else { if (protocol.equals("http")) { streamHandler = createStreamHandler("libcore.net.http.HttpHandler"); } else if (protocol.equals("https")) { streamHandler = createStreamHandler("libcore.net.http.HttpsHandler"); } } return streamHandler; }
private URLStreamHandler findHandler(String protocol){ URLStreamHandler streamHandler = null; String packageList = System.getProperty("java.protocol.handler.pkgs"); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); if (packageList != null && contextClassLoader != null) { for (String packageName : packageList.split("\\|")) { String className = packageName + "." + protocol + ".Handler"; try { Class<?> c = contextClassLoader.loadClass(className); streamHandler = (URLStreamHandler) c.newInstance(); if (streamHandler != null) { return streamHandler; } } catch (IllegalAccessException ignore) { } catch (InstantiationException ignore) { } catch (ClassNotFoundException ignore) { } } } if (Build.VERSION.SDK_INT >= 19) { if (protocol.equals("http")) { streamHandler = createStreamHandler("com.android.okhttp.HttpHandler"); } else if (protocol.equals("https")) { streamHandler = createStreamHandler("com.android.okhttp.HttpsHandler"); } } else { if (protocol.equals("http")) { streamHandler = createStreamHandler("libcore.net.http.HttpHandler"); } else if (protocol.equals("https")) { streamHandler = createStreamHandler("libcore.net.http.HttpsHandler"); } } return streamHandler; }
9,155
public void undoCde(){ tourneeRedo.clone(tournee, tourneeRedo); tournee.clone(oldTournee, tournee); tournee.SignalerFinDajoutPointsLivraisons(); }
public void undoCde(){ tourneeRedo.clone(tournee, tourneeRedo); tournee.clone(oldTournee, tournee); }
9,156
public Map<String, Object> queryProcessDefinitionVersions(User loginUser, String projectName, int pageNo, int pageSize, int processDefinitionId){ Map<String, Object> result = new HashMap<>(); if (pageNo <= 0 || pageSize <= 0) { putMsg(result, Status.QUERY_PROCESS_DEFINITION_VERSIONS_PAGE_NO_OR_PAGE_SIZE_LESS_THAN_1_ERROR, pageNo, pageSize); return result; } Project project = projectMapper.queryByName(projectName); Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); Status resultStatus = (Status) checkResult.get(Constants.STATUS); if (resultStatus != Status.SUCCESS) { return checkResult; } PageInfo<ProcessDefinitionVersion> pageInfo = new PageInfo<>(pageNo, pageSize); Page<ProcessDefinitionVersion> page = new Page<>(pageNo, pageSize); IPage<ProcessDefinitionVersion> processDefinitionVersionsPaging = processDefinitionVersionMapper.queryProcessDefinitionVersionsPaging(page, processDefinitionId); List<ProcessDefinitionVersion> processDefinitionVersions = processDefinitionVersionsPaging.getRecords(); pageInfo.setLists(processDefinitionVersions); pageInfo.setTotalCount((int) processDefinitionVersionsPaging.getTotal()); return ImmutableMap.of(Constants.MSG, Status.SUCCESS.getMsg(), Constants.STATUS, Status.SUCCESS, Constants.DATA_LIST, pageInfo); }
public Result<PageListVO<ProcessDefinitionVersion>> queryProcessDefinitionVersions(User loginUser, String projectName, int pageNo, int pageSize, int processDefinitionId){ if (pageNo <= 0 || pageSize <= 0) { CheckParamResult checkResult = new CheckParamResult(); putMsg(checkResult, Status.QUERY_PROCESS_DEFINITION_VERSIONS_PAGE_NO_OR_PAGE_SIZE_LESS_THAN_1_ERROR, pageNo, pageSize); return Result.error(checkResult); } Project project = projectMapper.queryByName(projectName); CheckParamResult checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); if (!Status.SUCCESS.equals(checkResult.getStatus())) { return Result.error(checkResult); } PageInfo<ProcessDefinitionVersion> pageInfo = new PageInfo<>(pageNo, pageSize); Page<ProcessDefinitionVersion> page = new Page<>(pageNo, pageSize); IPage<ProcessDefinitionVersion> processDefinitionVersionsPaging = processDefinitionVersionMapper.queryProcessDefinitionVersionsPaging(page, processDefinitionId); List<ProcessDefinitionVersion> processDefinitionVersions = processDefinitionVersionsPaging.getRecords(); pageInfo.setLists(processDefinitionVersions); pageInfo.setTotalCount((int) processDefinitionVersionsPaging.getTotal()); return Result.success(new PageListVO<>(pageInfo)); }
9,157
public boolean next(ImmutableBytesWritable key, Result value) throws IOException{ Result result; try { result = this.scanner.next(); } catch (UnknownScannerException e) { LOG.debug("recovered from " + StringUtils.stringifyException(e)); restart(lastRow); this.scanner.next(); result = this.scanner.next(); } if (result != null && result.size() > 0) { key.set(result.getRow()); lastRow = key.get(); if (result instanceof Writable && value instanceof Writable) { Writables.copyWritable((Writable) result, (Writable) value); } else { try { Method m = result.getClass().getMethod("copyFrom", Result.class); m.invoke(value, result); } catch (NoSuchMethodException e) { throw new IOException(e); } catch (SecurityException e) { throw new IOException(e); } catch (IllegalAccessException e) { throw new IOException(e); } catch (IllegalArgumentException e) { throw new IOException(e); } catch (InvocationTargetException e) { throw new IOException(e); } } return true; } return false; }
public boolean next(ImmutableBytesWritable key, Result value) throws IOException{ Result result; try { result = this.scanner.next(); } catch (UnknownScannerException e) { LOG.debug("recovered from " + StringUtils.stringifyException(e)); restart(lastRow); this.scanner.next(); result = this.scanner.next(); } if (result != null && result.size() > 0) { key.set(result.getRow()); lastRow = key.get(); if (result instanceof Writable && value instanceof Writable) { Writables.copyWritable((Writable) result, (Writable) value); } else { try { Method m = result.getClass().getMethod("copyFrom", Result.class); m.invoke(value, result); } catch (NoSuchMethodException | SecurityException | IllegalAccessException | InvocationTargetException e) { throw new IOException(e); } } return true; } return false; }
9,158
public static void beforeClass(){ s3Client = new S3Client(); s3Client.onInit(); }
public static void beforeClass(){ s3Client = new S3Client(); }
9,159
public UserBO getUser() throws Exception{ LoginBO userLogin = userLoginService.getUserLogin(); Optional<Users> rs = userRepository.findById(userLogin.getUserId()); if (rs.isPresent()) { Users user = rs.get(); UserBO userBO = UserBO.builder().name(user.getName()).surname(user.getSurname()).dateOfBirth(user.getDateOfBirth()).build(); try { List<OrderBO> list = orderService.listOrder(user.getId()); for (OrderBO order : list) { userBO.addBooks(order.getBookId()); } } catch (ExceptionDataNotFound orderNotFound) { log.info(orderNotFound.getMessage()); } return userBO; } throw new ExceptionDataNotFound("user", ""); }
public UserBO getUser() throws Exception{ LoginBO userLogin = userLoginService.getUserLogin(); if (null != userLogin) { UserBO userBO = userLogin.getUserInfo(); try { List<OrderBO> list = orderService.findByUsername(userLogin.getUsername()); for (OrderBO order : list) { userBO.addBooks(order.getBookId()); } } catch (ExceptionDataNotFound orderNotFound) { log.info(orderNotFound.getMessage()); } return userBO; } throw new ExceptionDataNotFound("user", ""); }
9,160
private HttpHeaders createHeaders(final String userId, final String password){ return new HttpHeaders() { { String auth = userId + ":" + password; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII)); String authHeader = "Basic " + new String(encodedAuth); set(HttpHeaders.AUTHORIZATION, authHeader); } }; }
private HttpHeaders createHeaders(final String userId, final String password){ byte[] encodedAuth = Base64.encodeBase64((userId + ":" + password).getBytes(StandardCharsets.US_ASCII)); String authHeader = "Basic " + new String(encodedAuth); HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.AUTHORIZATION, authHeader); return headers; }
9,161
public void replaceSymbols(Function<Symbol, Symbol> replaceFunction){ super.replaceSymbols(replaceFunction); if (whereClause.hasQuery()) { Symbol query = whereClause.query(); Symbol newQuery = replaceFunction.apply(query); if (query != newQuery) { whereClause = new WhereClause(newQuery, whereClause.docKeys().orElse(null), whereClause.partitions()); } } Lists2.replaceItems(toCollect, replaceFunction); if (orderBy != null) { orderBy.replace(replaceFunction); } }
public void replaceSymbols(Function<Symbol, Symbol> replaceFunction){ super.replaceSymbols(replaceFunction); whereClause.replace(replaceFunction); Lists2.replaceItems(toCollect, replaceFunction); if (orderBy != null) { orderBy.replace(replaceFunction); } }
9,162
public String userBuyin(@RequestParam String username, @RequestParam int amount){ String result = game.rebuy(username, amount); return result; }
public String userBuyin(@RequestParam String username, @RequestParam int amount){ return game.rebuy(username, amount); }
9,163
public void addProject(final File projectRoot){ final File wcRoot = this.determineWorkingCopyRoot(projectRoot); if (wcRoot != null) { boolean wcCreated = false; synchronized (this.projectsPerWcMap) { Set<File> projects = this.projectsPerWcMap.get(wcRoot); if (projects == null) { projects = new LinkedHashSet<>(); this.projectsPerWcMap.put(wcRoot, projects); wcCreated = true; } projects.add(projectRoot); } if (wcCreated) { final Job job = Job.create("Analyzing SVN working copy at " + wcRoot, new IJobFunction() { @Override public IStatus run(final IProgressMonitor monitor) { SvnWorkingCopyManager.getInstance().getWorkingCopy(wcRoot); return Status.OK_STATUS; } }); job.schedule(); } } }
public void addProject(final File projectRoot){ final File wcRoot = this.determineWorkingCopyRoot(projectRoot); if (wcRoot != null) { boolean wcCreated = false; synchronized (this.projectsPerWcMap) { Set<File> projects = this.projectsPerWcMap.get(wcRoot); if (projects == null) { projects = new LinkedHashSet<>(); this.projectsPerWcMap.put(wcRoot, projects); wcCreated = true; } projects.add(projectRoot); } if (wcCreated) { SvnWorkingCopyManager.getInstance().getWorkingCopy(wcRoot); } } }
9,164
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState){ final Bundle arguments = getArguments(); if (arguments != null) { final Session session = Session.getSession(view.getContext()); amountToPay = session.getAmountRepository().getAmountToPay(); hasDiscount = session.getDiscountRepository().getDiscount() != null; final OneTapModel model = (OneTapModel) arguments.getSerializable(ARG_ONE_TAP_MODEL); presenter = new OneTapPresenter(model, session.getPaymentRepository()); configureView(view, presenter, model); presenter.attachView(this); trackScreen(model); } }
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState){ final Bundle arguments = getArguments(); if (arguments != null) { final Session session = Session.getSession(view.getContext()); final OneTapModel model = (OneTapModel) arguments.getSerializable(ARG_ONE_TAP_MODEL); presenter = new OneTapPresenter(model, session.getPaymentRepository()); configureView(view, presenter, model); presenter.attachView(this); trackScreen(model); } }
9,165
public Mono<ServerResponse> createAccount(final ServerRequest request){ return request.bodyToMono(Account.class).log(null, Level.INFO).flatMap(new Function<Account, Mono<Account>>() { @Override public Mono<Account> apply(Account acc) { return repository.save(acc); } }).flatMap(new Function<Account, Mono<ServerResponse>>() { @Override public Mono<ServerResponse> apply(Account acc) { return ServerResponse.created(URI.create("")).contentType(MediaType.APPLICATION_JSON).bodyValue(acc); } }).onErrorResume(new Function<Throwable, Mono<? extends ServerResponse>>() { @Override public Mono<? extends ServerResponse> apply(Throwable th) { return ServerResponse.badRequest().contentType(MediaType.APPLICATION_JSON).bodyValue(th.getMessage()); } }); }
public Mono<ServerResponse> createAccount(final ServerRequest request){ return request.bodyToMono(Account.class).flatMap((Function<Account, Mono<Account>>) acc -> repository.save(acc)).flatMap((Function<Account, Mono<ServerResponse>>) acc -> ServerResponse.created(URI.create("")).contentType(MediaType.APPLICATION_JSON).bodyValue(acc)).onErrorResume(th -> ServerResponse.badRequest().contentType(MediaType.APPLICATION_JSON).bodyValue(th.getMessage())); }
9,166
public void onResponse(GetBraintreeTokenResponse token){ Menu.getInstance().getDataManager().setClientBraintreeToken(token.token); Settings.setMajor(SplashActivity.this, "1"); Settings.setMinor(SplashActivity.this, "1"); onBeaconFound(); }
public void onResponse(GetBraintreeTokenResponse token){ Menu.getInstance().getDataManager().setClientBraintreeToken(token.token); scanForIBeacon(); }
9,167
public void handle(Session session, Player player, PacketLogin message){ final State state = session.getState(); if (state == State.LOGIN) { session.setState(State.PLAY); session.sendPacket(new PacketLogin(0, "", 0, 0)); final Player sessionPlayer = new Player(session, message.getUsername()); Composter.addPlayer(sessionPlayer); session.setPlayer(sessionPlayer); } else { session.disconnect("Already logged in."); } }
public void handle(Session session, Player player, PacketLogin message){ final State state = session.getState(); if (state == State.LOGIN) { session.setState(State.PLAY); session.sendPacket(new PacketLogin(0, message.getUsername(), 0, 0)); session.setPlayer(new Player(session, message.getUsername())); } else { session.disconnect("Already logged in."); } }
9,168
private Command prepareReport(String arguments) throws IllegalFormatException{ final Matcher matcher = REPORT_DATA_ARGS_FORMAT.matcher(arguments.trim()); if (!matcher.matches()) { logger.log(Level.WARNING, "Does not match Report Command Format"); throw new IllegalFormatException(String.format(CORRECT_COMMAND_MESSAGE_STRING_FORMAT, ReportCommand.REPORT_DATA_ARGS_FORMAT_STRING)); } String type = matcher.group("type"); String startYearMonth = matcher.group("startYearMonth"); String endYearMonth = matcher.group("endYearMonth"); Command reportCommand; if (endYearMonth == null) { reportCommand = new ReportCommand(startYearMonth, "", type); } else { reportCommand = new ReportCommand(startYearMonth, endYearMonth, type); } assert reportCommand.getClass() == ReportCommand.class : "report should return reportCommand\n"; logger.log(Level.INFO, "ReportCommand parse success."); return reportCommand; }
private Command prepareReport(String arguments) throws IllegalFormatException{ final Matcher matcher = REPORT_DATA_ARGS_FORMAT.matcher(arguments.trim()); if (!matcher.matches()) { logger.log(Level.WARNING, "Does not match Report Command Format"); throw new IllegalFormatException(String.format(CORRECT_COMMAND_MESSAGE_STRING_FORMAT, ReportCommand.REPORT_DATA_ARGS_FORMAT_STRING)); } String type = matcher.group("type"); String startYearMonth = matcher.group("startYearMonth"); String endYearMonth = matcher.group("endYearMonth"); Command reportCommand; reportCommand = new ReportCommand(startYearMonth, Objects.requireNonNullElse(endYearMonth, ""), type); logger.log(Level.INFO, "ReportCommand parse success."); return reportCommand; }
9,169
public void initMocks() throws IOException{ MockitoAnnotations.initMocks(this); spyCommand = spy(new BackupCommand()); spyCommand.facade = mockInstallationManagerProxy; performBaseMocks(spyCommand, true); }
public void initMocks() throws IOException{ MockitoAnnotations.initMocks(this); spyCommand = spy(new BackupCommand()); performBaseMocks(spyCommand, true); }
9,170
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!"); } } }
9,171
public Map<T, Set<Object>> removeAll(CharID id){ Map<T, Set<Object>> componentMap = getCachedMap(id); if (componentMap == null) { return Collections.emptyMap(); } removeCache(id); for (T obj : componentMap.keySet()) { fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED); } return componentMap; }
public Map<T, Set<Object>> removeAll(CharID id){ Map<T, Set<Object>> componentMap = getCachedMap(id); if (componentMap == null) { return Collections.emptyMap(); } removeCache(id); componentMap.keySet().forEach(obj -> fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED)); return componentMap; }
9,172
public boolean save(SignalStrength signalStrength){ System.out.println("Save Signal Object: " + signalStrength); try { PGobject pGobject = new PGobject(); pGobject.setValue(signalStrength.getBssid()); pGobject.setType("macaddr"); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO " + table + " VALUES (?,?,?,?)"); preparedStatement.setObject(1, pGobject); preparedStatement.setInt(2, signalStrength.getSignalStrength()); preparedStatement.setObject(3, signalStrength.getLocation()); preparedStatement.setLong(4, System.currentTimeMillis()); int response = preparedStatement.executeUpdate(); preparedStatement.close(); return true; } catch (SQLException e) { return false; } }
public boolean save(SignalStrength signalStrength){ try { PGobject pGobject = new PGobject(); pGobject.setValue(signalStrength.getBssid()); pGobject.setType("macaddr"); PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO " + table + " VALUES (?,?,?,?)"); preparedStatement.setObject(1, pGobject); preparedStatement.setInt(2, signalStrength.getSignalStrength()); preparedStatement.setObject(3, signalStrength.getLocation()); preparedStatement.setLong(4, System.currentTimeMillis()); int response = preparedStatement.executeUpdate(); preparedStatement.close(); return true; } catch (SQLException e) { return false; } }
9,173
private void addSavedButtons(WGridPanel root){ ArrayList<JSONObject> commListCopy = MacroButtons.getMasterCommList(); System.out.println("I be doin my thing here"); if (commListCopy != null) { for (int i = 0; i < commListCopy.size(); i++) { String name = commListCopy.get(i).get("name").toString(); String command = commListCopy.get(i).get("command").toString(); addGUIButton(root, xValue, name, command); } } }
private void addSavedButtons(WGridPanel root){ ArrayList<JSONObject> commListCopy = MacroButtons.getMasterCommList(); if (commListCopy != null) { for (int i = 0; i < commListCopy.size(); i++) { String name = commListCopy.get(i).get("name").toString(); String command = commListCopy.get(i).get("command").toString(); addGUIButton(root, xValue, name, command); } } }
9,174
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_touch); btn1 = (Button) findViewById(R.id.button1); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 1 clicked", Toast.LENGTH_SHORT).show(); } }); btn2 = (Button) findViewById(R.id.button2); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 2 clicked", Toast.LENGTH_SHORT).show(); } }); btn3 = (Button) findViewById(R.id.button3); btn3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 3 clicked", Toast.LENGTH_SHORT).show(); } }); btn4 = (Button) findViewById(R.id.button4); btn4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 4 clicked", Toast.LENGTH_SHORT).show(); } }); try { tm = new TouchManager(); } catch (DeviceException e) { android.util.Log.e(getClass().getName(), "While creating activity", e); return; } }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_touch); Button btn1 = (Button) findViewById(R.id.button1); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 1 clicked", Toast.LENGTH_SHORT).show(); } }); Button btn2 = (Button) findViewById(R.id.button2); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 2 clicked", Toast.LENGTH_SHORT).show(); } }); Button btn3 = (Button) findViewById(R.id.button3); btn3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 3 clicked", Toast.LENGTH_SHORT).show(); } }); Button btn4 = (Button) findViewById(R.id.button4); btn4.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getBaseContext(), "Button 4 clicked", Toast.LENGTH_SHORT).show(); } }); try { tm = new TouchManager(); } catch (DeviceException e) { android.util.Log.e(getClass().getName(), "While creating activity", e); } }
9,175
public void testAddAnnotation() throws ParseException{ String code = "public class B { public void foo(){} }"; 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); List<AnnotationExpr> annotations = new LinkedList<AnnotationExpr>(); annotations.add(new MarkerAnnotationExpr(new NameExpr("Override"))); md.setAnnotations(annotations); 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()); assertCode(actions, code, "public class B { @Override public void foo(){} }"); code = "public class B {\n public void foo(){\n }\n }"; cu = parser.parse(code, false); cu2 = parser.parse(code, false); md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); annotations = new LinkedList<AnnotationExpr>(); annotations.add(new MarkerAnnotationExpr(new NameExpr("Override"))); md.setAnnotations(annotations); visitor = new ChangeLogVisitor(); ctx = new VisitorContext(); ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2); visitor.visit((CompilationUnit) cu, ctx); actions = visitor.getActionsToApply(); Assert.assertEquals(1, actions.size()); assertCode(actions, code, "public class B {\n @Override\n public void foo(){\n }\n }"); }
public void testAddAnnotation() throws ParseException{ String code = "public class B { public void foo(){} }"; 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); List<AnnotationExpr> annotations = new LinkedList<AnnotationExpr>(); annotations.add(new MarkerAnnotationExpr(new NameExpr("Override"))); md.setAnnotations(annotations); List<Action> actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); assertCode(actions, code, "public class B { @Override public void foo(){} }"); code = "public class B {\n public void foo(){\n }\n }"; cu = parser.parse(code, false); cu2 = parser.parse(code, false); md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0); annotations = new LinkedList<AnnotationExpr>(); annotations.add(new MarkerAnnotationExpr(new NameExpr("Override"))); md.setAnnotations(annotations); actions = getActions(cu2, cu); Assert.assertEquals(1, actions.size()); assertCode(actions, code, "public class B {\n @Override\n public void foo(){\n }\n }"); }
9,176
public Map<String, Object> queryList(User loginUser){ Map<String, Object> result = new HashMap<>(); if (isNotAdmin(loginUser, result)) { return result; } List<Queue> queueList = queueMapper.selectList(null); result.put(Constants.DATA_LIST, queueList); putMsg(result, Status.SUCCESS); return result; }
public Result<List<Queue>> queryList(User loginUser){ if (isNotAdmin(loginUser)) { return Result.error(Status.USER_NO_OPERATION_PERM); } List<Queue> queueList = queueMapper.selectList(null); return Result.success(queueList); }
9,177
public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()) { case R.id.action_led: replaceFragment(new FragmentLED(), true); return true; case R.id.action_toggle: Storage storage = Storage.getInstance(this); requestQueue.add(new ToggleRequest(new Response.Listener<ResponseCollection>() { @Override public void onResponse(ResponseCollection response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }, storage.getCredentials(), storage.getUsername())); return true; default: return super.onOptionsItemSelected(item); } }
public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()) { case R.id.action_led: replaceFragment(new FragmentLED(), true); return true; default: return super.onOptionsItemSelected(item); } }
9,178
public void toggleBookmark(Word word){ if (word.isBookmarked()) { mRemoveBookmarkUseCase.setParams(new RemoveBookmarkUseCase.Params(word, mCurrTransMode)); mCaseExecutor.execute(mRemoveBookmarkUseCase, new UseCase.Callback<RemoveBookmarkUseCase.Result>() { @Override public void onSuccess(RemoveBookmarkUseCase.Result result) { } @Override public void onFailed(Throwable err) { } }); } else { mAddBookmarkUseCase.setParams(new AddBookmarkUseCase.Params(word, mCurrTransMode)); mCaseExecutor.execute(mAddBookmarkUseCase, new UseCase.Callback<AddBookmarkUseCase.Result>() { @Override public void onSuccess(AddBookmarkUseCase.Result result) { } @Override public void onFailed(Throwable err) { } }); } }
public void toggleBookmark(Word word){ if (word.isBookmarked()) { mRemoveBookmarkUseCase.setParams(new RemoveBookmarkUseCase.Params(word, mCurrTransMode)); mCaseExecutor.execute(mRemoveBookmarkUseCase, new UseCase.CbAdapter<RemoveBookmarkUseCase.Result>()); } else { mAddBookmarkUseCase.setParams(new AddBookmarkUseCase.Params(word, mCurrTransMode)); mCaseExecutor.execute(mAddBookmarkUseCase, new UseCase.CbAdapter<AddBookmarkUseCase.Result>()); } }
9,179
public int compare(SmartRegisterClient oneClient, SmartRegisterClient anotherClient2){ CommonPersonObjectClient commonPersonObjectClient = (CommonPersonObjectClient) oneClient; CommonPersonObjectClient commonPersonObjectClient2 = (CommonPersonObjectClient) anotherClient2; switch(byMonthlyAndByDaily) { case ByMonth: commonPersonObjectClient.getDetails().get(field).equalsIgnoreCase("monthly"); commonPersonObjectClient2.getDetails().get(field).equalsIgnoreCase("monthly"); return 1; break; case ByDaily: commonPersonObjectClient.getDetails().get(field).equalsIgnoreCase("daily"); return 1; break; } }
public int compare(SmartRegisterClient oneClient, SmartRegisterClient anotherClient2){ return 0; }
9,180
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException{ Sequence value = Sequence.EMPTY_SEQUENCE; boolean trim = true; if (!args[0].isEmpty()) { final String str = args[0].getStringValue(); if (args.length == 2) { trim = args[1].effectiveBooleanValue(); } if (isCalledAs("base64-encode")) { final Base64Encoder enc = new Base64Encoder(); enc.translate(str.getBytes()); if (trim) { value = new StringValue(new String(enc.getCharArray()).trim()); } else { value = new StringValue(new String(enc.getCharArray())); } } else { final Base64Decoder dec = new Base64Decoder(); dec.translate(str); value = new StringValue(new String(dec.getByteArray())); } } return (value); }
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException{ Sequence value = Sequence.EMPTY_SEQUENCE; boolean trim = true; if (!args[0].isEmpty()) { final String str = args[0].getStringValue(); if (args.length == 2) { trim = args[1].effectiveBooleanValue(); } if (isCalledAs("base64-encode")) { String b64Str = Base64.encodeBase64String(str.getBytes(UTF_8)); if (trim) { b64Str = b64Str.trim(); } value = new StringValue(b64Str); } else { final byte[] data = Base64.decodeBase64(str); value = new StringValue(new String(data, UTF_8)); } } return (value); }
9,181
public boolean insert(CollectiveTransaction collectiveTransaction) throws ClassNotFoundException{ Connector connector = new Connector(); Connection connection = connector.Connect(); try { PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO collective_transactions" + "(id, transaction_id, user_id, donation_date, amount) VALUES " + "(?, ?, ?, ?, ?)"); preparedStatement.setLong(1, collectiveTransaction.getId()); preparedStatement.setLong(2, collectiveTransaction.getTransactionId()); preparedStatement.setLong(3, collectiveTransaction.getUserId()); preparedStatement.setDate(4, (Date) collectiveTransaction.getDonationDate()); preparedStatement.setInt(5, collectiveTransaction.getAmount()); preparedStatement.executeQuery(); preparedStatement.close(); connection.close(); return true; } catch (SQLException e) { e.printStackTrace(); } return false; }
public boolean insert(CollectiveTransaction collectiveTransaction) throws ClassNotFoundException{ Connection connection = this.getConnection(); try { PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO collective_transactions" + "(id, transaction_id, user_id, donation_date, amount) VALUES " + "(?, ?, ?, ?, ?)"); preparedStatement.setLong(1, collectiveTransaction.getId()); preparedStatement.setLong(2, collectiveTransaction.getTransactionId()); preparedStatement.setLong(3, collectiveTransaction.getUserId()); preparedStatement.setDate(4, (Date) collectiveTransaction.getDonationDate()); preparedStatement.setInt(5, collectiveTransaction.getAmount()); preparedStatement.executeQuery(); preparedStatement.close(); connection.close(); return true; } catch (SQLException e) { e.printStackTrace(); } return false; }
9,182
private void setupPreCalcVars(MatrixStack matrices, CallbackInfo callbackInfo, Collection<?> u1, int u2, int u3, StatusEffectSpriteManager u4, List<?> u5, Iterator<?> u6, StatusEffectInstance u7, StatusEffect u8, int x, int y){ preX = x; preY = y; }
private void setupPreCalcVars(MatrixStack matrices, CallbackInfo callbackInfo, Collection<?> u1, int u2, int u3, StatusEffectSpriteManager u4, List<?> u5, Iterator<?> u6, StatusEffectInstance u7, StatusEffect u8, int x, int y){ preY = y; }
9,183
public void onStart(){ super.onStart(); Log.d("Inside OnStart Function", "onStart Started"); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); Movies_Choice = sharedPreferences.getString(getString(R.string.pref_rating_choice_key), getString(R.string.pref_rating_choice_default)); Video_Choice = sharedPreferences.getString(getString(R.string.pref_video_choice_key), getString(R.string.pref_video_choice_default)); System.out.println("Movies Choice " + Movies_Choice); System.out.println("Videos Choice " + Video_Choice); if (isNetworkAvailable()) { Log.d("MainActivityFragment ", "Inside OnStart() Function"); FetchMovieData movieData = new FetchMovieData(getActivity()); try { movieData.execute(Movies_Choice, Video_Choice, "1").get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } progressBar.setVisibility(View.GONE); mMovieCursorAdapter.notifyDataSetChanged(); } else { Toast.makeText(getActivity(), "Make Sure that you are connected to Internet and Re-open the App", Toast.LENGTH_LONG).show(); } }
public void onStart(){ super.onStart(); Log.d("Inside OnStart Function", "onStart Started"); Movies_Choice = Utility.getRatingChoice(getActivity()); Video_Choice = Utility.getVideoChoice(getActivity()); System.out.println("Movies Choice " + Movies_Choice); System.out.println("Videos Choice " + Video_Choice); if (Utility.isNetworkAvailable(getActivity())) { Log.d("MainActivityFragment ", "Inside OnStart() Function"); FetchMovieData movieData = new FetchMovieData(getActivity()); try { movieData.execute(Movies_Choice, Video_Choice, "1").get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } progressBar.setVisibility(View.GONE); mMovieCursorAdapter.notifyDataSetChanged(); } else { Toast.makeText(getActivity(), "Make Sure that you are connected to Internet and Re-open the App", Toast.LENGTH_LONG).show(); } }
9,184
public StreamHandler initStreamHandler(){ Log.d(TAG, "initStreamHandler()"); return new StreamHandler() { @Override public void onListen(Object arguments, EventSink events) { Log.d(TAG, "onListen()"); eventSink = events; } @Override public void onCancel(Object arguments) { Log.d(TAG, "onCancel()"); closeGattServer(); } }; }
public StreamHandler initStreamHandler(){ return new StreamHandler() { @Override public void onListen(Object arguments, EventSink events) { Log.d(TAG, "onListen()"); eventSink = events; } @Override public void onCancel(Object arguments) { Log.d(TAG, "onCancel()"); closeGattServer(); } }; }
9,185
public ApiToken authenticateForToken(String accessKey, String secret){ logger.debug("Obtaining access token for application {} given key {}", stormpathClientHelper.getApplicationName(), accessKey); HttpRequest tokenRequest = buildHttpRequest(accessKey, secret); AccessTokenResult result = (AccessTokenResult) stormpathClientHelper.getApplication().authenticateOauthRequest(tokenRequest).withTtl(3600).execute(); TokenResponse token = result.getTokenResponse(); return buildApiToken(token); }
public OauthTokenResponse authenticateForToken(String accessKey, String secret){ logger.debug("Obtaining access token for application {} given key {}", stormpathClientHelper.getApplicationName(), accessKey); HttpRequest tokenRequest = buildHttpRequest(accessKey, secret); AccessTokenResult result = (AccessTokenResult) stormpathClientHelper.getApplication().authenticateOauthRequest(tokenRequest).withTtl(3600).execute(); return buildOauthTokenResponse(result.getTokenResponse(), result.getAccount()); }
9,186
public void calculateArgument29Test(){ StringBuilder xml_ = new StringBuilder(); xml_.append("$public $class pkg.Ex {\n"); xml_.append(" $public $static $int catching(){\n"); xml_.append(" $int t;\n"); xml_.append(" t=0i;\n"); xml_.append(" $iter($int i=0i;4i;1i){\n"); xml_.append(" $try{\n"); xml_.append(" t+=1i;\n"); xml_.append(" $if(i%2==0){\n"); xml_.append(" $continue;\n"); xml_.append(" }\n"); xml_.append(" t+=10i;\n"); xml_.append(" }\n"); xml_.append(" $finally{\n"); xml_.append(" t+=100i;\n"); xml_.append(" }\n"); xml_.append(" }\n"); xml_.append(" $return t;\n"); xml_.append(" }\n"); xml_.append("}\n"); StringMap<String> files_ = new StringMap<String>(); ContextEl cont_ = ctx(); files_.put("pkg/Ex", xml_.toString()); Classes.validateAll(files_, cont_); assertTrue(isEmptyErrors(cont_)); CustList<Argument> args_ = new CustList<Argument>(); MethodId id_ = getMethodId("catching"); Argument ret_ = new Argument(); ret_ = calculateNormal("pkg.Ex", id_, args_, cont_); assertEq(424, getNumber(ret_)); }
public void calculateArgument29Test(){ StringBuilder xml_ = new StringBuilder(); xml_.append("$public $class pkg.Ex {\n"); xml_.append(" $public $static $int catching(){\n"); xml_.append(" $int t;\n"); xml_.append(" t=0i;\n"); xml_.append(" $iter($int i=0i;4i;1i){\n"); xml_.append(" $try{\n"); xml_.append(" t+=1i;\n"); xml_.append(" $if(i%2==0){\n"); xml_.append(" $continue;\n"); xml_.append(" }\n"); xml_.append(" t+=10i;\n"); xml_.append(" }\n"); xml_.append(" $finally{\n"); xml_.append(" t+=100i;\n"); xml_.append(" }\n"); xml_.append(" }\n"); xml_.append(" $return t;\n"); xml_.append(" }\n"); xml_.append("}\n"); StringMap<String> files_ = new StringMap<String>(); files_.put("pkg/Ex", xml_.toString()); ContextEl cont_ = ctxOk(files_); CustList<Argument> args_ = new CustList<Argument>(); MethodId id_ = getMethodId("catching"); Argument ret_ = new Argument(); ret_ = calculateNormal("pkg.Ex", id_, args_, cont_); assertEq(424, getNumber(ret_)); }
9,187
public Page<Message> getPage(final String targetUrl, final TwilioRestClient client){ String resourceUrl = "https://" + Joiner.on(".").skipNulls().join(Domains.CHAT.toString(), client.getRegion(), "twilio", "com") + "/v1/Services/" + this.pathServiceSid + "/Channels/" + this.pathChannelSid + "/Messages"; if (!targetUrl.startsWith(resourceUrl)) { throw new InvalidRequestException("Invalid targetUrl for Message resource."); } Request request = new Request(HttpMethod.GET, targetUrl); return pageForRequest(client, request); }
public Page<Message> getPage(final String targetUrl, final TwilioRestClient client){ Request request = new Request(HttpMethod.GET, targetUrl); return pageForRequest(client, request); }
9,188
public Object call(ArrayList<OperationNode> arguments, String callFileName, int callLine){ setArguments(arguments, callFileName, callLine); var body = getBody(); var str = (String) body.getVariable("str").getValue(); var toBeReplaced = (String) body.getVariable("regex").getValue(); var replacement = (String) body.getVariable("replacement").getValue(); return str.replaceAll(toBeReplaced, replacement); }
public String call(ArrayList<OperationNode> arguments, String callFileName, int callLine){ setArguments(arguments, callFileName, callLine); var body = getBody(); return body.getStringVariableValue("str").replaceAll(body.getStringVariableValue("regex"), body.getStringVariableValue("replacement")); }
9,189
private static String describeDifference(Difference difference, Representation representation){ String actualFieldValue = representation.toStringOf(difference.getActual()); String otherFieldValue = representation.toStringOf(difference.getOther()); boolean sameRepresentation = Objects.equals(actualFieldValue, otherFieldValue); String actualFieldValueRepresentation = sameRepresentation ? representation.unambiguousToStringOf(difference.getActual()) : actualFieldValue; String otherFieldValueRepresentation = sameRepresentation ? representation.unambiguousToStringOf(difference.getOther()) : otherFieldValue; String additionalInfo = difference.getDescription().map(desc -> format("%n- reason : %s", escapePercent(desc))).orElse(""); return format("%nPath to difference: <%s>%n" + "- actual : <%s>%n" + "- expected: <%s>" + additionalInfo, join(difference.getPath()).with("."), escapePercent(actualFieldValueRepresentation), escapePercent(otherFieldValueRepresentation)); }
private static String describeDifference(Difference difference, Representation representation){ UnambiguousRepresentation unambiguousRepresentation = new UnambiguousRepresentation(representation, difference.getActual(), difference.getOther()); String additionalInfo = difference.getDescription().map(desc -> format("%n- reason : %s", escapePercent(desc))).orElse(""); return format("%nPath to difference: <%s>%n" + "- actual : <%s>%n" + "- expected: <%s>" + additionalInfo, join(difference.getPath()).with("."), escapePercent(unambiguousRepresentation.getActual()), escapePercent(unambiguousRepresentation.getExpected())); }
9,190
public RepairSegment map(int index, ResultSet r, StatementContext ctx) throws SQLException{ RingRange range = new RingRange(r.getBigDecimal("start_token").toBigInteger(), r.getBigDecimal("end_token").toBigInteger()); RepairSegment.Builder repairSegmentBuilder = new RepairSegment.Builder(fromSequenceId(r.getLong("run_id")), range, fromSequenceId(r.getLong("repair_unit_id"))); return repairSegmentBuilder.state(RepairSegment.State.values()[r.getInt("state")]).coordinatorHost(r.getString("coordinator_host")).startTime(RepairRunMapper.getDateTimeOrNull(r, "start_time")).endTime(RepairRunMapper.getDateTimeOrNull(r, "end_time")).failCount(r.getInt("fail_count")).build(fromSequenceId(r.getLong("id"))); }
public RepairSegment map(int index, ResultSet r, StatementContext ctx) throws SQLException{ RingRange range = new RingRange(r.getBigDecimal("start_token").toBigInteger(), r.getBigDecimal("end_token").toBigInteger()); return new RepairSegment.Builder(range, fromSequenceId(r.getLong("repair_unit_id"))).withRunId(fromSequenceId(r.getLong("run_id"))).state(RepairSegment.State.values()[r.getInt("state")]).coordinatorHost(r.getString("coordinator_host")).startTime(RepairRunMapper.getDateTimeOrNull(r, "start_time")).endTime(RepairRunMapper.getDateTimeOrNull(r, "end_time")).failCount(r.getInt("fail_count")).build(fromSequenceId(r.getLong("id"))); }
9,191
private Function<Item, Element> itemToElementWithDomain(String domainName){ return item -> { String itemCoverUrl = getCoverUrl(item.getCoverOfItemOrPodcast(), domainName); Element itunesItemThumbnail = new Element(IMAGE, ITUNES_NAMESPACE).setContent(new Text(itemCoverUrl)); Element thumbnail = new Element(THUMBNAIL, MEDIA_NAMESPACE).setAttribute(URL_STRING, itemCoverUrl); Element item_enclosure = new Element(ENCLOSURE).setAttribute(URL_STRING, domainName.concat(item.getProxyURLWithoutExtention()).concat((item.isDownloaded()) ? "." + FilenameUtils.getExtension(item.getFileName()) : mimeTypeService.getExtension(item))); if (item.getLength() != null) item_enclosure.setAttribute(LENGTH, String.valueOf(item.getLength())); if (!isEmpty(item.getMimeType())) item_enclosure.setAttribute(TYPE, item.getMimeType()); return new Element(ITEM).addContent(new Element(TITLE).addContent(new Text(item.getTitle()))).addContent(new Element(DESCRIPTION).addContent(new Text(item.getDescription()))).addContent(new Element(PUB_DATE).addContent(new Text(item.getPubDate().format(DateTimeFormatter.RFC_1123_DATE_TIME)))).addContent(new Element(EXPLICIT, ITUNES_NAMESPACE).addContent(new Text(NO))).addContent(new Element(SUBTITLE, ITUNES_NAMESPACE).addContent(new Text(item.getTitle()))).addContent(new Element(SUMMARY, ITUNES_NAMESPACE).addContent(new Text(item.getDescription()))).addContent(new Element(GUID).addContent(new Text(domainName + item.getProxyURL()))).addContent(itunesItemThumbnail).addContent(thumbnail).addContent(item_enclosure); }; }
private Function<Item, Element> itemToElementWithDomain(String domainName){ return item -> { String itemCoverUrl = getCoverUrl(item.getCoverOfItemOrPodcast(), domainName); Element itunesItemThumbnail = new Element(IMAGE, ITUNES_NAMESPACE).setContent(new Text(itemCoverUrl)); Element thumbnail = new Element(THUMBNAIL, MEDIA_NAMESPACE).setAttribute(URL_STRING, itemCoverUrl); Element item_enclosure = new Element(ENCLOSURE).setAttribute(URL_STRING, domainName.concat(item.getProxyURLWithoutExtention()).concat((item.isDownloaded()) ? "." + FilenameUtils.getExtension(item.getFileName()) : mimeTypeService.getExtension(item))); Option(item.getLength()).map(String::valueOf).forEach(l -> item_enclosure.setAttribute(LENGTH, l)); if (!isEmpty(item.getMimeType())) item_enclosure.setAttribute(TYPE, item.getMimeType()); return new Element(ITEM).addContent(new Element(TITLE).addContent(new Text(item.getTitle()))).addContent(new Element(DESCRIPTION).addContent(new Text(item.getDescription()))).addContent(new Element(PUB_DATE).addContent(new Text(item.getPubDate().format(DateTimeFormatter.RFC_1123_DATE_TIME)))).addContent(new Element(EXPLICIT, ITUNES_NAMESPACE).addContent(new Text(NO))).addContent(new Element(SUBTITLE, ITUNES_NAMESPACE).addContent(new Text(item.getTitle()))).addContent(new Element(SUMMARY, ITUNES_NAMESPACE).addContent(new Text(item.getDescription()))).addContent(new Element(GUID).addContent(new Text(domainName + item.getProxyURL()))).addContent(itunesItemThumbnail).addContent(thumbnail).addContent(item_enclosure); }; }
9,192
public void testToString() throws ParseException{ final AtomicBoolean done = new AtomicBoolean(false); final SVGPathSegMoveto m = new SVGPathSegMoveto(0d, 0d, false); final SVGPathParser parser = new SVGPathParser(m.toString() + " " + seg.toString(), pathSeg -> { if (pathSeg instanceof SVGPathSegMoveto) { return; } done.set(true); final SVGPathSegCurvetoCubicSmooth seg2 = (SVGPathSegCurvetoCubicSmooth) pathSeg; assertEquals(seg.getX(), seg2.getX(), 0.0001); assertEquals(seg.getY(), seg2.getY(), 0.0001); assertEquals(seg.isRelative(), seg2.isRelative()); }); parser.parse(); assertTrue(done.get()); }
public void testToString(){ final AtomicBoolean done = new AtomicBoolean(false); final SVGPathSegMoveto m = new SVGPathSegMoveto(0d, 0d, false); SVGParserUtils.INSTANCE.parseSVGPath(m.toString() + " " + seg.toString(), pathSeg -> { if (pathSeg instanceof SVGPathSegMoveto) { return; } done.set(true); final SVGPathSegCurvetoCubicSmooth seg2 = (SVGPathSegCurvetoCubicSmooth) pathSeg; assertEquals(seg.getX(), seg2.getX(), 0.0001); assertEquals(seg.getY(), seg2.getY(), 0.0001); assertEquals(seg.isRelative(), seg2.isRelative()); }); assertTrue(done.get()); }
9,193
public void actionPerformed(ActionEvent e){ ResourceClassSingleton.getInstance().changeStatusIsWindowOpenedUp(); FiguresJoe.figureScript2(driverManager.getCurrentDriver()); TestJobs2dApp testJobs2dApp = new TestJobs2dApp(); testJobs2dApp.getLogger().info("Remaining ink: " + ResourceClassSingleton.getInstance().getInk()); testJobs2dApp.getLogger().info("Remaining usage: " + ResourceClassSingleton.getInstance().getUsage()); }
public void actionPerformed(ActionEvent e){ ResourceClassSingleton.getInstance().changeStatusIsWindowOpenedUp(); FiguresJoe.figureScript2(driverManager.getCurrentDriver()); }
9,194
public ValidationResult isValid() throws DataException{ if (!Crypto.isValidAddress(groupKickTransactionData.getMember())) return ValidationResult.INVALID_ADDRESS; GroupRepository groupRepository = this.repository.getGroupRepository(); int groupId = groupKickTransactionData.getGroupId(); GroupData groupData = groupRepository.fromGroupId(groupId); if (groupData == null) return ValidationResult.GROUP_DOES_NOT_EXIST; Account admin = getAdmin(); if (!groupRepository.adminExists(groupId, admin.getAddress())) return ValidationResult.NOT_GROUP_ADMIN; Account member = getMember(); if (!groupRepository.joinRequestExists(groupId, member.getAddress()) && !groupRepository.memberExists(groupId, member.getAddress())) return ValidationResult.NOT_GROUP_MEMBER; if (!admin.getAddress().equals(groupData.getOwner()) && groupRepository.adminExists(groupId, member.getAddress())) return ValidationResult.INVALID_GROUP_OWNER; if (groupKickTransactionData.getFee().compareTo(BigDecimal.ZERO) <= 0) return ValidationResult.NEGATIVE_FEE; if (!Arrays.equals(admin.getLastReference(), groupKickTransactionData.getReference())) return ValidationResult.INVALID_REFERENCE; if (admin.getConfirmedBalance(Asset.QORA).compareTo(groupKickTransactionData.getFee()) < 0) return ValidationResult.NO_BALANCE; return ValidationResult.OK; }
public ValidationResult isValid() throws DataException{ if (!Crypto.isValidAddress(groupKickTransactionData.getMember())) return ValidationResult.INVALID_ADDRESS; GroupRepository groupRepository = this.repository.getGroupRepository(); int groupId = groupKickTransactionData.getGroupId(); GroupData groupData = groupRepository.fromGroupId(groupId); if (groupData == null) return ValidationResult.GROUP_DOES_NOT_EXIST; Account admin = getAdmin(); if (!groupRepository.adminExists(groupId, admin.getAddress())) return ValidationResult.NOT_GROUP_ADMIN; Account member = getMember(); if (!groupRepository.joinRequestExists(groupId, member.getAddress()) && !groupRepository.memberExists(groupId, member.getAddress())) return ValidationResult.NOT_GROUP_MEMBER; if (!admin.getAddress().equals(groupData.getOwner()) && groupRepository.adminExists(groupId, member.getAddress())) return ValidationResult.INVALID_GROUP_OWNER; if (groupKickTransactionData.getFee().compareTo(BigDecimal.ZERO) <= 0) return ValidationResult.NEGATIVE_FEE; if (admin.getConfirmedBalance(Asset.QORA).compareTo(groupKickTransactionData.getFee()) < 0) return ValidationResult.NO_BALANCE; return ValidationResult.OK; }
9,195
void setupEnding(WeaveContext context){ endingExpressionSymbols.add(iterableVariable); final LambdaBranch branch = new LambdaBranch(); branch.setCommandName(endingLambda.getName()); branch.setInputs(endingExpressionSymbols); branch.setOutputExpression(iterableVariable + " <= " + endingExpression); context.getLambdaHelper().getBranches().add(branch); endingLambda.captureAttribute("Parameters"); endingLambda.handleObject(() -> { endingLambda.captureAttribute(COMMAND_VAR); endingLambda.setProperty(endingLambda.getName()); endingExpressionSymbols.forEach(it -> { endingLambda.captureAttribute(it + ".$"); endingLambda.setProperty("$." + it); }); }); endingLambda.captureAttribute("Resource"); endingLambda.setProperty("@@@lambda_helper_arn@@@"); endingLambda.setResultPath("$." + choiceVar); endingLambda.setNextState(choice.getName()); }
void setupEnding(WeaveContext context){ endingExpressionSymbols.add(iterableVariable); constructLambda(context, endingLambda, iterableVariable + " <= " + endingExpression, endingExpressionSymbols); endingLambda.captureAttribute("Resource"); endingLambda.setProperty("@@@lambda_helper_arn@@@"); endingLambda.setResultPath("$." + choiceVar); endingLambda.setNextState(choice.getName()); }
9,196
public void closeEx(@NotNull Throwable e){ throw new AssertionError(); }
public void closeEx(@NotNull Throwable e){ }
9,197
public AboutToStartOrSubmitCallbackResponse handleAboutToStartEvent(@RequestBody CallbackRequest callbackrequest){ final String epo = "EMERGENCY_PROTECTION_ORDER"; final String showEpoFieldId = "EPO_REASONING_SHOW"; CaseDetails caseDetails = callbackrequest.getCaseDetails(); Map<String, Object> data = caseDetails.getData(); Optional<List<String>> orderType = Optional.ofNullable((Map<String, Object>) data.get("orders")).map(orders -> (List<String>) orders.get("orderType")); if (orderType.isPresent()) { orderType.ifPresent(orderTypes -> { if (orderTypes.contains(epo)) { data.put(showEpoFieldId, ImmutableList.of("SHOW_FIELD")); } else if (data.containsKey(showEpoFieldId)) { data.remove("groundsForEPO"); data.remove(showEpoFieldId); } }); } else { data.remove("groundsForEPO"); data.remove(showEpoFieldId); } return AboutToStartOrSubmitCallbackResponse.builder().data(data).build(); }
public AboutToStartOrSubmitCallbackResponse handleAboutToStartEvent(@RequestBody CallbackRequest callbackrequest){ final String showEpoFieldId = "EPO_REASONING_SHOW"; CaseDetails caseDetails = callbackrequest.getCaseDetails(); Map<String, Object> data = caseDetails.getData(); Optional<List<String>> orderType = Optional.ofNullable((Map<String, Object>) data.get("orders")).map(orders -> (List<String>) orders.get("orderType")); if (orderType.isPresent()) { orderType.ifPresent(orderTypes -> { if (orderTypes.contains(OrderType.EMERGENCY_PROTECTION_ORDER.name())) { data.put(showEpoFieldId, ImmutableList.of("SHOW_FIELD")); } else if (data.containsKey(showEpoFieldId)) { data.remove("groundsForEPO"); data.remove(showEpoFieldId); } }); } else { data.remove("groundsForEPO"); data.remove(showEpoFieldId); } return AboutToStartOrSubmitCallbackResponse.builder().data(data).build(); }
9,198
public Response updateThing(@ApiParam(value = "thing data", required = true) EnrichedThingDTO thingBean) throws IOException{ ThingUID thingUID = new ThingUID(thingBean.UID); ThingUID bridgeUID = null; if (thingBean.bridgeUID != null) { bridgeUID = new ThingUID(thingBean.bridgeUID); } Configuration configuration = new Configuration(thingBean.configuration); Thing thing = thingSetupManager.getThing(thingUID); if (thingBean.item != null && thing != null) { String label = thingBean.label; List<String> groupNames = thingBean.item.groupNames; @SuppressWarnings("deprecation") GroupItem thingGroupItem = thing.getLinkedItem(); if (thingGroupItem != null) { boolean labelChanged = false; if (thingGroupItem.getLabel() == null || !thingGroupItem.getLabel().equals(label)) { thingGroupItem.setLabel(label); labelChanged = true; } boolean groupsChanged = setGroupNames(thingGroupItem, groupNames); if (labelChanged || groupsChanged) { thingSetupManager.updateItem(thingGroupItem); } } } if (thing != null) { if (bridgeUID != null) { thing.setBridgeUID(bridgeUID); } ThingResource.updateConfiguration(thing, configuration); thingSetupManager.updateThing(thing); } return Response.ok().build(); }
public Response updateThing(@ApiParam(value = "thing data", required = true) EnrichedThingDTO thingBean) throws IOException{ ThingUID thingUID = new ThingUID(thingBean.UID); ThingUID bridgeUID = null; if (thingBean.bridgeUID != null) { bridgeUID = new ThingUID(thingBean.bridgeUID); } Configuration configuration = new Configuration(thingBean.configuration); Thing thing = thingSetupManager.getThing(thingUID); if (thing != null) { String label = thingBean.label; @SuppressWarnings("deprecation") GroupItem thingGroupItem = thing.getLinkedItem(); if (thingGroupItem != null) { boolean labelChanged = false; if (thingGroupItem.getLabel() == null || !thingGroupItem.getLabel().equals(label)) { thingGroupItem.setLabel(label); labelChanged = true; } boolean groupsChanged = setGroupNames(thingGroupItem, new ArrayList<String>()); if (labelChanged || groupsChanged) { thingSetupManager.updateItem(thingGroupItem); } } } if (thing != null) { if (bridgeUID != null) { thing.setBridgeUID(bridgeUID); } ThingResource.updateConfiguration(thing, configuration); thingSetupManager.updateThing(thing); } return Response.ok().build(); }
9,199
public void testCustomRole() throws Throwable{ CustomRole customRoleModel = new CustomRole(); assertNull(customRoleModel.getId()); assertNull(customRoleModel.getName()); assertNull(customRoleModel.getAccountId()); assertNull(customRoleModel.getServiceName()); assertNull(customRoleModel.getDisplayName()); assertNull(customRoleModel.getDescription()); assertNull(customRoleModel.getActions()); assertNull(customRoleModel.getCreatedAt()); assertNull(customRoleModel.getCreatedById()); assertNull(customRoleModel.getLastModifiedAt()); assertNull(customRoleModel.getLastModifiedById()); assertNull(customRoleModel.getHref()); }
public void testCustomRole() throws Throwable{ CustomRole customRoleModel = new CustomRole(); assertNull(customRoleModel.getDisplayName()); assertNull(customRoleModel.getDescription()); assertNull(customRoleModel.getActions()); assertNull(customRoleModel.getName()); assertNull(customRoleModel.getAccountId()); assertNull(customRoleModel.getServiceName()); }