Unnamed: 0
int64
0
9.45k
cwe_id
stringclasses
1 value
source
stringlengths
37
2.53k
target
stringlengths
19
2.4k
0
public boolean save(SystemUser systemUser){ Users user = systemUser.getId() != null ? userRepository.findById(systemUser.getId()).orElse(new Users()) : new Users(); user.setNumberPhone(systemUser.getNumberPhone()); if (systemUser.getId() == null || (systemUser.getPassword() != null && !systemUser.getPassword().trim().isEmpty())) { user.setPassword(passwordEncoder.encode(systemUser.getPassword())); } user.setFirstUserName(systemUser.getFirstUserName()); user.setLastUserName(systemUser.getLastUserName()); user.setEmail(systemUser.getEmail()); if (systemUser.getGender() == null) { user.setGender(genderRepository.findOneByNameGender("Man")); } else { user.setGender(systemUser.getGender()); } if (systemUser.getRoles() == null) { user.setRoles(new HashSet<>(Collections.singletonList(roleRepository.findOneByNameRole("ROLE_CLIENT")))); } else { user.setRoles(systemUser.getRoles()); } userRepository.save(user); return true; }
public void save(SystemUser systemUser){ Users user = systemUser.getId() != null ? userRepository.findById(systemUser.getId()).orElse(new Users()) : new Users(); user.setNumberPhone(systemUser.getNumberPhone()); if (systemUser.getId() == null || (systemUser.getPassword() != null && !systemUser.getPassword().trim().isEmpty())) { user.setPassword(passwordEncoder.encode(systemUser.getPassword())); } user.setFirstUserName(systemUser.getFirstUserName()); user.setLastUserName(systemUser.getLastUserName()); user.setEmail(systemUser.getEmail()); if (systemUser.getGender() == null) { user.setGender(genderRepository.findOneByNameGender("Man")); } else { user.setGender(systemUser.getGender()); } if (systemUser.getRoles() == null) { user.setRoles(new HashSet<>(Collections.singletonList(roleRepository.findOneByNameRole("ROLE_CLIENT")))); } else { user.setRoles(systemUser.getRoles()); } userRepository.save(user); }
1
public Location getLocation(){ final Location center = new Location(0, 0); markers.forEach(marker -> { center.add(marker.getLocation()); }); center.div((float) markers.size()); return center; }
public Location getLocation(){ final Location center = new Location(0, 0); markers.forEach(marker -> center.add(marker.getLocation())); center.div((float) markers.size()); return center; }
2
public URI getUri(){ try { return new URI(request.getRequestURI()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
public URI getUri(){ return URI.create(request.getRequestURI()); }
3
private static boolean isActivityShowing(Context context){ SharedPreferences preferences = context.getSharedPreferences(Verloop.SHARED_PREFERENCE_FILE_NAME, Context.MODE_PRIVATE); return preferences.getBoolean(Verloop.IS_SHOWN, false); }
private static boolean isActivityShowing(Context context){ return true; }
4
private R decodeRawResultSet(ResultSet rs) throws SQLException{ BiConsumer<C, Row> accumulator = collector.accumulator(); List<String> columnNames = new ArrayList<>(); RowDesc desc = new RowDesc(columnNames); C container = collector.supplier().get(); ResultSetMetaData metaData = rs.getMetaData(); int cols = metaData.getColumnCount(); for (int i = 1; i <= cols; i++) { columnNames.add(metaData.getColumnLabel(i)); } while (rs.next()) { Row row = new JDBCRow(desc); for (int i = 1; i <= cols; i++) { Object res = convertSqlValue(rs, i); row.addValue(res); } accumulator.accept(container, row); } return collector.finisher().apply(container); }
private R decodeRawResultSet(ResultSet rs) throws SQLException{ BiConsumer<C, Row> accumulator = collector.accumulator(); List<String> columnNames = new ArrayList<>(); RowDesc desc = new RowDesc(columnNames); C container = collector.supplier().get(); ResultSetMetaData metaData = rs.getMetaData(); int cols = metaData.getColumnCount(); for (int i = 1; i <= cols; i++) { columnNames.add(metaData.getColumnLabel(i)); } while (rs.next()) { Row row = new JDBCRow(desc); for (int i = 1; i <= cols; i++) { row.addValue(helper.getDecoder().parse(metaData, i, rs)); } accumulator.accept(container, row); } return collector.finisher().apply(container); }
5
public boolean update(Context context, KvPairs pairs, AnyKey anyKey){ LOGGER.trace("update: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ") + anyKey.getAny().toString()); String table = anyKey.getKey().getTable(); if (table == null) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug("update kvSave failed: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); return false; } else { LOGGER.debug("updated kvSave Ok: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); } } else { Query query = new Query(context, jdbcTemplate, pairs, anyKey); if (!query.prepareUpdate() || !query.executeUpdate()) { if (enableDbFallback) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug("update fallback to kvSave failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); return false; } else { String msg = "updated fallbacked to kvSave OK: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "); context.logTraceMessage(msg); LOGGER.warn(msg); } } else { LOGGER.debug("update failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); return false; } } else { LOGGER.debug("updated Ok: " + anyKey.size() + " record(s) from " + table); } } AppCtx.getKeyInfoRepo().save(context, pairs, anyKey); return true; }
public boolean update(Context context, KvPairs pairs, AnyKey anyKey){ LOGGER.trace("update: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ") + anyKey.getAny().toString()); String table = anyKey.getKey().getTable(); if (table == null) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug("update kvSave failed: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); return false; } else { LOGGER.debug("updated kvSave Ok: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); } } else { Query query = new Query(context, jdbcTemplate, pairs, anyKey); if (!query.ifUpdateOk() || !query.executeUpdate()) { if (enableDbFallback) { if (!kvSave(context, pairs, anyKey)) { LOGGER.debug("update fallback to kvSave failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); return false; } else { String msg = "updated fallbacked to kvSave OK: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "); context.logTraceMessage(msg); LOGGER.warn(msg); } } else { LOGGER.debug("update failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ")); return false; } } else { LOGGER.debug("updated Ok: " + anyKey.size() + " record(s) from " + table); } } return true; }
6
protected static boolean hasErrThree(String folder_, String relative_, String html_, String htmlTwo_, String htmlThree_, StringMap<String> filesSec_){ Configuration conf_ = EquallableExUtil.newConfiguration(); conf_.setPrefix("c:"); AnalyzedTestConfiguration a_ = build(conf_); setStack(a_); getHeaders(filesSec_, a_); assertTrue(isEmptyErrors(a_)); setup(folder_, relative_, conf_); newBeanInfo(a_, "pkg.BeanOne", "bean_one"); newBeanInfo(a_, "pkg.BeanTwo", "bean_two"); newBeanInfo(a_, "pkg.BeanThree", "bean_three"); analyzeInner(conf_, a_, html_, htmlTwo_, htmlThree_); buildExecPart(a_, "bean_one"); buildExecPart(a_, "bean_two"); buildExecPart(a_, "bean_three"); return !isEmptyErrors(a_); }
protected static boolean hasErrThree(String folder_, String relative_, String html_, String htmlTwo_, String htmlThree_, StringMap<String> filesSec_){ Configuration conf_ = EquallableExUtil.newConfiguration(); conf_.setPrefix("c:"); AnalyzedTestConfiguration a_ = build(conf_); getHeaders(filesSec_, a_); assertTrue(isEmptyErrors(a_)); setup(folder_, relative_, conf_); newBeanInfo(a_, "pkg.BeanOne", "bean_one"); newBeanInfo(a_, "pkg.BeanTwo", "bean_two"); newBeanInfo(a_, "pkg.BeanThree", "bean_three"); analyzeInner(conf_, a_, html_, htmlTwo_, htmlThree_); buildExecPart(a_, "bean_one"); buildExecPart(a_, "bean_two"); buildExecPart(a_, "bean_three"); return !isEmptyErrors(a_); }
7
public void process(JsonObject resultObject, RequestError requestError){ if (resultObject != null) { try { List<SourceEdit> edits = SourceEdit.fromJsonArray(resultObject.get("edits").getAsJsonArray()); int selectionOffset = resultObject.get("selectionOffset").getAsInt(); int selectionLength = resultObject.get("selectionLength").getAsInt(); consumer.computedFormat(edits, selectionOffset, selectionLength); } catch (Exception exception) { String message = exception.getMessage(); String stackTrace = null; if (exception.getStackTrace() != null) { stackTrace = ExceptionUtils.getStackTrace(exception); } requestError = new RequestError(ExtendedRequestErrorCode.INVALID_SERVER_RESPONSE, message != null ? message : "", stackTrace); } } if (requestError != null) { consumer.onError(requestError); } }
public void process(JsonObject resultObject, RequestError requestError){ if (resultObject != null) { try { List<SourceEdit> edits = SourceEdit.fromJsonArray(resultObject.get("edits").getAsJsonArray()); int selectionOffset = resultObject.get("selectionOffset").getAsInt(); int selectionLength = resultObject.get("selectionLength").getAsInt(); consumer.computedFormat(edits, selectionOffset, selectionLength); } catch (Exception exception) { requestError = generateRequestError(exception); } } if (requestError != null) { consumer.onError(requestError); } }
8
protected void processOptions(Widget widget, ObjectNode schema){ Map<String, String> optionsMap = UiSchemaConstants.getWidgetOptionsMapping().get(widget.getWidgetType()); if (optionsMap != null) { ObjectNode options = JsonNodeFactory.instance.objectNode(); for (Map.Entry<String, String> entry : optionsMap.entrySet()) { options.put(entry.getKey(), entry.getValue()); } schema.set(UiSchemaConstants.TAG_OPTIONS, options); } if (widget.getWidgetCode() != null) { ObjectNode options = JsonNodeFactory.instance.objectNode(); options.put("language", widget.getWidgetCode().name()); schema.set(UiSchemaConstants.TAG_OPTIONS, options); } }
protected void processOptions(Widget widget, ObjectNode schema){ Map<String, String> optionsMap = UiSchemaConstants.getWidgetOptionsMapping().get(widget.getWidgetType()); if (optionsMap != null) { ObjectNode options = JsonNodeFactory.instance.objectNode(); for (Map.Entry<String, String> entry : optionsMap.entrySet()) { if (widget.getConfigurationValue(entry.getKey()) != null) { options.put(entry.getKey(), widget.getConfigurationValue(entry.getKey()).toString()); } else { options.put(entry.getKey(), entry.getValue()); } } schema.set(UiSchemaConstants.TAG_OPTIONS, options); } }
9
protected void onStart(){ super.onStart(); Lists list = new Lists("Šoping lista test1", "grey", "22.06.2018 - 13:00"); Lists list2 = new Lists("Šoping lista test2", "green", "22.06.2018 - 14:00"); Lists list3 = new Lists("Šoping lista test3", "blue", "22.06.2018 - 15:00"); Lists list4 = new Lists("Šoping lista test4", "red", "22.06.2018 - 16:00"); lists.add(list); lists.add(list2); lists.add(list3); lists.add(list4); ListsAdapter listAdapter = new ListsAdapter(mContext, lists); mRecyclerView.setAdapter(listAdapter); mFAB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!mIsNewsListVisible) { mIsNewsListVisible = true; FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); newListFragment = new NewListFragment(); fragmentTransaction.add(R.id.fragment_container, newListFragment); fragmentTransaction.commit(); mFAB.setVisibility(View.GONE); } } }); }
protected void onStart(){ super.onStart(); ListModel list = new ListModel("Šoping lista test1", "grey", "22.06.2018 - 13:00"); ListModel list2 = new ListModel("Šoping lista test2", "green", "22.06.2018 - 14:00"); ListModel list3 = new ListModel("Šoping lista test3", "blue", "22.06.2018 - 15:00"); ListModel list4 = new ListModel("Šoping lista test4", "red", "22.06.2018 - 16:00"); lists.add(list); lists.add(list2); lists.add(list3); lists.add(list4); ListsAdapter listAdapter = new ListsAdapter(mContext, lists); mRecyclerView.setAdapter(listAdapter); }
10
public void removeLink(String uid, InetSocketAddress outLinkAddress){ this.inLinkClientUidToMinimaAddress.remove(uid); this.inLinks.remove(outLinkAddress); this.outLinks.remove(outLinkAddress); this.clientLinks.remove(outLinkAddress); log.debug(this.genPrintableState()); }
public void removeLink(InetSocketAddress outLinkAddress){ this.inLinks.remove(outLinkAddress); this.outLinks.remove(outLinkAddress); this.clientLinks.remove(outLinkAddress); log.debug(this.genPrintableState()); }
11
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View fragmentLayout = inflater.inflate(R.layout.fragment_movie_detail, container, false); ButterKnife.bind(this, fragmentLayout); movie = getMovie(); putMovieDataIntoViews(); Log.d(TAG, "onCreateView: " + movie.getBackdropPath()); return fragmentLayout; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View fragmentLayout = inflater.inflate(R.layout.fragment_movie_detail, container, false); ButterKnife.bind(this, fragmentLayout); movie = getMovie(); putMovieDataIntoViews(); return fragmentLayout; }
12
public Map<String, Object> queryProjectCreatedByUser(User loginUser){ Map<String, Object> result = new HashMap<>(); if (isNotAdmin(loginUser, result)) { return result; } List<Project> projects = projectMapper.queryProjectCreatedByUser(loginUser.getId()); result.put(Constants.DATA_LIST, projects); putMsg(result, Status.SUCCESS); return result; }
public Result<List<Project>> queryProjectCreatedByUser(User loginUser){ if (isNotAdmin(loginUser)) { return Result.error(Status.USER_NO_OPERATION_PERM); } List<Project> projects = projectMapper.queryProjectCreatedByUser(loginUser.getId()); return Result.success(projects); }
13
public Parameters.Fhir subsumes(@ApiParam(value = "The id of the code system to invoke the operation on") @PathVariable("codeSystemId") String codeSystemId, @ApiParam(name = "body", value = "The lookup request parameters") @RequestBody Parameters.Fhir in){ SubsumptionRequest request = toRequest(in, SubsumptionRequest.class); validateSubsumptionRequest(request); SubsumptionResult result = codeSystemProviderRegistry.getCodeSystemProvider(getBus(), locales, request.getSystem()).subsumes(request); return toResponse(result); }
public Promise<Parameters.Fhir> subsumes(@ApiParam(value = "The id of the code system to invoke the operation on") @PathVariable("codeSystemId") String codeSystemId, @ApiParam(name = "body", value = "The lookup request parameters") @RequestBody Parameters.Fhir in){ SubsumptionRequest request = toRequest(in, SubsumptionRequest.class); validateSubsumptionRequest(request); return FhirRequests.codeSystems().prepareSubsumes().setRequest(request).buildAsync().execute(getBus()).then(this::toResponse); }
14
public int onStartCommand(Intent intent, int flags, int startId){ if (mHandler == null) { mHandler = new Handler(this); } if (mThread != null) { mThread.interrupt(); } if (mInterface != null) { try { mInterface.close(); } catch (IOException e) { e.printStackTrace(); } } if (mEncrypter == null) { mEncrypter = new Encryptor(); } mThread = new Thread(this); mThread.start(); return START_STICKY; }
public int onStartCommand(Intent intent, int flags, int startId){ if (mHandler == null) { mHandler = new Handler(this); } if (mThread != null) { mThread.interrupt(); } if (mInterface != null) { try { mInterface.close(); } catch (IOException e) { e.printStackTrace(); } } mThread = new Thread(this); mThread.start(); return START_STICKY; }
15
public void testMissingLowerCorner() throws CswException{ HierarchicalStreamReader reader = mock(HierarchicalStreamReader.class); Stack<String> boundingBoxNodes = new Stack<String>(); boundingBoxNodes.push("-2.228 51.126"); boundingBoxNodes.push("UpperCorner"); boundingBoxNodes.push("-6.171 44.792"); boundingBoxNodes.push("MISSING LOWER CORNER"); boundingBoxNodes.push("BoundingBox"); boundingBoxNodes.push("BoundingBox"); Answer<String> answer = new Answer<String>() { @Override public String answer(InvocationOnMock invocationOnMock) throws Throwable { return boundingBoxNodes.pop(); } }; when(reader.getNodeName()).thenAnswer(answer); when(reader.getValue()).thenAnswer(answer); BoundingBoxReader boundingBoxReader = new BoundingBoxReader(reader, CswAxisOrder.LON_LAT); boundingBoxReader.getWkt(); }
public void testMissingLowerCorner() throws CswException{ HierarchicalStreamReader reader = mock(HierarchicalStreamReader.class); Stack<String> boundingBoxNodes = new Stack<>(); boundingBoxNodes.push("-2.228 51.126"); boundingBoxNodes.push("UpperCorner"); boundingBoxNodes.push("-6.171 44.792"); boundingBoxNodes.push("MISSING LOWER CORNER"); boundingBoxNodes.push("BoundingBox"); boundingBoxNodes.push("BoundingBox"); Answer<String> answer = invocationOnMock -> boundingBoxNodes.pop(); when(reader.getNodeName()).thenAnswer(answer); when(reader.getValue()).thenAnswer(answer); BoundingBoxReader boundingBoxReader = new BoundingBoxReader(reader, CswAxisOrder.LON_LAT); boundingBoxReader.getWkt(); }
16
private static List<MRelation> retrieve(final Properties ctx, final I_AD_RelationType type, final int recordId, final boolean normalDirection, final String trxName){ final StringBuilder wc = new StringBuilder(); wc.append(COLUMNNAME_AD_RelationType_ID + "=? AND "); if (normalDirection) { wc.append(COLUMNNAME_Record_Source_ID + "=?"); } else { wc.append(COLUMNNAME_Record_Target_ID + "=?"); } return new Query(ctx, Table_Name, wc.toString(), trxName).setParameters(type.getAD_RelationType_ID(), recordId).setOnlyActiveRecords(true).setClient_ID().setOrderBy(COLUMNNAME_SeqNo).list(); }
private static List<I_AD_Relation> retrieve(final Properties ctx, final I_AD_RelationType type, final int recordId, final boolean normalDirection, final String trxName){ final IQueryBuilder<I_AD_Relation> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_AD_Relation.class, ctx, trxName).addOnlyActiveRecordsFilter().addOnlyContextClient().addEqualsFilter(I_AD_Relation.COLUMNNAME_AD_RelationType_ID, type.getAD_RelationType_ID()).orderBy().addColumn(I_AD_Relation.COLUMNNAME_SeqNo).endOrderBy(); if (normalDirection) { queryBuilder.addEqualsFilter(I_AD_Relation.COLUMNNAME_Record_Source_ID, recordId); } else { queryBuilder.addEqualsFilter(I_AD_Relation.COLUMNNAME_Record_Target_ID, recordId); } return queryBuilder.create().list(I_AD_Relation.class); }
17
public void remove(SwitchId datapath){ log.info("Switch service receive remove request for {}", datapath); SwitchFsm fsm = controller.get(datapath); if (fsm == null) { log.info("Got DELETE request for not existing switch {}", datapath); return; } SwitchFsmContext context = SwitchFsmContext.builder(carrier).build(); controllerExecutor.fire(fsm, SwitchFsmEvent.SWITCH_REMOVE, context); if (fsm.isTerminated()) { controller.remove(datapath); log.debug("Switch service removed FSM {}", datapath); logWrapper.onSwitchDelete(datapath); } else { log.error("Switch service remove failed for FSM {}, state: {}", datapath, fsm.getCurrentState()); } }
public void remove(SwitchId datapath){ log.info("Switch service receive remove request for {}", datapath); SwitchFsm fsm = controller.get(datapath); if (fsm == null) { log.info("Got DELETE request for not existing switch {}", datapath); return; } SwitchFsmContext context = SwitchFsmContext.builder(carrier).build(); controllerExecutor.fire(fsm, SwitchFsmEvent.SWITCH_REMOVE, context); if (fsm.isTerminated()) { controller.remove(datapath); log.debug("Switch service removed FSM {}", datapath); } else { log.error("Switch service remove failed for FSM {}, state: {}", datapath, fsm.getCurrentState()); } }
18
private void parseIntentExtras(Bundle extras){ call_direction_type = (Consts.CALL_DIRECTION_TYPE) extras.getSerializable(Consts.CALL_DIRECTION_TYPE_EXTRAS); currentSession = SessionManager.getCurrentSession(); call_type = (QBRTCTypes.QBConferenceType) extras.getSerializable(Consts.CALL_TYPE_EXTRAS); opponentsList = (List<Integer>) extras.getSerializable(Consts.OPPONENTS_LIST_EXTRAS); userInfo = (Map<String, String>) extras.getSerializable(Consts.USER_INFO_EXTRAS); }
private void parseIntentExtras(Bundle extras){ call_direction_type = (Consts.CALL_DIRECTION_TYPE) extras.getSerializable(Consts.CALL_DIRECTION_TYPE_EXTRAS); call_type = (QBRTCTypes.QBConferenceType) extras.getSerializable(Consts.CALL_TYPE_EXTRAS); opponentsList = (List<Integer>) extras.getSerializable(Consts.OPPONENTS_LIST_EXTRAS); userInfo = (Map<String, String>) extras.getSerializable(Consts.USER_INFO_EXTRAS); }
19
public void shouldHandleValidAQR(){ when(validator.validate(eq(ATTRIBUTE_QUERY), any(Messages.class))).thenReturn(messages()); when(transformer.apply(request)).thenReturn(matchingServiceRequestDto); when(matchingServiceClient.makeMatchingServiceRequest(matchingServiceRequestDto)).thenReturn(matchingServiceResponseDto); when(matchingServiceRequestDto.getHashedPid()).thenReturn(PID); when(responseMapper.map(matchingServiceResponseDto, PID, request.getAttributeQuery().getID(), request.getAttributeQuery().getSubject().getNameID().getNameQualifier(), AuthnContext.LEVEL_2, request.getAttributeQuery().getSubject().getNameID().getSPNameQualifier())).thenReturn(outboundResponseFromMatchingService); VerifyMatchingServiceResponse response = (VerifyMatchingServiceResponse) service.handle(request); verify(validator).validate(eq(ATTRIBUTE_QUERY), any(Messages.class)); verify(transformer).apply(request); verify(matchingServiceClient).makeMatchingServiceRequest(matchingServiceRequestDto); verify(responseMapper).map(matchingServiceResponseDto, PID, request.getAttributeQuery().getID(), request.getAttributeQuery().getSubject().getNameID().getNameQualifier(), AuthnContext.LEVEL_2, request.getAttributeQuery().getSubject().getNameID().getSPNameQualifier()); assertThat(response.getOutboundResponseFromMatchingService()).isEqualTo(outboundResponseFromMatchingService); verifyNoMoreInteractions(validator, transformer, matchingServiceClient); }
public void shouldHandleValidAQR(){ MatchingServiceRequestDto matchingServiceRequestDto = MatchingServiceRequestDtoBuilder.aMatchingServiceRequestDto().withHashedPid(PID).build(); MatchingServiceResponseDto matchingServiceResponseDto = MatchingServiceResponseDtoBuilder.aMatchingServiceResponseDto().build(); when(validator.validate(eq(ATTRIBUTE_QUERY), any(Messages.class))).thenReturn(messages()); when(transformer.apply(request)).thenReturn(matchingServiceRequestDto); when(matchingServiceClient.makeMatchingServiceRequest(matchingServiceRequestDto)).thenReturn(matchingServiceResponseDto); when(responseMapper.map(matchingServiceResponseDto, PID, request.getAttributeQuery().getID(), request.getAttributeQuery().getSubject().getNameID().getNameQualifier(), AuthnContext.LEVEL_2, request.getAttributeQuery().getSubject().getNameID().getSPNameQualifier())).thenReturn(outboundResponseFromMatchingService); VerifyMatchingServiceResponse response = (VerifyMatchingServiceResponse) service.handle(request); assertThat(response.getOutboundResponseFromMatchingService()).isEqualTo(outboundResponseFromMatchingService); }
20
public Result generateToken(@RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "userId") int userId, @RequestParam(value = "expireTime") String expireTime){ logger.info("login user {}, generate token , userId : {} , token expire time : {}", loginUser, userId, expireTime); Map<String, Object> result = accessTokenService.generateToken(loginUser, userId, expireTime); return returnDataList(result); }
public Result<String> generateToken(@RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "userId") int userId, @RequestParam(value = "expireTime") String expireTime){ logger.info("login user {}, generate token , userId : {} , token expire time : {}", loginUser, userId, expireTime); return accessTokenService.generateToken(loginUser, userId, expireTime); }
21
public boolean getLoggingSwitch(){ try { ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); boolean b = appInfo.metaData.getBoolean("LOGGING"); return b; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return false; }
public boolean getLoggingSwitch(){ try { ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA); return appInfo.metaData.getBoolean("LOGGING"); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return false; }
22
public Result execute(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @ApiParam(name = "projectName", value = "PROJECT_NAME", required = true) @PathVariable String projectName, @RequestParam("processInstanceId") Integer processInstanceId, @RequestParam("executeType") ExecuteType executeType){ logger.info("execute command, login user: {}, project:{}, process instance id:{}, execute type:{}", loginUser.getUserName(), projectName, processInstanceId, executeType); Map<String, Object> result = execService.execute(loginUser, projectName, processInstanceId, executeType); return returnDataList(result); }
public Result<Void> execute(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @ApiParam(name = "projectName", value = "PROJECT_NAME", required = true) @PathVariable String projectName, @RequestParam("processInstanceId") Integer processInstanceId, @RequestParam("executeType") ExecuteType executeType){ logger.info("execute command, login user: {}, project:{}, process instance id:{}, execute type:{}", loginUser.getUserName(), projectName, processInstanceId, executeType); return execService.execute(loginUser, projectName, processInstanceId, executeType); }
23
public Object eval(Bindings bindings, ELContext context){ try { evalResult = super.eval(bindings, context); hasEvalResult = true; return evalResult; } catch (DeferredParsingException e) { throw new DeferredParsingException(this, getPartiallyResolved(bindings, context, e, false)); } }
public Object eval(Bindings bindings, ELContext context){ return EvalResultHolder.super.eval(() -> super.eval(bindings, context), bindings, context); }
24
private void loadData(){ Log.e("ScreenRUn", "Load!1"); makeJsonObjectRequestPostHome(0, loadLimit); }
private void loadData(){ makeJsonObjectRequestPostHome(0, loadLimit); }
25
public Vector<String> toGo(){ return new Vector<String>() { { add("goto " + to); } }; }
public List<String> toGo(){ return Collections.singletonList("goto " + to); }
26
private static VarRef populateFieldAccess(JCVariableDecl rootVar, JavacResolution javacResolution, JavacNode annotationNode, int level, Type type, JCFieldAccess fa, boolean isMeth, List<JCExpression> args, ListBuffer<JCStatement> statements) throws TypeNotConvertibleException, SafeCallUnexpectedStateException, SafeCallInternalException, SafeCallIllegalUsingException{ Name templateName = rootVar.name; JavacTreeMaker treeMaker = annotationNode.getTreeMaker(); JCExpression selected = fa.selected; VarRef varRef = populateInitStatements(level + 1, rootVar, selected, statements, annotationNode, javacResolution); JCExpression variableExpr; if (varRef.var != null) { Name childName = varRef.getVarName(); JCFieldAccess newFa = newSelect(treeMaker, fa, childName); newFa.type = annotationNode.getSymbolTable().objectType; JCExpression newExpr = isMeth ? args != null ? treeMaker.App(newFa, args) : treeMaker.App(newFa) : newFa; newExpr.pos = newFa.pos; variableExpr = newElvis(treeMaker, annotationNode.getAst(), newExpr, type); } else if (isMeth) { fa.type = type; variableExpr = args != null ? treeMaker.App(fa, args) : treeMaker.App(fa); variableExpr.pos = fa.pos; } else variableExpr = fa; int verifyLevel = level; Name newName = newVarName(templateName, verifyLevel, annotationNode); JCVariableDecl variableDecl = makeVariableDecl(treeMaker, statements, newName, type, variableExpr); int maxLevel = varRef.level > verifyLevel ? varRef.level : verifyLevel; return new VarRef(variableDecl, maxLevel); }
private static VarRef populateFieldAccess(JCVariableDecl rootVar, JavacResolution javacResolution, JavacNode annotationNode, int fieldVarLevel, int lastLevel, Type type, JCFieldAccess fa, boolean isMeth, List<JCExpression> args, ListBuffer<JCStatement> statements) throws TypeNotConvertibleException, SafeCallUnexpectedStateException, SafeCallInternalException, SafeCallIllegalUsingException{ Name templateName = rootVar.name; JavacTreeMaker treeMaker = annotationNode.getTreeMaker(); JCExpression selected = fa.selected; VarRef varRef = populateInitStatements(lastLevel + 1, rootVar, selected, statements, annotationNode, javacResolution); JCExpression variableExpr; if (varRef.var != null) { Name childName = varRef.getVarName(); JCFieldAccess newFa = newSelect(treeMaker, fa, childName); newFa.type = annotationNode.getSymbolTable().objectType; JCExpression newExpr = isMeth ? args != null ? treeMaker.App(newFa, args) : treeMaker.App(newFa) : newFa; newExpr.pos = newFa.pos; variableExpr = newElvis(treeMaker, annotationNode.getAst(), newExpr, type); } else if (isMeth) { fa.type = type; variableExpr = args != null ? treeMaker.App(fa, args) : treeMaker.App(fa); variableExpr.pos = fa.pos; } else variableExpr = fa; Name newName = newVarName(templateName, fieldVarLevel, annotationNode); JCVariableDecl variableDecl = makeVariableDecl(treeMaker, statements, newName, type, variableExpr); int maxLevel = varRef.level > fieldVarLevel ? varRef.level : fieldVarLevel; return new VarRef(variableDecl, maxLevel); }
27
private StatisticsResponse createFakeStatistics(){ StatisticsModel modelCourse = new StatisticsModel(0, 0, 0, 0, 0, 0, 0, 0); StatisticsModel modelLevel = new StatisticsModel(0, 0, 0, 0, 0, 0, 0, 0); StatisticsResponse statistics = new StatisticsResponse(modelCourse, modelLevel); return statistics; }
private StatisticsResponse createFakeStatistics(){ StatisticsModel modelCourse = new StatisticsModel(); StatisticsResponse statistics = new StatisticsResponse(modelCourse); return statistics; }
28
public void buildCodec(Channel channel, ConnectionImpl connection){ ChannelPipeline pipeline = channel.pipeline(); PacketDecoder decoder = new PacketDecoder(connection); PacketEncoder encoder = new PacketEncoder(connection); pipeline.addAfter(ChannelHandlers.RAW_CAPTURE_RECEIVE, ChannelHandlers.DECODER_TRANSFORMER, decoder); pipeline.addAfter(ChannelHandlers.RAW_CAPTURE_SEND, ChannelHandlers.ENCODER_TRANSFORMER, encoder); connection.initCodec(PacketCodec.instance, encoder, decoder); }
public void buildCodec(Channel channel, ConnectionImpl connection){ connection.initCodec(PacketCodec.instance); channel.pipeline().addAfter(ChannelHandlers.RAW_CAPTURE_RECEIVE, ChannelHandlers.DECODER_TRANSFORMER, new PacketDecoder(connection)).addAfter(ChannelHandlers.RAW_CAPTURE_SEND, ChannelHandlers.ENCODER_TRANSFORMER, new PacketEncoder(connection)); }
29
public String trackSubdivision(Model model, HttpSession session, @PathVariable("subdivision.id") Long subdivisionId){ List<Buttons> buttons = buttonsService.getAllWhereParentIdIsNull(new Sort(Sort.Direction.ASC, "id")); model.addAttribute("buttons", buttons); List<Buttons> button = buttonsService.getAllWhereParentIdIsNotNull(); model.addAttribute("button", button); Long currUserId = (Long) session.getAttribute("currUserId"); User user = userService.getById(currUserId); model.addAttribute("userLogo", user.getName()); model.addAttribute("h1name", "Відділ - " + subdivisionService.getById(subdivisionId).getName()); model.addAttribute("subdivision", subdivisionService.getById(subdivisionId)); return "/subdivision/track"; }
public String trackSubdivision(Model model, HttpSession session, @PathVariable("subdivision.id") Long subdivisionId){ List<Buttons> buttons = buttonsService.getAllWhereParentIdIsNull(new Sort(Sort.Direction.ASC, "id")); model.addAttribute("buttons", buttons); List<Buttons> button = buttonsService.getAllWhereParentIdIsNotNull(); model.addAttribute("button", button); model.addAttribute("h1name", "Відділ - " + subdivisionService.getById(subdivisionId).getName()); model.addAttribute("subdivision", subdivisionService.getById(subdivisionId)); return "/subdivision/track"; }
30
public View getPrototypeView(Context context){ View prototypeView = super.getPrototypeView(context); Spinner variableSpinner = (Spinner) prototypeView.findViewById(R.id.change_variable_spinner); DataAdapter dataAdapter = ProjectManager.getInstance().getCurrentlyEditedScene().getDataContainer().createDataAdapter(context, ProjectManager.getInstance().getCurrentSprite()); UserVariableAdapterWrapper userVariableAdapterWrapper = new UserVariableAdapterWrapper(context, dataAdapter); userVariableAdapterWrapper.setItemLayout(android.R.layout.simple_spinner_item, android.R.id.text1); variableSpinner.setAdapter(userVariableAdapterWrapper); setSpinnerSelection(variableSpinner, null); TextView textChangeVariable = (TextView) prototypeView.findViewById(R.id.brick_change_variable_edit_text); textChangeVariable.setText(formatNumberForPrototypeView(BrickValues.CHANGE_VARIABLE)); return prototypeView; }
public View getPrototypeView(Context context){ View prototypeView = super.getPrototypeView(context); Spinner variableSpinner = prototypeView.findViewById(R.id.change_variable_spinner); DataAdapter dataAdapter = ProjectManager.getInstance().getCurrentlyEditedScene().getDataContainer().createDataAdapter(context, ProjectManager.getInstance().getCurrentSprite()); UserVariableAdapterWrapper userVariableAdapterWrapper = new UserVariableAdapterWrapper(context, dataAdapter); userVariableAdapterWrapper.setItemLayout(android.R.layout.simple_spinner_item, android.R.id.text1); variableSpinner.setAdapter(userVariableAdapterWrapper); setSpinnerSelection(variableSpinner, null); return prototypeView; }
31
public OptionalInt getTotal(final Job<?, ?> job){ Predicate<JobAction> predicate; if (selectTools) { predicate = action -> StringContainsUtils.containsAnyIgnoreCase(action.getId(), getIds()); } else { predicate = action -> true; } return job.getActions(JobAction.class).stream().filter(predicate).map(JobAction::getLatestAction).filter(Optional::isPresent).map(Optional::get).map(ResultAction::getResult).mapToInt(AnalysisResult::getTotalSize).reduce(Integer::sum); }
public OptionalInt getTotal(final Job<?, ?> job){ return job.getActions(JobAction.class).stream().filter(createToolFilter(selectTools, tools)).map(JobAction::getLatestAction).filter(Optional::isPresent).map(Optional::get).map(ResultAction::getResult).mapToInt(AnalysisResult::getTotalSize).reduce(Integer::sum); }
32
public void ending(Graphics g){ int tempY = y; int index = -1; if (!musicPlayed) { music.setSong(99); music.play(); musicPlayed = true; } if (!recorded) recordPosition(g); try { Thread.sleep(7); } catch (InterruptedException e) { System.out.println(e); } for (String text : texts) { tempY += Line; index++; if (tempY < -Line || tempY > finalY + Line) continue; if (text != "" && text.charAt(0) == '-') { g.setFont(titleFont); } else { g.setFont(font); } g.drawString(text, posRecord[index], tempY); } if (y + Line * texts.length > 0) y -= 1; else fadeIn(g); }
public void ending(Graphics g){ int tempY = y; int index = -1; if (!musicPlayed) { music.setSong(99); music.play(); musicPlayed = true; } if (!recorded) recordPosition(g); try { Thread.sleep(7); } catch (InterruptedException e) { System.out.println(e); } for (String text : texts) { tempY += Line; index++; if (tempY < -Line || tempY > finalY + Line) continue; if (text != "" && text.charAt(0) == '-') g.setFont(titleFont); else g.setFont(font); g.drawString(text, posRecord[index], tempY); } if (y + Line * texts.length > 0) y -= 1; else fadeIn(g); }
33
private Response handleError(String chargeId, GatewayError error){ switch(error.getErrorType()) { case UNEXPECTED_HTTP_STATUS_CODE_FROM_GATEWAY: case MALFORMED_RESPONSE_RECEIVED_FROM_GATEWAY: case GATEWAY_URL_DNS_ERROR: case GATEWAY_CONNECTION_TIMEOUT_ERROR: case GATEWAY_CONNECTION_SOCKET_ERROR: return serviceErrorResponse(error.getMessage()); default: logger.error("Charge {}: error {}", chargeId, error.getMessage()); return badRequestResponse(error.getMessage()); } }
private Response handleError(String chargeId, GatewayError error){ switch(error.getErrorType()) { case GATEWAY_CONNECTION_TIMEOUT_ERROR: case OTHER: return serviceErrorResponse(error.getMessage()); default: logger.error("Charge {}: error {}", chargeId, error.getMessage()); return badRequestResponse(error.getMessage()); } }
34
public Podcast patchUpdate(Podcast patchPodcast){ Podcast podcastToUpdate = this.findOne(patchPodcast.getId()); if (podcastToUpdate == null) throw new PodcastNotFoundException(); podcastToUpdate.setTitle(patchPodcast.getTitle()); podcastToUpdate.setUrl(patchPodcast.getUrl()); podcastToUpdate.setSignature(patchPodcast.getSignature()); podcastToUpdate.setType(patchPodcast.getType()); if (!coverBusiness.hasSameCoverURL(patchPodcast, podcastToUpdate)) { patchPodcast.getCover().setUrl(coverBusiness.download(patchPodcast)); } podcastToUpdate.setCover(coverBusiness.findOne(patchPodcast.getCover().getId()).setHeight(patchPodcast.getCover().getHeight()).setUrl(patchPodcast.getCover().getUrl()).setWidth(patchPodcast.getCover().getWidth())); podcastToUpdate.setDescription(patchPodcast.getDescription()); podcastToUpdate.setHasToBeDeleted(patchPodcast.getHasToBeDeleted()); podcastToUpdate.setTags(patchPodcast.getTags()); return this.reatachAndSave(podcastToUpdate); }
public Podcast patchUpdate(Podcast patchPodcast){ Podcast podcastToUpdate = this.findOne(patchPodcast.getId()); if (podcastToUpdate == null) throw new PodcastNotFoundException(); if (!coverBusiness.hasSameCoverURL(patchPodcast, podcastToUpdate)) { patchPodcast.getCover().setUrl(coverBusiness.download(patchPodcast)); } podcastToUpdate.setTitle(patchPodcast.getTitle()).setUrl(patchPodcast.getUrl()).setSignature(patchPodcast.getSignature()).setType(patchPodcast.getType()).setDescription(patchPodcast.getDescription()).setHasToBeDeleted(patchPodcast.getHasToBeDeleted()).setTags(tagBusiness.getTagListByName(patchPodcast.getTags())).setCover(coverBusiness.findOne(patchPodcast.getCover().getId()).setHeight(patchPodcast.getCover().getHeight()).setUrl(patchPodcast.getCover().getUrl()).setWidth(patchPodcast.getCover().getWidth())); return save(podcastToUpdate); }
35
void updateAllStreets(){ for (int i = 0; i < GameState.getInstance().getAllDeeds().size(); i++) { if (GameState.getInstance().getAllDeeds().get(i) instanceof Street) { final Street s = (Street) GameState.getInstance().getAllDeeds().get(i); if (s.getHouseCount() != 0) { final int finalI = i; runOnUiThread(new Runnable() { @Override public void run() { if (!s.getHasHotel()) { houseFields[finalI].setText(String.valueOf(s.getHouseCount())); } else { houseFields[finalI].setText("H"); } } }); } } } }
void updateAllStreets(){ for (int i = 0; i < GameState.getInstance().getAllDeeds().size(); i++) { if (GameState.getInstance().getAllDeeds().get(i) instanceof Street) { final Street s = (Street) GameState.getInstance().getAllDeeds().get(i); if (s.getHouseCount() != 0) { final int finalI = i; runOnUiThread(() -> { if (!s.getHasHotel()) { houseFields[finalI].setText(String.valueOf(s.getHouseCount())); } else { houseFields[finalI].setText("H"); } }); } } } }
36
public Time calculateTime(SpeedForm speedForm){ String majorUnit = ((majorUnit = speedForm.getDistanceMajorUnit()) != null) ? majorUnit : "kilometer"; String minorUnit = ((minorUnit = speedForm.getDistanceMinorUnit()) != null) ? minorUnit : "meter"; String speedUnit = ((speedUnit = speedForm.getSpeedUnit()) != null) ? speedUnit : "kilometerPerHour"; checkValidUnit(validSpeedUnits, speedUnit); TimeCalculator timeCalculator = TimeCalculatorFactory.buildFromSpeed(speedForm, majorUnit, minorUnit); return timeCalculator.computeTime(); }
public Time calculateTime(SpeedForm speedForm){ UnitParser unitParser = new UnitParser(speedForm).invoke(); TimeCalculator timeCalculator = TimeCalculatorFactory.buildFromSpeed(speedForm, unitParser.getMajorUnit(), unitParser.getMinorUnit()); return timeCalculator.computeTime(); }
37
private CompactionUnit pickForSizeRatio(int maxLevel, List<SortedRun> runs){ int candidateCount = 0; int startIndex = 0; boolean pickByRatio = false; for (int i = 0; i < runs.size(); i++) { SortedRun run = runs.get(i); candidateCount = 1; long candidateSize = run.size(); for (int j = i + 1; j < runs.size(); j++) { SortedRun next = runs.get(j); if (candidateSize * (100.0 + sizeRatio) / 100.0 < next.size()) { break; } candidateSize += next.size(); candidateCount++; } if (candidateCount > 1) { pickByRatio = true; startIndex = i; break; } } if (pickByRatio) { return createUnit(runs, maxLevel, startIndex, startIndex + candidateCount); } return null; }
private CompactionUnit pickForSizeRatio(int maxLevel, List<SortedRun> runs){ for (int i = 0; i < runs.size(); i++) { int candidateCount = 1; long candidateSize = runs.get(i).size(); for (int j = i + 1; j < runs.size(); j++) { SortedRun next = runs.get(j); if (candidateSize * (100.0 + sizeRatio) / 100.0 < next.size()) { break; } candidateSize += next.size(); candidateCount++; } if (candidateCount > 1) { return createUnit(runs, maxLevel, i, i + candidateCount); } } return null; }
38
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_chatting_resolved); assignViews(); KeyboardUtil.attach(this, mPanelRoot); sendImgTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(ChattingResolvedActivity.this, TranslucentActivity.class)); } }); mRootView.setOnKeyboardShowingListener(new CustomRootLayout.OnKeyboardShowingListener() { @Override public void onKeyboardShowing(boolean isShowing) { Log.d(TAG, String.format("Keyboard is %s", isShowing ? "showing" : "hiding")); } }); mContentRyv.setLayoutManager(new LinearLayoutManager(this)); mContentRyv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_UP) { KeyboardUtil.hideKeyboard(mSendEdt); mPanelRoot.setVisibility(View.GONE); } return false; } }); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_chatting_resolved); assignViews(); KeyboardUtil.attach(this, mPanelRoot, new KeyboardUtil.OnKeyboardShowingListener() { @Override public void onKeyboardShowing(boolean isShowing) { Log.d(TAG, String.format("Keyboard is %s", isShowing ? "showing" : "hiding")); } }); sendImgTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(ChattingResolvedActivity.this, TranslucentActivity.class)); } }); mContentRyv.setLayoutManager(new LinearLayoutManager(this)); mContentRyv.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (motionEvent.getAction() == MotionEvent.ACTION_UP) { KeyboardUtil.hideKeyboard(mSendEdt); mPanelRoot.setVisibility(View.GONE); } return false; } }); }
39
public void onResult(User user){ if (user == null) { listener.onResult(LoginAttemptListener.INC_USERNAME); return; } if (user.getPassword().equals(enteredPassword)) { currentUser = user; listener.onResult(LoginAttemptListener.SUCCESS); } else { currentUser = null; listener.onResult(LoginAttemptListener.INC_PASSWORD); } }
public void onResult(User user){ if (user == null) { listener.onResult(LoginAttemptListener.INC_USERNAME); return; } if (user.getPassword().equals(enteredPassword)) { masterVM.setCurrentUser(user); listener.onResult(LoginAttemptListener.SUCCESS); } else { listener.onResult(LoginAttemptListener.INC_PASSWORD); } }
40
void startTask(HSSource gearSource, String[] tasks){ if (!mRunning) { mGearSource = gearSource; mTasks = new ArrayList<>(Arrays.asList(tasks)); mTask = new Task(); mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, tasks); mResponse = new TaskResponse(); mRunning = true; } }
void startTask(HSSource gearSource, String[] tasks){ if (!mRunning) { mGearSource = gearSource; mTasks = new ArrayList<>(Arrays.asList(tasks)); mTask = new Task(); mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, tasks); mRunning = true; } }
41
public Map<String, Object> querySchedule(User loginUser, String projectName, Integer processDefineId, String searchVal, Integer pageNo, Integer pageSize){ HashMap<String, Object> result = new HashMap<>(); Project project = projectMapper.queryByName(projectName); boolean hasProjectAndPerm = projectService.hasProjectAndPerm(loginUser, project, result); if (!hasProjectAndPerm) { return result; } ProcessDefinition processDefinition = processService.findProcessDefineById(processDefineId); if (processDefinition == null) { putMsg(result, Status.PROCESS_DEFINE_NOT_EXIST, processDefineId); return result; } Page<Schedule> page = new Page<>(pageNo, pageSize); IPage<Schedule> scheduleIPage = scheduleMapper.queryByProcessDefineIdPaging(page, processDefineId, searchVal); PageInfo<Schedule> pageInfo = new PageInfo<>(pageNo, pageSize); pageInfo.setTotalCount((int) scheduleIPage.getTotal()); pageInfo.setLists(scheduleIPage.getRecords()); result.put(Constants.DATA_LIST, pageInfo); putMsg(result, Status.SUCCESS); return result; }
public Result<PageListVO<Schedule>> querySchedule(User loginUser, String projectName, Integer processDefineId, String searchVal, Integer pageNo, Integer pageSize){ Project project = projectMapper.queryByName(projectName); CheckParamResult checkResult = projectService.hasProjectAndPerm(loginUser, project); if (!Status.SUCCESS.equals(checkResult.getStatus())) { return Result.error(checkResult); } ProcessDefinition processDefinition = processService.findProcessDefineById(processDefineId); if (processDefinition == null) { return Result.errorWithArgs(Status.PROCESS_DEFINE_NOT_EXIST, processDefineId); } Page<Schedule> page = new Page<>(pageNo, pageSize); IPage<Schedule> scheduleIPage = scheduleMapper.queryByProcessDefineIdPaging(page, processDefineId, searchVal); PageInfo<Schedule> pageInfo = new PageInfo<>(pageNo, pageSize); pageInfo.setTotalCount((int) scheduleIPage.getTotal()); pageInfo.setLists(scheduleIPage.getRecords()); return Result.success(new PageListVO<>(pageInfo)); }
42
public Map<K, Object> executeOnKeys(Set<K> keys, EntryProcessor entryProcessor){ Set<Data> dataKeys = new HashSet<Data>(keys.size()); for (K key : keys) { dataKeys.add(toData(key)); } MapExecuteOnKeysRequest request = new MapExecuteOnKeysRequest(name, entryProcessor, dataKeys); MapEntries entrySet = invoke(request); Map<K, Object> result = new HashMap<K, Object>(); for (Entry<Data, Data> dataEntry : entrySet) { final Data keyData = dataEntry.getKey(); final Data valueData = dataEntry.getValue(); K key = toObject(keyData); result.put(key, toObject(valueData)); } return result; }
public Map<K, Object> executeOnKeys(Set<K> keys, EntryProcessor entryProcessor){ Set<Data> dataKeys = new HashSet<Data>(keys.size()); for (K key : keys) { dataKeys.add(toData(key)); } MapExecuteOnKeysRequest request = new MapExecuteOnKeysRequest(name, entryProcessor, dataKeys); MapEntries entrySet = invoke(request); return prepareResult(entrySet); }
43
public List<ProviderMessageContent> buildMessageContents(Long notificationId, Date providerCreationDate, ConfigurationJobModel job, PolicyOverrideNotificationView notificationView, BlackDuckBucket blackDuckBucket, BlackDuckServicesFactory blackDuckServicesFactory){ long timeout = blackDuckServicesFactory.getBlackDuckHttpClient().getTimeoutInSeconds(); BlackDuckBucketService bucketService = blackDuckServicesFactory.createBlackDuckBucketService(); BlackDuckResponseCache responseCache = new BlackDuckResponseCache(bucketService, blackDuckBucket, timeout); BlackDuckService blackDuckService = blackDuckServicesFactory.createBlackDuckService(); ComponentService componentService = blackDuckServicesFactory.createComponentService(); PolicyOverrideNotificationContent overrideContent = notificationView.getContent(); ItemOperation operation = ItemOperation.DELETE; try { ProviderMessageContent.Builder projectVersionMessageBuilder = new ProviderMessageContent.Builder().applyProvider(getProviderName(), blackDuckServicesFactory.getBlackDuckHttpClient().getBaseUrl()).applyTopic(MessageBuilderConstants.LABEL_PROJECT_NAME, overrideContent.getProjectName()).applySubTopic(MessageBuilderConstants.LABEL_PROJECT_VERSION_NAME, overrideContent.getProjectVersionName(), overrideContent.getProjectVersion()).applyProviderCreationTime(providerCreationDate); List<PolicyInfo> policies = overrideContent.getPolicyInfos(); List<ComponentItem> items = retrievePolicyItems(responseCache, blackDuckService, componentService, overrideContent, policies, notificationId, operation, overrideContent.getProjectVersion()); projectVersionMessageBuilder.applyAllComponentItems(items); return List.of(projectVersionMessageBuilder.build()); } catch (AlertException ex) { logger.error("Error creating policy override message.", ex); } return List.of(); }
public List<ProviderMessageContent> buildMessageContents(Long notificationId, Date providerCreationDate, ConfigurationJobModel job, PolicyOverrideNotificationView notificationView, BlackDuckBucket blackDuckBucket, BlackDuckServicesFactory blackDuckServicesFactory){ long timeout = blackDuckServicesFactory.getBlackDuckHttpClient().getTimeoutInSeconds(); BlackDuckBucketService bucketService = blackDuckServicesFactory.createBlackDuckBucketService(); BlackDuckResponseCache responseCache = new BlackDuckResponseCache(bucketService, blackDuckBucket, timeout); PolicyOverrideNotificationContent overrideContent = notificationView.getContent(); ItemOperation operation = ItemOperation.DELETE; try { ProviderMessageContent.Builder projectVersionMessageBuilder = new ProviderMessageContent.Builder().applyProvider(getProviderName(), blackDuckServicesFactory.getBlackDuckHttpClient().getBaseUrl()).applyTopic(MessageBuilderConstants.LABEL_PROJECT_NAME, overrideContent.getProjectName()).applySubTopic(MessageBuilderConstants.LABEL_PROJECT_VERSION_NAME, overrideContent.getProjectVersionName(), overrideContent.getProjectVersion()).applyProviderCreationTime(providerCreationDate); List<PolicyInfo> policies = overrideContent.getPolicyInfos(); List<ComponentItem> items = retrievePolicyItems(responseCache, overrideContent, policies, notificationId, operation, overrideContent.getProjectVersion()); projectVersionMessageBuilder.applyAllComponentItems(items); return List.of(projectVersionMessageBuilder.build()); } catch (AlertException ex) { logger.error("Error creating policy override message.", ex); } return List.of(); }
44
public void onAttach(Activity activity){ try { positiveListener = (PositiveListener) activity; } catch (ClassCastException exception) { throw new ClassCastException(activity.toString() + " must implement BaseDialogFragment.PositiveListener"); } if (activity instanceof NegativeListener) { negativeListener = (NegativeListener) activity; } super.onAttach(activity); }
public void onAttach(Activity activity){ if (activity instanceof MsgDialogCallBack) { mListener = (MsgDialogCallBack) activity; } super.onAttach(activity); }
45
public void setDelegate(){ final ExtensibleConfigurationPersister configurationPersister = new EmptyConfigurationPersister(); final boolean isMaster = false; final IgnoredDomainResourceRegistry ignoredDomainResourceRegistry = new IgnoredDomainResourceRegistry(hostControllerInfo); final PathManagerService pathManager = new HostPathManagerService(); final DelegatingConfigurableAuthorizer authorizer = new DelegatingConfigurableAuthorizer(); final HostRegistrations hostRegistrations = null; final DomainHostExcludeRegistry domainHostExcludeRegistry = new DomainHostExcludeRegistry(); final MutableRootResourceRegistrationProvider rootResourceRegistrationProvider = new MutableRootResourceRegistrationProvider() { @Override public ManagementResourceRegistration getRootResourceRegistrationForUpdate(OperationContext context) { return managementModel.getRootResourceRegistration(); } }; DomainRootDefinition domain = new DomainRootDefinition(domainController, hostControllerEnvironment, configurationPersister, repository, repository, isMaster, hostControllerInfo, extensionRegistry, ignoredDomainResourceRegistry, pathManager, authorizer, hostRegistrations, domainHostExcludeRegistry, rootResourceRegistrationProvider); getDelegatingResourceDefiniton().setDelegate(domain); final String hostName = hostControllerEnvironment.getHostName(); final HostControllerConfigurationPersister hostControllerConfigurationPersister = new HostControllerConfigurationPersister(hostControllerEnvironment, hostControllerInfo, Executors.newCachedThreadPool(), extensionRegistry, extensionRegistry); final HostRunningModeControl runningModeControl = new HostRunningModeControl(RunningMode.NORMAL, RestartMode.SERVERS); final ServerInventory serverInventory = null; final HostFileRepository remoteFileRepository = repository; final AbstractVaultReader vaultReader = null; final ControlledProcessState processState = null; final ManagedAuditLogger auditLogger = null; final BootErrorCollector bootErrorCollector = null; hostResourceDefinition = new HostResourceDefinition(hostName, hostControllerConfigurationPersister, hostControllerEnvironment, runningModeControl, repository, hostControllerInfo, serverInventory, remoteFileRepository, repository, domainController, extensionRegistry, vaultReader, ignoredDomainResourceRegistry, processState, pathManager, authorizer, auditLogger, bootErrorCollector); }
public void setDelegate(){ final ExtensibleConfigurationPersister configurationPersister = new EmptyConfigurationPersister(); final boolean isMaster = false; final IgnoredDomainResourceRegistry ignoredDomainResourceRegistry = new IgnoredDomainResourceRegistry(hostControllerInfo); final PathManagerService pathManager = new HostPathManagerService(); final DelegatingConfigurableAuthorizer authorizer = new DelegatingConfigurableAuthorizer(); final HostRegistrations hostRegistrations = null; final DomainHostExcludeRegistry domainHostExcludeRegistry = new DomainHostExcludeRegistry(); final MutableRootResourceRegistrationProvider rootResourceRegistrationProvider = new MutableRootResourceRegistrationProvider() { @Override public ManagementResourceRegistration getRootResourceRegistrationForUpdate(OperationContext context) { return managementModel.getRootResourceRegistration(); } }; DomainRootDefinition domain = new DomainRootDefinition(hostControllerEnvironment, configurationPersister, repository, repository, isMaster, hostControllerInfo, extensionRegistry, ignoredDomainResourceRegistry, authorizer, hostRegistrations, domainHostExcludeRegistry, rootResourceRegistrationProvider); getDelegatingResourceDefiniton().setDelegate(domain); final String hostName = hostControllerEnvironment.getHostName(); final HostControllerConfigurationPersister hostControllerConfigurationPersister = new HostControllerConfigurationPersister(hostControllerEnvironment, hostControllerInfo, Executors.newCachedThreadPool(), extensionRegistry, extensionRegistry); final HostRunningModeControl runningModeControl = new HostRunningModeControl(RunningMode.NORMAL, RestartMode.SERVERS); final ServerInventory serverInventory = null; final AbstractVaultReader vaultReader = null; final ControlledProcessState processState = null; final ManagedAuditLogger auditLogger = null; final BootErrorCollector bootErrorCollector = null; hostResourceDefinition = new HostResourceDefinition(hostName, hostControllerConfigurationPersister, hostControllerEnvironment, runningModeControl, hostControllerInfo, serverInventory, repository, domainController, extensionRegistry, vaultReader, ignoredDomainResourceRegistry, processState, pathManager, authorizer, auditLogger, bootErrorCollector); }
46
private void createVideoView(@NonNull final View rootView){ String url = getURLToUse(); playerView = rootView.findViewById(R.id.recipeinfo_step_video); final ImageView ivThumbnail = rootView.findViewById(R.id.recipeinfo_step_video_thumbnail); if ((!AppUtil.isEmpty(url)) && (!"IMAGE_MEDIA".equals(url))) { ivThumbnail.setVisibility(View.GONE); playerView.setControllerVisibilityListener(this); playerView.setErrorMessageProvider(new PlayerErrorMessageProvider()); } else { playerView.setVisibility(View.GONE); if ("IMAGE_MEDIA".equals(url)) { url = null; Picasso.get().load(mStepData.getURLThumbnail()).placeholder(R.drawable.ic_baseline_fastfood_24px).into(ivThumbnail, new com.squareup.picasso.Callback() { @Override public void onSuccess() { Log.d(TAG, "Picasso:onSuccess: image fetched"); } @Override public void onError(Exception e) { Log.e(TAG, "Picasso:onError: ", e); ivThumbnail.setImageResource(R.drawable.ic_baseline_fastfood_24px); } }); } } mediaURL = url; }
private void createVideoView(@NonNull final View rootView){ String url = getURLToUse(); final ImageView ivThumbnail = rootView.findViewById(R.id.recipeinfo_step_video_thumbnail); mPlayerView = rootView.findViewById(R.id.recipeinfo_step_video); if ((!AppUtil.isEmpty(url)) && (!"IMAGE_MEDIA".equals(url))) { ivThumbnail.setVisibility(View.GONE); mPlayerView.setErrorMessageProvider(new PlayerErrorMessageProvider()); } else { mPlayerView.setVisibility(View.GONE); if ("IMAGE_MEDIA".equals(url)) { url = null; Picasso.get().load(mStepData.getURLThumbnail()).placeholder(R.drawable.ic_baseline_fastfood_24px).into(ivThumbnail, new com.squareup.picasso.Callback() { @Override public void onSuccess() { Log.d(TAG, "Picasso:onSuccess: image fetched"); } @Override public void onError(Exception e) { Log.e(TAG, "Picasso:onError: ", e); ivThumbnail.setImageResource(R.drawable.ic_baseline_fastfood_24px); } }); } } mMediaURL = url; }
47
public Object getFirstValueFromJSONArray(String key) throws Exception{ Object valueToReturn; try { object = parser.parse(new FileReader(file)); jsonObject = (JSONObject) object; if (jsonObject.containsKey(key)) { if (jsonObject.get(key) instanceof JSONArray) { JSONArray jsonArray = (JSONArray) jsonObject.get(key); valueToReturn = jsonArray.get(0); } else { throw new NoSuchJSONArrayException(); } } else { throw new NoSuchPropertyException(); } } catch (ParseException e) { throw new JSONParseException(); } catch (NoSuchPropertyException e) { throw new NoSuchPropertyException("Property " + key + " is not present in JSON"); } catch (NoSuchJSONArrayException e) { throw new NoSuchJSONArrayException(); } catch (FileNotFoundException e) { throw new FileNotFoundException("File " + file + " is not found"); } catch (IOException e) { throw new IOException("Could not read file " + file); } catch (Exception e) { throw new Exception(e.getCause().toString()); } return valueToReturn; }
public Object getFirstValueFromJSONArray(String key) throws Exception{ Object valueToReturn; try { object = parser.parse(new FileReader(file)); jsonObject = (JSONObject) object; valueToReturn = accessJSON.getFirstValueFromJSONArray(jsonObject, key); } catch (ParseException e) { throw new JSONParseException(); } catch (FileNotFoundException e) { throw new FileNotFoundException("File " + file + " is not found"); } catch (IOException e) { throw new IOException("Could not read file " + file); } catch (Exception e) { throw new Exception(e.getMessage()); } return valueToReturn; }
48
public void doList(List<UrlCapsule> urlCapsules, T params, int count){ StringBuilder a = new StringBuilder(); for (int i = 0; i < 10 && i < urlCapsules.size(); i++) { a.append(i + 1).append(urlCapsules.get(i).toEmbedDisplay()); } DiscordUserDisplay userInfoConsideringGuildOrNot = CommandUtil.getUserInfoEscaped(params.getE(), params.getDiscordId()); EmbedBuilder embedBuilder = configEmbed(new ChuuEmbedBuilder(params.getE()).setDescription(a).setThumbnail(userInfoConsideringGuildOrNot.urlImage()), params, count); params.getE().sendMessage(embedBuilder.build()).queue(message1 -> new Reactionary<>(urlCapsules, message1, embedBuilder)); }
public void doList(List<UrlCapsule> urlCapsules, T params, int count){ DiscordUserDisplay userInfoConsideringGuildOrNot = CommandUtil.getUserInfoEscaped(params.getE(), params.getDiscordId()); EmbedBuilder embedBuilder = configEmbed(new ChuuEmbedBuilder(params.getE()).setThumbnail(userInfoConsideringGuildOrNot.urlImage()), params, count); new PaginatorBuilder<>(params.getE(), embedBuilder, urlCapsules).build().queue(); }
49
public void onAddWordBtnClicked(){ String word = wordField.getText(); String translation = translationField.getText(); WordEntry wordEntry = new WordEntry(word, translation); if (word.isEmpty()) { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Word field must not be empty.", ButtonType.OK); alert.showAndWait(); return; } if (translation.isEmpty()) { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Translation field must not be empty.", ButtonType.OK); alert.showAndWait(); return; } if (wordEntryList.isWordEntryOnList(wordEntry)) { Alert alert = new Alert(Alert.AlertType.INFORMATION, "This word entry [word: " + word + ", translation: " + translation + "] " + "is already in your dictionary.", ButtonType.OK); alert.showAndWait(); return; } wordEntryList.addWord(new WordEntry(word, translation)); afterWordsListChanged(); wordField.clear(); translationField.clear(); }
public void onAddWordBtnClicked(){ String word = wordField.getText(); String translation = translationField.getText(); WordEntry wordEntry = new WordEntry(word, translation); if (word.isEmpty() || translation.isEmpty()) { Alert alert = new Alert(Alert.AlertType.INFORMATION, "Word and Translation fields must not be empty.", ButtonType.OK); alert.showAndWait(); return; } if (wordEntryList.isWordEntryOnList(wordEntry)) { Alert alert = new Alert(Alert.AlertType.INFORMATION, "This word entry [word: " + word + ", translation: " + translation + "] " + "is already in your dictionary.", ButtonType.OK); alert.showAndWait(); return; } wordEntryList.addWord(new WordEntry(word, translation)); afterWordsListChanged(); wordField.clear(); translationField.clear(); }
50
private void testShardBoundaries(int[] expected, int numShards, int numDisks, int[] rangeBounds){ IPartitioner partitioner = Murmur3Partitioner.instance; List<Splitter.WeightedRange> ranges = new ArrayList<>(); for (int i = 0; i < rangeBounds.length; i += 2) ranges.add(new Splitter.WeightedRange(1.0, new Range<>(getToken(rangeBounds[i + 0]), getToken(rangeBounds[i + 1])))); SortedLocalRanges sortedRanges = SortedLocalRanges.forTesting(cfs, ranges); System.out.println(sortedRanges.getRanges()); List<PartitionPosition> diskBoundaries = sortedRanges.split(numDisks); System.out.println(diskBoundaries); int[] result = UnifiedCompactionStrategy.computeShardBoundaries(sortedRanges, diskBoundaries, numShards, partitioner.splitter()).stream().map(PartitionPosition::getToken).mapToInt(this::fromToken).toArray(); Assert.assertArrayEquals("Disks " + numDisks + " shards " + numShards + " expected " + Arrays.toString(expected) + " was " + Arrays.toString(result), expected, result); }
private void testShardBoundaries(int[] expected, int numShards, int numDisks, int[] rangeBounds){ IPartitioner partitioner = Murmur3Partitioner.instance; List<Splitter.WeightedRange> ranges = new ArrayList<>(); for (int i = 0; i < rangeBounds.length; i += 2) ranges.add(new Splitter.WeightedRange(1.0, new Range<>(getToken(rangeBounds[i + 0]), getToken(rangeBounds[i + 1])))); SortedLocalRanges sortedRanges = SortedLocalRanges.forTesting(cfs, ranges); List<PartitionPosition> diskBoundaries = sortedRanges.split(numDisks); int[] result = UnifiedCompactionStrategy.computeShardBoundaries(sortedRanges, diskBoundaries, numShards, partitioner.splitter()).stream().map(PartitionPosition::getToken).mapToInt(this::fromToken).toArray(); Assert.assertArrayEquals("Disks " + numDisks + " shards " + numShards + " expected " + Arrays.toString(expected) + " was " + Arrays.toString(result), expected, result); }
51
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException{ Slider s = (Slider) w; String snippetName = "slider"; String snippet = getSnippet(snippetName); String frequency = s.getFrequency() == 0 ? "200" : Integer.toString(s.getFrequency()); snippet = StringUtils.replace(snippet, "%id%", itemUIRegistry.getWidgetId(s)); snippet = StringUtils.replace(snippet, "%category%", getCategory(w)); snippet = StringUtils.replace(snippet, "%icon_type%", config.getIconType()); snippet = StringUtils.replace(snippet, "%state%", getState(w)); snippet = StringUtils.replace(snippet, "%item%", w.getItem()); snippet = StringUtils.replace(snippet, "%label%", getLabel(s)); snippet = StringUtils.replace(snippet, "%state%", itemUIRegistry.getState(s).toString()); snippet = StringUtils.replace(snippet, "%frequency%", frequency); snippet = StringUtils.replace(snippet, "%switch%", s.isSwitchEnabled() ? "1" : "0"); snippet = StringUtils.replace(snippet, "%servletname%", WebAppServlet.SERVLET_NAME); snippet = processColor(w, snippet); sb.append(snippet); return null; }
public EList<Widget> renderWidget(Widget w, StringBuilder sb) throws RenderException{ Slider s = (Slider) w; String snippetName = "slider"; String snippet = getSnippet(snippetName); String frequency = s.getFrequency() == 0 ? "200" : Integer.toString(s.getFrequency()); snippet = preprocessSnippet(snippet, w); snippet = StringUtils.replace(snippet, "%frequency%", frequency); snippet = StringUtils.replace(snippet, "%switch%", s.isSwitchEnabled() ? "1" : "0"); snippet = processColor(w, snippet); sb.append(snippet); return null; }
52
public void addPost(OnePost post) throws SQLException{ post.setStatusId(1); String plsql = "BEGIN PACKAGE_FORUM.INSERT_POST(?, ?, ?, ?); END;"; System.out.println("wtf"); CallableStatement statement = DatabaseConnection.getConnection().prepareCall(plsql); System.out.println(post.getContent()); System.out.println(post.getStatusId()); System.out.println(post.getThreadId()); System.out.println(post.getUserId()); statement.setString(1, post.getContent()); statement.setInt(2, post.getStatusId()); statement.setInt(3, post.getThreadId()); statement.setInt(4, post.getUserId()); statement.execute(); statement.close(); }
public void addPost(OnePost post) throws SQLException{ post.setStatusId(1); String plsql = "BEGIN PACKAGE_FORUM.INSERT_POST(?, ?, ?, ?); END;"; CallableStatement statement = DatabaseConnection.getConnection().prepareCall(plsql); statement.setString(1, post.getContent()); statement.setInt(2, post.getStatusId()); statement.setInt(3, post.getThreadId()); statement.setInt(4, post.getUserId()); statement.execute(); statement.close(); }
53
final Set<String> getConfigurationValues(@Nonnull final LinkerContext context, @Nonnull final String propertyName){ final HashSet<String> set = new HashSet<>(); final SortedSet<ConfigurationProperty> properties = context.getConfigurationProperties(); for (final ConfigurationProperty configurationProperty : properties) { if (propertyName.equals(configurationProperty.getName())) { for (final String value : configurationProperty.getValues()) { set.add(value); } } } return set; }
final Set<String> getConfigurationValues(@Nonnull final LinkerContext context, @Nonnull final String propertyName){ final HashSet<String> set = new HashSet<>(); final SortedSet<ConfigurationProperty> properties = context.getConfigurationProperties(); for (final ConfigurationProperty configurationProperty : properties) { if (propertyName.equals(configurationProperty.getName())) { set.addAll(configurationProperty.getValues()); } } return set; }
54
public void processPdfFiles(List<Pdf> pdfs, List<ScannableItem> scannedItems){ List<ScannableItem> uploadedItems = new ArrayList<ScannableItem>(); List<FileUploadResponse> responses = documentManagementService.uploadDocuments(pdfs); Map<String, String> response = DocumentManagementService.convertResponseToMap(responses); scannedItems.forEach(item -> { if (response.containsKey(item.getFileName())) { log.info("File found {}", item.getFileName()); item.setDocumentUrl(response.get(item.getFileName())); uploadedItems.add(item); } else { log.info("File not found {}", item.getFileName()); } }); scannableItemRepository.saveAll(uploadedItems); }
public void processPdfFiles(List<Pdf> pdfs, List<ScannableItem> scannedItems){ List<FileUploadResponse> responses = documentManagementService.uploadDocuments(pdfs); Map<String, String> response = DocumentManagementService.convertResponseToMap(responses); scannedItems.forEach(item -> { log.info(item.getFileName(), response.containsKey(item.getFileName())); if (response.containsKey(item.getFileName())) { log.info("File found {}", item.getFileName()); item.setDocumentUrl(response.get(item.getFileName())); } else { log.info("File not found {}", item.getFileName()); } }); scannableItemRepository.saveAll(scannedItems); }
55
public static List<R> processIntersectingRetrievals(List<IndexCall<R>> retrievals, final int limit){ Preconditions.checkArgument(!retrievals.isEmpty()); Preconditions.checkArgument(limit >= 0, "Invalid limit: %s", limit); List<R> results; int multiplier = Math.min(16, (int) Math.pow(2, retrievals.size() - 1)); int subLimit = Integer.MAX_VALUE; if (Integer.MAX_VALUE / multiplier >= limit) subLimit = limit * multiplier; boolean exhaustedResults; do { exhaustedResults = true; results = null; for (IndexCall<R> call : retrievals) { Collection<R> subResult; try { subResult = call.call(subLimit); } catch (Exception e) { throw new JanusGraphException("Could not process individual retrieval call ", e); } if (subResult.size() >= subLimit) exhaustedResults = false; if (results == null) { results = Lists.newArrayList(subResult); } else { Set<R> subResultSet = ImmutableSet.copyOf(subResult); Iterator resultIterator = results.iterator(); while (resultIterator.hasNext()) { if (!subResultSet.contains(resultIterator.next())) resultIterator.remove(); } } } subLimit = (int) Math.min(Integer.MAX_VALUE - 1, Math.max(Math.pow(subLimit, 1.5), (subLimit + 1) * 2)); } while (results != null && results.size() < limit && !exhaustedResults); return results; }
public static List<R> processIntersectingRetrievals(List<IndexCall<R>> retrievals, final int limit){ Preconditions.checkArgument(!retrievals.isEmpty()); Preconditions.checkArgument(limit >= 0, "Invalid limit: %s", limit); List<R> results; int multiplier = Math.min(16, (int) Math.pow(2, retrievals.size() - 1)); int subLimit = Integer.MAX_VALUE; if (Integer.MAX_VALUE / multiplier >= limit) subLimit = limit * multiplier; boolean exhaustedResults; do { exhaustedResults = true; results = null; for (IndexCall<R> call : retrievals) { Collection<R> subResult; try { subResult = call.call(subLimit); } catch (Exception e) { throw new JanusGraphException("Could not process individual retrieval call ", e); } if (subResult.size() >= subLimit) exhaustedResults = false; if (results == null) { results = Lists.newArrayList(subResult); } else { Set<R> subResultSet = ImmutableSet.copyOf(subResult); results.removeIf(o -> !subResultSet.contains(o)); } } subLimit = (int) Math.min(Integer.MAX_VALUE - 1, Math.max(Math.pow(subLimit, 1.5), (subLimit + 1) * 2)); } while (results != null && results.size() < limit && !exhaustedResults); return results; }
56
static String formatTemperature(Context context, double temperature, boolean isMetric){ double temp; if (!isMetric) { temp = 9 * temperature / 5 + 32; } else { temp = temperature; } return context.getString(R.string.format_temperature, temp); }
public static String formatTemperature(Context context, double temperature){ String suffix = "\u00B0"; if (!isMetric(context)) { temperature = (temperature * 1.8) + 32; } return String.format(context.getString(R.string.format_temperature), temperature); }
57
public Node visitFunctionDefinitionStatement(Mx_starParser.FunctionDefinitionStatementContext ctx){ String name = ctx.Identifier().getText(); String rtype = ctx.type().getText(); String trace = dom.getClassTrace(); if (!rtype.equals("void") && !typeList.hasType(rtype)) { assert false; } LOGGER.fine("enter function: " + name); dom.enterFunc(trace, name, rtype); ParamListInstance node = (ParamListInstance) visit(ctx.paramListDefinition()); if (state == VisitState.MEMBER_DECLARATION) { Func func = new Func(trace, name, rtype); if (!dom.isGlobal()) { func.addParam(trace); } node.params.params.forEach(param -> func.addParam(param.second)); if (funcList.addFunc(func) == false) { assert false; } } else { code.newSection(dom.getAddr()); for (Pair<String, String> param : node.params.params) { allocateVariable(param.first, param.second); } if (ctx.statements() != null) { visit(ctx.statements()); } code.packScope(); code.packSection(); } LOGGER.fine("exit function: " + name); dom.exitFunc(); return new FunctionNode(name, rtype); }
public Node visitFunctionDefinitionStatement(Mx_starParser.FunctionDefinitionStatementContext ctx){ String name = ctx.Identifier().getText(); String rtype = ctx.type().getText(); String trace = dom.getClassTrace(); if (!rtype.equals("void") && !typeList.hasType(rtype)) { assert false; } LOGGER.fine("enter function: " + name); dom.enterFunc(trace, name, rtype); ParamListInstance node = (ParamListInstance) visit(ctx.paramListDefinition()); if (state == VisitState.MEMBER_DECLARATION) { Func func = new Func(trace, name, rtype); if (!dom.isGlobal()) { func.addParam(trace); } node.params.params.forEach(param -> func.addParam(param.second)); if (funcList.addFunc(func) == false) { assert false; } } else { code.newSection(dom.getAddr()); if (ctx.statements() != null) { visit(ctx.statements()); } code.packScope(); code.packSection(); } LOGGER.fine("exit function: " + name); dom.exitFunc(); return new FunctionNode(name, rtype); }
58
public Mono<CollectionModel<EntityModel<HouseholdSearch>>> getHouseholds(ServerWebExchange exchange){ MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); String hostName = queryParams.getFirst("host"); String address = queryParams.getFirst("address"); Flux<HouseholdSearch> householdSearchFlux; if (hostName != null) { householdSearchFlux = householdSearchService.getHouseholdsByHostName(hostName); } else if (address != null) { householdSearchFlux = householdSearchService.getHouseholdsByAddress(address); } else { householdSearchFlux = householdSearchService.getHouseholds(); } return assembler.toCollectionModel(householdSearchFlux, exchange); }
public Mono<CollectionModel<EntityModel<HouseholdSearch>>> getHouseholds(ServerWebExchange exchange){ MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams(); Flux<HouseholdSearch> householdSearchFlux = householdSearchService.getHouseholdsByFilters(queryParams); return assembler.toCollectionModel(householdSearchFlux, exchange); }
59
public boolean updateEvent(String event, String email){ Person p = emailPersonMap.get(email); if (p == null) { return false; } switch(event) { case "checkIn": if (p.getData().isCheckedIn()) { return false; } updateDB(email); p.getData().setCheckedIn(true); break; case "tshirt": if (p.getData().isTshirt()) { return false; } p.getData().setTshirt(true); break; case "lunch1": p.getData().setLunch1(p.getData().getLunch1() + 1); break; case "dinner": p.getData().setDinner(p.getData().getDinner() + 1); break; case "midnightSnack": p.getData().setMidnightSnack(p.getData().getMidnightSnack() + 1); break; case "breakfast": p.getData().setBreakfast(p.getData().getBreakfast() + 1); break; case "lunch2": p.getData().setLunch2(p.getData().getLunch2() + 1); break; default: return false; } backupDB(); return true; }
public boolean updateEvent(String event, String email){ Person p = emailPersonMap.get(email); if (p == null) { return false; } switch(event) { case "checkIn": if (p.getData().isCheckedIn()) { return false; } p.getData().setCheckedIn(true); break; case "tshirt": if (p.getData().isTshirt()) { return false; } p.getData().setTshirt(true); break; default: if (!p.getData().getEvents().containsKey(event)) { return false; } p.getData().incrementEventCount(event); break; } backupDB(); return true; }
60
public void onCreate(){ LogWrapper.log(Log.INFO, LOG_TAG, "Creating DNS VPN service"); VpnController.getInstance().setIntraVpnService(this); firebaseAnalytics = FirebaseAnalytics.getInstance(this); syncNumRequests(); }
public void onCreate(){ LogWrapper.log(Log.INFO, LOG_TAG, "Creating DNS VPN service"); VpnController.getInstance().setIntraVpnService(this); syncNumRequests(); }
61
public void testCreateSFSGeneratesFileSystemCredentials(){ AtomicBoolean tested = new AtomicBoolean(false); String expectedFileName = "expectedFile"; File expectedFile = new File(directory.getAbsolutePath() + File.separator + expectedFileName); FileSelectActivity activity = Robolectric.setupActivity(FileSelectActivity.class); FileWorkflow workflow = new FileWorkflow(); workflow.setFileOrDirectory(directory); Intent startCreateSFS = new Intent(activity, CreateSecureFileSystem.class); startCreateSFS.putExtra(FileWorkflow.PARM_WORKFLOW_NAME, workflow); CreateSecureFileSystem createSecureFileSystem = Robolectric.buildActivity(CreateSecureFileSystem.class, startCreateSFS).create().get(); createSecureFileSystem.setOnCompleteListener(credentials -> { try { new SecureFileSystem(expectedFile) { @Override protected SecureString getPassword() { return credentials.getPassword(); } }; tested.set(true); } catch (ChunkedMediumException e) { e.printStackTrace(); fail("Unexpected error"); } }); EditText fileName = createSecureFileSystem.findViewById(R.id.fileName); fileName.setText(expectedFileName); EditText password = createSecureFileSystem.findViewById(R.id.password); password.setText("password"); password = createSecureFileSystem.findViewById(R.id.confirmPassword); password.setText("password"); createSecureFileSystem.findViewById(R.id.ok).performClick(); Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> expectedFile.exists() && tested.get()); assertTrue("SFS loadable using credentials", tested.get()); }
public void testCreateSFSGeneratesFileSystemCredentials(){ AtomicBoolean tested = new AtomicBoolean(false); String expectedFileName = "expectedFile"; File expectedFile = new File(directory.getAbsolutePath() + File.separator + expectedFileName); CreateSecureFileSystem createSecureFileSystem = Robolectric.buildActivity(CreateSecureFileSystem.class, startCreateSFS).create().get(); createSecureFileSystem.setOnCompleteListener(credentials -> { try { new SecureFileSystem(expectedFile) { @Override protected SecureString getPassword() { return credentials.getPassword(); } }; tested.set(true); } catch (ChunkedMediumException e) { e.printStackTrace(); fail("Unexpected error"); } }); EditText fileName = createSecureFileSystem.findViewById(R.id.fileName); fileName.setText(expectedFileName); EditText password = createSecureFileSystem.findViewById(R.id.password); password.setText("password"); password = createSecureFileSystem.findViewById(R.id.confirmPassword); password.setText("password"); createSecureFileSystem.findViewById(R.id.ok).performClick(); Awaitility.await().atMost(10, TimeUnit.SECONDS).until(() -> expectedFile.exists() && tested.get()); assertTrue("SFS loadable using credentials", tested.get()); }
62
public boolean write(HttpObject o){ if (o instanceof HttpHeaders) { logBuilder.startResponse(); final HttpHeaders headers = (HttpHeaders) o; final HttpStatus status = headers.status(); if (status != null && status.codeClass() != HttpStatusClass.INFORMATIONAL) { logBuilder.statusCode(status.code()); logBuilder.responseEnvelope(headers); } } else if (o instanceof HttpData) { logBuilder.increaseResponseLength(((HttpData) o).length()); } return delegate.write(o); }
public boolean write(HttpObject o){ if (o instanceof HttpHeaders) { logBuilder.startResponse(); final HttpHeaders headers = (HttpHeaders) o; final HttpStatus status = headers.status(); if (status != null && status.codeClass() != HttpStatusClass.INFORMATIONAL) { logBuilder.responseHeaders(headers); } } else if (o instanceof HttpData) { logBuilder.increaseResponseLength(((HttpData) o).length()); } return delegate.write(o); }
63
public String logout(){ Cookie[] cookies = request.getCookies(); for (Cookie c : cookies) { if (c.getName().equals("name")) { if (c.getValue() == null) { return "redirect:"; } } } cookie = new Cookie("name", ""); cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); return "redirect:"; }
public String logout(){ cookie = new Cookie("name", ""); cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); return "redirect:"; }
64
public int countDragons(ArrayList<Combination> win){ int count = 0; for (int i = 0; i < 4; i++) { if (win.get(i).getSuit() == 'H') { if (win.get(i).getTile(0).getRank() > 4) count++; } } return count; }
public int countDragons(ArrayList<Combination> win){ int count = 0; for (int i = 0; i < 4; i++) { if (isDragonTiles(win.get(i))) count++; } return count; }
65
private static String internalDecode(ProtonBuffer buffer, final int length, CharsetDecoder decoder){ final char[] chars = new char[length]; final int bufferInitialPosition = buffer.getReadIndex(); int offset; for (offset = 0; offset < length; offset++) { final byte b = buffer.getByte(bufferInitialPosition + offset); if (b < 0) { break; } chars[offset] = (char) b; } buffer.setReadIndex(bufferInitialPosition + offset); if (offset == length) { return new String(chars, 0, length); } else { return internalDecodeUTF8(buffer, length, chars, offset, decoder); } }
private static String internalDecode(ProtonBuffer buffer, final int length, CharsetDecoder decoder, char[] scratch){ final int bufferInitialPosition = buffer.getReadIndex(); int offset; for (offset = 0; offset < length; offset++) { final byte b = buffer.getByte(bufferInitialPosition + offset); if (b < 0) { break; } scratch[offset] = (char) b; } buffer.setReadIndex(bufferInitialPosition + offset); if (offset == length) { return new String(scratch, 0, length); } else { return internalDecodeUTF8(buffer, length, scratch, offset, decoder); } }
66
public PartyDTO getPartyByPartyCode(String partyCode){ if (Strings.isNullOrEmpty(partyCode)) throw new InvalidDataException("Party Code is required"); final TMsParty tMsParty = partyRepository.findByPrtyCodeAndPrtyStatus(partyCode, Constants.STATUS_ACTIVE.getShortValue()); if (tMsParty == null) throw new DataNotFoundException("Party not found for the Code : " + partyCode); PartyDTO partyDTO = PartyMapper.INSTANCE.entityToDTO(tMsParty); final List<PartyContactDTO> contactDTOList = partyContactService.getContactsByPartyCode(partyDTO.getPartyCode(), true); partyDTO.setContactList(contactDTOList); return partyDTO; }
public PartyDTO getPartyByPartyCode(String partyCode){ final TMsParty tMsParty = validateByPartyCode(partyCode); PartyDTO partyDTO = PartyMapper.INSTANCE.entityToDTO(tMsParty); setReferenceData(tMsParty, partyDTO); final List<PartyContactDTO> contactDTOList = partyContactService.getContactsByPartyCode(partyDTO.getPartyCode(), true); partyDTO.setContactList(contactDTOList); return partyDTO; }
67
public boolean checkRentalAvailable(Integer currentBookCnt){ if (this.rentalStatus != RentalStatus.RENT_UNAVAILABLE) { if (currentBookCnt + 1 > 5) { System.out.println("대출 가능한 도서의 수는 " + (5 - this.getRentedItems().size()) + "권 입니다."); return false; } else { return true; } } else { System.out.println("연체 상태입니다."); return false; } }
public boolean checkRentalAvailable(Integer newBookListCnt) throws Exception{ if (this.rentalStatus != RentalStatus.RENT_UNAVAILABLE) throw new Exception("연체 상태입니다."); if (this.getLateFee() == 0) throw new Exception("연체료를 정산 후, 도서를 대여하실 수 있습니다."); if (newBookListCnt + this.getRentedItems().size() <= 5) throw new Exception("대출 가능한 도서의 수는 " + (5 - this.getRentedItems().size()) + "권 입니다."); return true; }
68
public void contextDestroyed(ServletContextEvent sce){ tokenService.deleteAllInBatch(); System.out.println("Servlet Context is destroyed...."); }
public void contextDestroyed(ServletContextEvent sce){ System.out.println("Servlet Context is destroyed...."); }
69
public ValueTypeDTO getValueType(final String valueTypeIdentifier){ if (checkIfIndexExists(ELASTIC_INDEX_VALUETYPE)) { final ObjectMapper mapper = new ObjectMapper(); registerModulesToMapper(mapper); final SearchRequest searchRequest = new SearchRequest(); searchRequest.indices(ELASTIC_INDEX_VALUETYPE); searchRequest.types(ELASTIC_TYPE_VALUETYPE); final SearchSourceBuilder searchBuilder = new SearchSourceBuilder(); final BoolQueryBuilder builder = new BoolQueryBuilder().should(matchQuery("id", valueTypeIdentifier.toLowerCase())).should(matchQuery("localName", valueTypeIdentifier.toLowerCase()).analyzer(TEXT_ANALYZER)).minimumShouldMatch(1); searchBuilder.query(builder); searchRequest.source(searchBuilder); try { final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); if (response.getHits().getTotalHits() > 0) { final SearchHit hit = response.getHits().getAt(0); try { if (hit != null) { return mapper.readValue(hit.getSourceAsString(), ValueTypeDTO.class); } } catch (final IOException e) { LOG.error("getValueType reading value from JSON string failed: " + hit.getSourceAsString(), e); throw new JsonParsingException(ERR_MSG_USER_406); } } } catch (final IOException e) { LOG.error("SearchRequest failed!", e); throw new YtiCodeListException(new ErrorModel(HttpStatus.INTERNAL_SERVER_ERROR.value(), "ElasticSearch index query error!")); } } return null; }
public ValueTypeDTO getValueType(final String valueTypeIdentifier){ if (checkIfIndexExists(ELASTIC_INDEX_VALUETYPE)) { final ObjectMapper mapper = new ObjectMapper(); registerModulesToMapper(mapper); final SearchRequest searchRequest = createSearchRequest(ELASTIC_INDEX_VALUETYPE); final SearchSourceBuilder searchBuilder = new SearchSourceBuilder(); final BoolQueryBuilder builder = new BoolQueryBuilder().should(matchQuery("id", valueTypeIdentifier.toLowerCase())).should(matchQuery("localName", valueTypeIdentifier.toLowerCase()).analyzer(TEXT_ANALYZER)).minimumShouldMatch(1); searchBuilder.query(builder); searchRequest.source(searchBuilder); try { final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); if (response.getHits().getTotalHits() > 0) { final SearchHit hit = response.getHits().getAt(0); try { if (hit != null) { return mapper.readValue(hit.getSourceAsString(), ValueTypeDTO.class); } } catch (final IOException e) { LOG.error("getValueType reading value from JSON string failed: " + hit.getSourceAsString(), e); throw new JsonParsingException(ERR_MSG_USER_406); } } } catch (final IOException e) { LOG.error("SearchRequest failed!", e); throw new YtiCodeListException(new ErrorModel(HttpStatus.INTERNAL_SERVER_ERROR.value(), "ElasticSearch index query error!")); } } return null; }
70
public int getAgeSetIndex(CharID id){ BioSet bioSet = bioSetFacet.get(id); Optional<Region> region = regionFacet.getRegion(id); Race race = raceFacet.get(id); String raceName = race == null ? "" : race.getKeyName().trim(); List<String> values = bioSet.getValueInMaps(region, raceName, "BASEAGE"); if (values == null) { return 0; } int pcAge = ageFacet.getAge(id); int ageSet = -1; for (String s : values) { int setBaseAge = Integer.parseInt(s); if (pcAge < setBaseAge) { break; } ++ageSet; } if (ageSet < 0) { ageSet = 0; } return ageSet; }
public int getAgeSetIndex(CharID id){ BioSet bioSet = bioSetFacet.get(id); Optional<Region> region = regionFacet.getRegion(id); Race race = raceFacet.get(id); String raceName = race == null ? "" : race.getKeyName().trim(); List<String> values = bioSet.getValueInMaps(region, raceName, "BASEAGE"); if (values == null) { return 0; } int pcAge = ageFacet.get(id); int ageSet = -1; ageSet += values.stream().mapToInt(Integer::parseInt).takeWhile(setBaseAge -> pcAge >= setBaseAge).count(); if (ageSet < 0) { ageSet = 0; } return ageSet; }
71
private static Map<String, Object> overrideConfiguration(){ Map<String, Object> overrideData = new HashMap<String, Object>(); try { URI databaseURI = new URI(System.getenv("DATABASE_URL")); String username = "postgres"; String password = ""; if (databaseURI.getUserInfo() != null) { username = databaseURI.getUserInfo().split(":")[0]; password = databaseURI.getUserInfo().split(":")[1]; } String databaseURL = String.format("jdbc:postgresql://%s:%s%s", databaseURI.getHost(), databaseURI.getPort(), databaseURI.getPath()); if (databaseURI.getPath().contains("_test")) { overrideData.put("hibernate.hbm2ddl.auto", "create"); } overrideData.put("javax.persistence.jdbc.url", databaseURL); overrideData.put("javax.persistence.jdbc.user", username); overrideData.put("javax.persistence.jdbc.password", password); return overrideData; } catch (URISyntaxException e) { return overrideData; } catch (NullPointerException e) { return overrideData; } }
private static Map<String, Object> overrideConfiguration(){ Map<String, Object> overrideData = new HashMap<>(); try { URI databaseURI = new URI(System.getenv("DATABASE_URL")); String username = "postgres"; String password = ""; if (databaseURI.getUserInfo() != null) { username = databaseURI.getUserInfo().split(":")[0]; password = databaseURI.getUserInfo().split(":")[1]; } String databaseURL = String.format("jdbc:postgresql://%s:%s%s", databaseURI.getHost(), databaseURI.getPort(), databaseURI.getPath()); if (databaseURI.getPath().contains("_test")) { overrideData.put("hibernate.hbm2ddl.auto", "create"); } overrideData.put("javax.persistence.jdbc.url", databaseURL); overrideData.put("javax.persistence.jdbc.user", username); overrideData.put("javax.persistence.jdbc.password", password); return overrideData; } catch (URISyntaxException | NullPointerException e) { return overrideData; } }
72
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.fragment_alert_form, container, false); Button buttonPhoto = view.findViewById(R.id.take_photo_btn); Button buttonUploader = view.findViewById(R.id.upload_form); Button buttonPhotoChooser = view.findViewById(R.id.choose_photo_button); Button buttonLocalization = view.findViewById(R.id.enter_localization); buttonPhoto.setOnClickListener(this::onTakePhotoClick); buttonUploader.setOnClickListener(this::onFormUploadClick); buttonPhotoChooser.setOnClickListener(this::onChoosePhotoClick); buttonLocalization.setOnClickListener(this::onChooseLocalization); getLastLocation(); categorySpinner = view.findViewById(R.id.alert_form_category); populateCategorySpinner(); titleView = view.findViewById(R.id.alert_form_title); titleInvalidView = view.findViewById(R.id.alert_form_title_invalid); descriptionView = view.findViewById(R.id.alert_form_description); descriptionInvalidView = view.findViewById(R.id.alert_form_description_invalid); uploadedPhotoView = view.findViewById(R.id.uploaded_photo); photoUploadInfoView = view.findViewById(R.id.alert_image_info); photoUploadLayout = view.findViewById(R.id.photo_upload_constraint); localizationInvalid = view.findViewById(R.id.enter_localization_invalid); if (!checkCameraHardware(getActivity())) { photoUploadLayout.setVisibility(View.INVISIBLE); } else { uploadedPhotoView.setVisibility(View.INVISIBLE); } return view; }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view = inflater.inflate(R.layout.fragment_alert_form, container, false); Button buttonPhoto = view.findViewById(R.id.take_photo_btn); Button buttonUploader = view.findViewById(R.id.upload_form); Button buttonPhotoChooser = view.findViewById(R.id.choose_photo_button); Button buttonLocalization = view.findViewById(R.id.enter_localization); buttonPhoto.setOnClickListener(this::onTakePhotoClick); buttonUploader.setOnClickListener(this::onFormUploadClick); buttonPhotoChooser.setOnClickListener(this::onChoosePhotoClick); buttonLocalization.setOnClickListener(this::onChooseLocalization); categorySpinner = view.findViewById(R.id.alert_form_category); populateCategorySpinner(); titleView = view.findViewById(R.id.alert_form_title); titleInvalidView = view.findViewById(R.id.alert_form_title_invalid); descriptionView = view.findViewById(R.id.alert_form_description); descriptionInvalidView = view.findViewById(R.id.alert_form_description_invalid); uploadedPhotoView = view.findViewById(R.id.uploaded_photo); photoUploadInfoView = view.findViewById(R.id.alert_image_info); photoUploadLayout = view.findViewById(R.id.photo_upload_constraint); localizationInvalid = view.findViewById(R.id.enter_localization_invalid); if (!checkCameraHardware(getActivity())) { photoUploadLayout.setVisibility(View.INVISIBLE); } else { uploadedPhotoView.setVisibility(View.INVISIBLE); } return view; }
73
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ resp.setCharacterEncoding(DEFAULT_ENCODING); String parameter = req.getParameter(USER); StringBuilder sql = new StringBuilder("SELECT STRAIGHT_JOIN f.follower_email FROM").append(Helper.TABLE_USER).append("u FORCE INDEX (Name_email_id) ").append("INNER JOIN").append(Helper.TABLE_FOLLOWERS).append("f FORCE INDEX (following_follower) ").append("ON f.follower_email=u.email ").append("WHERE f.following_email=").append('\'').append(parameter).append("\' "); parameter = req.getParameter(SINCE_ID); if (parameter != null) sql.append(" AND u.id >= ").append(parameter); parameter = req.getParameter(ORDER); sql.append(" ORDER BY u.name "); if (parameter != null) sql.append(parameter); parameter = req.getParameter(LIMIT); if (parameter != null) sql.append(" LIMIT ").append(parameter); JsonArray followers = new JsonArray(); try (Connection connection = mHelper.getConnection()) { mHelper.runQuery(connection, sql.toString(), rs -> { while (rs.next()) { followers.add(getUserDetails(connection, rs.getString(1), true)); } }); } catch (SQLException e) { Errors.unknownError(resp.getWriter()); e.printStackTrace(); return; } Errors.correct(resp.getWriter(), followers); }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ resp.setCharacterEncoding(DEFAULT_ENCODING); String parameter = req.getParameter(USER); StringBuilder sql = new StringBuilder("SELECT * FROM ").append(DBHelper.TABLE_USER).append("u INNER JOIN (").append("SELECT DISTINCT follower_email FROM ").append(DBHelper.TABLE_FOLLOWERS).append("FORCE INDEX (following_follower) ").append("WHERE following_email=\'").append(parameter).append("\') f ").append("ON f.follower_email=u.email "); parameter = req.getParameter(SINCE_ID); if (parameter != null) sql.append(" AND u.id >= ").append(parameter); parameter = req.getParameter(ORDER); if (parameter != null) sql.append(" ORDER BY u.name ").append(parameter); parameter = req.getParameter(LIMIT); if (parameter != null) sql.append(" LIMIT ").append(parameter); JsonArray following; try (Connection connection = mHelper.getConnection()) { following = mHelper.runTypedQuery(connection, sql.toString(), rs -> getUsersDetails(connection, rs)); } catch (SQLException e) { Errors.unknownError(resp.getWriter()); e.printStackTrace(); return; } Errors.correct(resp.getWriter(), following); }
74
public HttpResponse<Void> ferdigstill(FerdigstillJournalpostRequest ferdigstillJournalpostRequest){ var oppdaterJoarnalpostApiUrl = URL_JOURNALPOSTAPI_V1 + '/' + ferdigstillJournalpostRequest.getJournalpostId() + "/ferdigstill"; var oppdaterJournalpostResponseEntity = restTemplate.exchange(oppdaterJoarnalpostApiUrl, HttpMethod.PATCH, new HttpEntity<>(ferdigstillJournalpostRequest), Void.class); return new HttpResponse<>(oppdaterJournalpostResponseEntity); }
public void ferdigstill(FerdigstillJournalpostRequest ferdigstillJournalpostRequest){ var oppdaterJoarnalpostApiUrl = URL_JOURNALPOSTAPI_V1 + '/' + ferdigstillJournalpostRequest.getJournalpostId() + "/ferdigstill"; restTemplate.exchange(oppdaterJoarnalpostApiUrl, HttpMethod.PATCH, new HttpEntity<>(ferdigstillJournalpostRequest), Void.class); }
75
private LogicalExpression materializeExpression(LogicalExpression expression, IterOutcome lastStatus, VectorAccessible input, ErrorCollector collector) throws ClassTransformationException{ LogicalExpression materializedExpr; if (lastStatus != IterOutcome.NONE) { materializedExpr = ExpressionTreeMaterializer.materialize(expression, input, collector, context.getFunctionRegistry(), unionTypeEnabled); } else { materializedExpr = new TypedNullConstant(Types.optional(MinorType.INT)); } if (collector.hasErrors()) { throw new ClassTransformationException(String.format("Failure while trying to materialize incoming field from %s batch. Errors:\n %s.", (input == leftIterator ? LEFT_INPUT : RIGHT_INPUT), collector.toErrorString())); } return materializedExpr; }
private LogicalExpression materializeExpression(LogicalExpression expression, IterOutcome lastStatus, VectorAccessible input, ErrorCollector collector){ LogicalExpression materializedExpr; if (lastStatus != IterOutcome.NONE) { materializedExpr = ExpressionTreeMaterializer.materialize(expression, input, collector, context.getFunctionRegistry(), unionTypeEnabled); } else { materializedExpr = new TypedNullConstant(Types.optional(MinorType.INT)); } collector.reportErrors(logger); return materializedExpr; }
76
public void processElement(ProcessContext c) throws IOException{ RecalibrationTables rt = c.element(); SAMFileHeader header = c.sideInput(headerView); File temp = IOUtils.createTempFile("temp-recalibrationtable-", ".tmp"); if (null == rt) { log.debug("Special case: zero reads in input."); StandardCovariateList covariates = new StandardCovariateList(toolArgs.RAC, header); int numReadGroups = header.getReadGroups().size(); RecalibrationEngine recalibrationEngine = new RecalibrationEngine(covariates, numReadGroups); rt = recalibrationEngine.getRecalibrationTables(); RecalibrationEngine.finalizeRecalibrationTables(rt); } try { BaseRecalibratorFn.saveTextualReport(temp, header, rt, toolArgs); BaseRecalOutput ret = new BaseRecalOutput(temp); c.output(ret); } catch (FileNotFoundException e) { throw new GATKException("can't find my own temporary file", e); } catch (IOException e) { throw new GATKException("unable to save temporary report to " + temp.getPath(), e); } }
public void processElement(ProcessContext c) throws IOException{ RecalibrationTables rt = c.element(); SAMFileHeader header = c.sideInput(headerView); File temp = IOUtils.createTempFile("temp-recalibrationtable-", ".tmp"); if (null == rt) { log.debug("Special case: zero reads in input."); BaseRecalibrationEngine recalibrationEngine = new BaseRecalibrationEngine(recalArgs, header); rt = recalibrationEngine.getRecalibrationTables(); BaseRecalibrationEngine.finalizeRecalibrationTables(rt); } try { BaseRecalibratorFn.saveTextualReport(temp, header, rt, recalArgs); BaseRecalOutput ret = new BaseRecalOutput(temp); c.output(ret); } catch (FileNotFoundException e) { throw new GATKException("can't find my own temporary file", e); } catch (IOException e) { throw new GATKException("unable to save temporary report to " + temp.getPath(), e); } }
77
public void shouldAppendToStream() throws Exception{ when(eventRepository.getCurrentSequenceIdForStream(STREAM_ID)).thenReturn(INITIAL_VERSION); eventStreamManager.append(STREAM_ID, singletonList(envelope().with(metadataOf(ID_VALUE, NAME_VALUE)).withPayloadOf(PAYLOAD_FIELD_VALUE, PAYLOAD_FIELD_NAME).build()).stream()); long expectedVersion = INITIAL_VERSION + 1; ArgumentCaptor<JsonEnvelope> envelopeArgumentCaptor = ArgumentCaptor.forClass(JsonEnvelope.class); ArgumentCaptor<UUID> streamIdCaptor = ArgumentCaptor.forClass(UUID.class); ArgumentCaptor<Long> versionCaptor = ArgumentCaptor.forClass(Long.class); verify(eventRepository).store(envelopeArgumentCaptor.capture(), streamIdCaptor.capture(), versionCaptor.capture()); verify(eventPublisher).publish(envelopeArgumentCaptor.capture()); assertThat(streamIdCaptor.getValue(), equalTo(STREAM_ID)); assertThat(versionCaptor.getValue(), equalTo(expectedVersion)); assertThat(envelopeArgumentCaptor.getValue(), jsonEnvelope(metadata().withVersion(expectedVersion).withId(ID_VALUE).withName(NAME_VALUE).withStreamId(STREAM_ID), payloadIsJson(withJsonPath(format("$.%s", PAYLOAD_FIELD_NAME), equalTo(PAYLOAD_FIELD_VALUE))))); }
public void shouldAppendToStream() throws Exception{ when(eventRepository.getCurrentSequenceIdForStream(STREAM_ID)).thenReturn(INITIAL_VERSION); eventStreamManager.append(STREAM_ID, Stream.of(envelope().with(metadataOf(ID_VALUE, NAME_VALUE)).withPayloadOf(PAYLOAD_FIELD_VALUE, PAYLOAD_FIELD_NAME).build())); long expectedVersion = INITIAL_VERSION + 1; ArgumentCaptor<JsonEnvelope> envelopeArgumentCaptor = ArgumentCaptor.forClass(JsonEnvelope.class); verify(eventRepository).store(envelopeArgumentCaptor.capture()); verify(eventPublisher).publish(envelopeArgumentCaptor.capture()); assertThat(envelopeArgumentCaptor.getValue(), jsonEnvelope(metadata().withVersion(expectedVersion).withId(ID_VALUE).withName(NAME_VALUE).withStreamId(STREAM_ID), payloadIsJson(withJsonPath(format("$.%s", PAYLOAD_FIELD_NAME), equalTo(PAYLOAD_FIELD_VALUE))))); }
78
public NBTTagCompound getUpdateTag(){ final NBTTagCompound tagCompound = new NBTTagCompound(); writeToNBT(tagCompound); tagCompound.removeTag(ICoreSignature.UUID_MOST_TAG); tagCompound.removeTag(ICoreSignature.UUID_LEAST_TAG); tagCompound.removeTag(IBeamFrequency.BEAM_FREQUENCY_TAG); return tagCompound; }
public NBTTagCompound getUpdateTag(){ final NBTTagCompound tagCompound = super.getUpdateTag(); tagCompound.removeTag(ICoreSignature.UUID_MOST_TAG); tagCompound.removeTag(ICoreSignature.UUID_LEAST_TAG); tagCompound.removeTag(IBeamFrequency.BEAM_FREQUENCY_TAG); return tagCompound; }
79
public int search(int[] A, int target){ if (A.length == 0) return -1; int start = 0; int end = A.length - 1; while (start < end) { int mid = (start + end) / 2; if (A[mid] == target) return mid; if (A[start] <= A[mid]) { if (target >= A[start] && target < A[mid]) { end = mid - 1; } else { start = mid + 1; } } else { if (target > A[mid] && target <= A[end]) { start = mid + 1; } else { end = mid - 1; } } } return A[start] == target ? start : -1; }
public int search(int[] A, int target){ if (A.length == 0) return -1; int start = 0; int end = A.length - 1; while (start < end) { int mid = (start + end) / 2; if (A[mid] == target) return mid; if (A[start] <= A[mid]) { if (target >= A[start] && target < A[mid]) end = mid - 1; else start = mid + 1; } else { if (target > A[mid] && target <= A[end]) { start = mid + 1; } else { end = mid - 1; } } } return A[start] == target ? start : -1; }
80
private void setReadMarkers(final String aReadMarkerEventId, final String aReadReceiptEventId, final ApiCallback<Void> callback){ Log.d(LOG_TAG, "## setReadMarkers(): readMarkerEventId " + aReadMarkerEventId + " readReceiptEventId " + aReadMarkerEventId); final String readMarkerEventId = MXSession.isMessageId(aReadMarkerEventId) ? aReadMarkerEventId : null; final String readReceiptEventId = MXSession.isMessageId(aReadReceiptEventId) ? aReadReceiptEventId : null; if (TextUtils.isEmpty(readMarkerEventId) && TextUtils.isEmpty(readReceiptEventId)) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (null != callback) { callback.onSuccess(null); } } }); } else { mDataHandler.getDataRetriever().getRoomsRestClient().sendReadMarker(getRoomId(), readMarkerEventId, readReceiptEventId, new ApiCallback<Void>() { @Override public void onSuccess(Void info) { if (null != callback) { callback.onSuccess(info); } } @Override public void onNetworkError(Exception e) { if (null != callback) { callback.onNetworkError(e); } } @Override public void onMatrixError(MatrixError e) { if (null != callback) { callback.onMatrixError(e); } } @Override public void onUnexpectedError(Exception e) { if (null != callback) { callback.onUnexpectedError(e); } } }); } }
private void setReadMarkers(final String aReadMarkerEventId, final String aReadReceiptEventId, final ApiCallback<Void> callback){ Log.d(LOG_TAG, "## setReadMarkers(): readMarkerEventId " + aReadMarkerEventId + " readReceiptEventId " + aReadMarkerEventId); final String readMarkerEventId = MXSession.isMessageId(aReadMarkerEventId) ? aReadMarkerEventId : null; final String readReceiptEventId = MXSession.isMessageId(aReadReceiptEventId) ? aReadReceiptEventId : null; if (TextUtils.isEmpty(readMarkerEventId) && TextUtils.isEmpty(readReceiptEventId)) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { if (null != callback) { callback.onSuccess(null); } } }); } else { mDataHandler.getDataRetriever().getRoomsRestClient().sendReadMarker(getRoomId(), readMarkerEventId, readReceiptEventId, new SimpleApiCallback<Void>(callback) { @Override public void onSuccess(Void info) { if (null != callback) { callback.onSuccess(info); } } }); } }
81
public String panel(Model model, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer size, @RequestParam(defaultValue = "id") String sortBy, @RequestParam(defaultValue = "true") Boolean asc){ String userEmail = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userService.getUserByEmail(userEmail); Page<Donation> donationPage; if (asc) { donationPage = donationService.getAllByUserSotred(user, PageRequest.of(page - 1, size, Sort.Direction.ASC, sortBy)); } else { donationPage = donationService.getAllByUserSotred(user, PageRequest.of(page - 1, size, Sort.Direction.DESC, sortBy)); } int totalPages = donationPage.getTotalPages(); if (totalPages > 0) { List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages).boxed().collect(Collectors.toList()); model.addAttribute("pageNumbers", pageNumbers); } model.addAttribute("donations", donationPage); return "user/donations"; }
public String panel(@AuthenticationPrincipal User authUser, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer size, @RequestParam(defaultValue = "id") String sortBy, @RequestParam(defaultValue = "true") Boolean asc, Model model){ User user = userService.getUserByEmail(authUser.getEmail()); Page<Donation> donationPage; if (asc) { donationPage = donationService.getAllByUserSotred(user, PageRequest.of(page - 1, size, Sort.Direction.ASC, sortBy)); } else { donationPage = donationService.getAllByUserSotred(user, PageRequest.of(page - 1, size, Sort.Direction.DESC, sortBy)); } int totalPages = donationPage.getTotalPages(); if (totalPages > 0) { List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages).boxed().collect(Collectors.toList()); model.addAttribute("pageNumbers", pageNumbers); } model.addAttribute("donations", donationPage); return "user/donations"; }
82
public Result updateProject(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("projectId") Integer projectId, @RequestParam("projectName") String projectName, @RequestParam(value = "description", required = false) String description){ logger.info("login user {} , updateProcessInstance project name: {}, desc: {}", loginUser.getUserName(), projectName, description); Map<String, Object> result = projectService.update(loginUser, projectId, projectName, description); return returnDataList(result); }
public Result<Void> updateProject(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("projectId") Integer projectId, @RequestParam("projectName") String projectName, @RequestParam(value = "description", required = false) String description){ logger.info("login user {} , updateProcessInstance project name: {}, desc: {}", loginUser.getUserName(), projectName, description); return projectService.update(loginUser, projectId, projectName, description); }
83
public List<BusinessUnitDTO> findAllSortedBUDTO(@RequestParam(value = QueryConstants.SORT_BY) final String sortBy, @RequestParam(value = QueryConstants.SORT_ORDER) final String sortOrder){ List<BusinessUnitDTO> returnList = new ArrayList<>(); for (Iterator<BusinessUnit> iterBU = findAllSortedInternal(sortBy, sortOrder).listIterator(); iterBU.hasNext(); ) { BusinessUnit currentBU = iterBU.next(); BusinessUnitDTO businessUnitDTO = buildBusinessUnitDTO(currentBU); for (Iterator<BusinessUnitConfigurationPreference> iterBUCP = currentBU.getBusinessUnitConfigurationPreferences().listIterator(); iterBUCP.hasNext(); ) { BusinessUnitConfigurationPreference currentBUCP = iterBUCP.next(); BusinessUnitConfigPreferenceDTO businessUnitConfigPreferenceDTO = buildBusinessConfigPreferenceDTO(currentBUCP); businessUnitDTO.addBusinessUnitConfigPreferenceDTO(businessUnitConfigPreferenceDTO); } returnList.add(businessUnitDTO); } return returnList; }
public List<BusinessUnitDTO> findAllSortedBUDTO(@RequestParam(value = QueryConstants.SORT_BY) final String sortBy, @RequestParam(value = QueryConstants.SORT_ORDER) final String sortOrder){ List<BusinessUnitDTO> returnList = buildBuindessUnitDTOList(findAllSortedInternal(sortBy, sortOrder)); return returnList; }
84
public void testPythonMultipleOutputs() throws Exception{ Operation additionSubtraction = new PythonScriptOperation(PythonTest.class.getResource("/edu/wpi/grip/scripts/addition-subtraction.py")); Step step = new Step.Factory(eventBus, (origin) -> new MockExceptionWitness(eventBus, origin)).create(additionSubtraction); Socket aSocket = step.getInputSockets().get(0); Socket bSocket = step.getInputSockets().get(1); Socket sumSocket = step.getOutputSockets().get(0); Socket differenceSocket = step.getOutputSockets().get(1); aSocket.setValue(a); bSocket.setValue(b); step.runPerformIfPossible(); assertEquals("Value was not assigned after run", a + b, sumSocket.getValue().get()); assertEquals("Value was not assigned after run", a - b, differenceSocket.getValue().get()); }
public void testPythonMultipleOutputs() throws Exception{ Step step = new Step.Factory((origin) -> new MockExceptionWitness(eventBus, origin)).create(PythonScriptFile.create(PythonTest.class.getResource("/edu/wpi/grip/scripts/addition-subtraction.py")).toOperationMetaData(isf, osf)); Socket aSocket = step.getInputSockets().get(0); Socket bSocket = step.getInputSockets().get(1); Socket sumSocket = step.getOutputSockets().get(0); Socket differenceSocket = step.getOutputSockets().get(1); aSocket.setValue(a); bSocket.setValue(b); step.runPerformIfPossible(); assertEquals("Value was not assigned after run", a + b, sumSocket.getValue().get()); assertEquals("Value was not assigned after run", a - b, differenceSocket.getValue().get()); }
85
public List<Match> getNonOverlappingMatches(Clause clause){ var skipList = memoTable.get(clause); if (skipList == null) { return Collections.emptyList(); } var firstEntry = skipList.firstEntry(); var nonoverlappingMatches = new ArrayList<Match>(); if (firstEntry != null) { for (var ent = firstEntry; ent != null; ) { var startPos = ent.getKey(); var memoEntry = ent.getValue(); if (memoEntry.bestMatch != null) { nonoverlappingMatches.add(memoEntry.bestMatch); ent = skipList.higherEntry(startPos + Math.max(1, memoEntry.bestMatch.len) - 1); } else { ent = skipList.higherEntry(startPos); } } } return nonoverlappingMatches; }
public List<Match> getNonOverlappingMatches(Clause clause){ var skipList = memoTable.get(clause); if (skipList == null) { return Collections.emptyList(); } var firstEntry = skipList.firstEntry(); var nonoverlappingMatches = new ArrayList<Match>(); if (firstEntry != null) { for (var ent = firstEntry; ent != null; ) { var startPos = ent.getKey(); var match = ent.getValue(); nonoverlappingMatches.add(match); ent = skipList.higherEntry(startPos + Math.max(1, match.len) - 1); } } return nonoverlappingMatches; }
86
public boolean onTouchEvent(MotionEvent event){ int actionMasked = MotionEventCompat.getActionMasked(event); switch(event.getAction() & actionMasked) { case MotionEvent.ACTION_DOWN: { startClickTime = SystemClock.currentThreadTimeMillis(); break; } case MotionEvent.ACTION_UP: { long clickDuration = SystemClock.currentThreadTimeMillis() - startClickTime; if (clickDuration < MAX_CLICK_DURATION) { if (!animatorSet.isRunning()) { cx = event.getX(); cy = event.getY(); ripple(); } } } } return super.onTouchEvent(event); }
public boolean onTouchEvent(MotionEvent event){ int actionMasked = MotionEventCompat.getActionMasked(event); switch(event.getAction() & actionMasked) { case MotionEvent.ACTION_DOWN: { cx = event.getX(); cy = event.getY(); ripple(); break; } } return super.onTouchEvent(event); }
87
public static long findMyBoardingPass(String fileName){ List<String> passes = readInBoardingPasses(fileName); List<Long> seatIds = passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.toList()); long mySeatId = -1; for (Long seatId : seatIds) { if (mySeatId == -1) { mySeatId = seatId; continue; } if (seatId > mySeatId + 1) { mySeatId++; break; } mySeatId = seatId; } return mySeatId; }
public static long findMyBoardingPass(String fileName){ List<String> passes = readInBoardingPasses(fileName); return passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.reducing(-1, (mySeatId, seatId) -> (mySeatId.longValue() == -1L || seatId.longValue() <= mySeatId.longValue() + 1) ? seatId : mySeatId)).longValue() + 1L; }
88
public void onNext(Integer t){ try { Thread.sleep(1); } catch (InterruptedException e) { } if (counter.getAndIncrement() % 100 == 0) { System.out.print("testIssue2890NoStackoverflow -> "); System.out.println(counter.get()); } ; }
public void onNext(Integer t){ try { Thread.sleep(1); } catch (InterruptedException e) { } if (counter.getAndIncrement() % 100 == 0) { System.out.print("testIssue2890NoStackoverflow -> "); System.out.println(counter.get()); } }
89
public Set<Car> findAllByOwnerId(long id) throws SQLException, NamingException{ Context ctx = new InitialContext(); Context envContext = (Context) ctx.lookup("java:comp/env"); DataSource dataSource = (DataSource) envContext.lookup("jdbc/TestDB"); Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllCarsByOwnerIdStatement = con.prepareStatement("SELECT * FROM cars WHERE owner_id = ?"); findAllCarsByOwnerIdStatement.setLong(1, id); ResultSet cars = findAllCarsByOwnerIdStatement.executeQuery(); Set<Car> carSet = new HashSet(); while (cars.next()) { Car car = CarUtils.initializeCar(cars); carSet.add(car); } findAllCarsByOwnerIdStatement.close(); cars.close(); return carSet; } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }
public Set<Car> findAllByOwnerId(long id) throws SQLException, NamingException{ Connection con = null; try { con = dataSource.getConnection(); PreparedStatement findAllCarsByOwnerIdStatement = con.prepareStatement("SELECT * FROM cars WHERE owner_id = ?"); findAllCarsByOwnerIdStatement.setLong(1, id); ResultSet cars = findAllCarsByOwnerIdStatement.executeQuery(); Set<Car> carSet = new HashSet(); while (cars.next()) { Car car = CarUtils.initializeCar(cars); carSet.add(car); } findAllCarsByOwnerIdStatement.close(); cars.close(); return carSet; } finally { if (con != null) try { con.close(); } catch (Exception ignore) { } } }
90
public int reserveGameId(){ Statement statement = null; ResultSet result = null; try { statement = connection.createStatement(); statement.executeUpdate("INSERT INTO games () VALUES ()"); result = statement.executeQuery("SELECT LAST_INSERT_ID();"); if (result.next()) { return result.getInt("LAST_INSERT_ID()"); } } catch (SQLException e) { System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); e.printStackTrace(); } finally { if (result != null) { try { result.close(); } catch (SQLException e) { } } if (statement != null) { try { statement.close(); } catch (SQLException e) { } } } return -1; }
public int reserveGameId(){ return errorHandler(-1, (statement, result) -> { statement = connection.createStatement(); statement.executeUpdate("INSERT INTO games () VALUES ()"); result = statement.executeQuery("SELECT LAST_INSERT_ID();"); if (result.next()) { return result.getInt("LAST_INSERT_ID()"); } else { return -1; } }); }
91
public void buildtrace(ByteCodeGraph graph){ StmtNode stmt = buildstmt(graph); ParseInfo info = graph.parseinfo; List<Node> prednodes = new ArrayList<Node>(); List<Node> usenodes = new ArrayList<Node>(); Node defnode = null; int varindex = info.getintvalue("VAR"); int incconst = info.getintvalue("CONST"); String nodename = graph.getFormalVarNameWithIndex(varindex); usenodes.add(graph.getNode(nodename)); graph.incVarIndex(varindex); nodename = graph.getFormalVarNameWithIndex(varindex); defnode = new Node(nodename, graph.testname, stmt); graph.addNode(nodename, defnode); if (defnode != null) { graph.buildFactor(defnode, prednodes, usenodes, null, stmt); if (graph.auto_oracle) { graph.last_defined_var = defnode; } } }
public void buildtrace(ByteCodeGraph graph){ StmtNode stmt = buildstmt(graph); ParseInfo info = graph.parseinfo; List<Node> prednodes = new ArrayList<Node>(); List<Node> usenodes = new ArrayList<Node>(); Node defnode = null; int varindex = info.getintvalue("VAR"); int incconst = info.getintvalue("CONST"); String nodename = graph.getFormalVarNameWithIndex(varindex); usenodes.add(graph.getNode(nodename)); defnode = graph.addNewVarNode(varindex, stmt); if (defnode != null) { graph.buildFactor(defnode, prednodes, usenodes, null, stmt); if (graph.auto_oracle) { graph.last_defined_var = defnode; } } }
92
public void Execute(Rover rover, Plateau plateau) throws ProgramException{ for (char command : getCommands().toCharArray()) { switch(command) { case 'L': rover.setDirection(Direction.GetLeft(rover.getDirection())); break; case 'R': rover.setDirection(Direction.GetRight(rover.getDirection())); break; case 'M': try { rover.getPosition().moveToDirection(rover.getDirection(), plateau); } catch (ProgramException p) { System.err.println(p.getMessage()); } break; default: throw new ProgramException(String.format("Error: Command %c not found", command)); } } }
public void Execute(Rover rover, Plateau plateau) throws ProgramException{ for (char command : getCommands().toCharArray()) { switch(command) { case 'L': rover.setDirection(Direction.GetLeft(rover.getDirection())); break; case 'R': rover.setDirection(Direction.GetRight(rover.getDirection())); break; case 'M': rover.getPosition().moveToDirection(rover.getDirection(), plateau); break; default: throw new ProgramException(String.format("Error: Command %c not found", command)); } } }
93
public void onVspReceiveData(BluetoothGatt gatt, BluetoothGattCharacteristic ch){ mRxBuffer.write(ch.getStringValue(0)); while (mRxBuffer.read(mRxDest, "\r") != 0) { Log.i(TAG, "Data received: " + StringEscapeUtils.escapeJava(mRxDest.toString())); switch(mFifoAndVspManagerState) { case UPLOADING: if (mRxDest.toString().contains("\n00\r")) { mRxDest.delete(0, mRxDest.length()); } else if (mRxDest.toString().contains("\n01\t")) { String errorCode = mRxDest.toString(); mRxDest.delete(0, mRxDest.length()); errorCode = DataManipulation.stripStringValue("\t", "\r", errorCode); onUploadFailed(errorCode); } break; default: break; } } }
public void onVspReceiveData(BluetoothGatt gatt, BluetoothGattCharacteristic ch){ mRxBuffer.write(ch.getStringValue(0)); while (mRxBuffer.read(mRxDest, "\r") != 0) { Log.i(TAG, "Data received: " + StringEscapeUtils.escapeJava(mRxDest.toString())); if (mFifoAndVspManagerState == FifoAndVspManagerState.UPLOADING) { if (mRxDest.toString().contains("\n00\r")) { mRxDest.delete(0, mRxDest.length()); } else if (mRxDest.toString().contains("\n01\t")) { String errorCode = mRxDest.toString(); mRxDest.delete(0, mRxDest.length()); errorCode = DataManipulation.stripStringValue("\t", "\r", errorCode); onUploadFailed(errorCode); } } } }
94
protected BrokerPool startDB(){ try { Configuration config = new Configuration(); BrokerPool.configure(1, 5, config); return BrokerPool.getInstance(); } catch (Exception e) { fail(e.getMessage()); } return null; }
protected BrokerPool startDB() throws DatabaseConfigurationException, EXistException{ final Configuration config = new Configuration(); BrokerPool.configure(1, 5, config); return BrokerPool.getInstance(); }
95
public String getEncryptedData(String alias){ if (alias == null || "".equals(alias)) { return alias; } if (!initialize || encryptedData.isEmpty()) { if (log.isDebugEnabled()) { log.debug("There is no secret found for alias '" + alias + "' returning itself"); } return alias; } StringBuffer sb = new StringBuffer(); sb.append(alias); String encryptedValue = encryptedData.get(sb.toString()); if (encryptedValue == null || "".equals(encryptedValue)) { if (log.isDebugEnabled()) { log.debug("There is no secret found for alias '" + alias + "' returning itself"); } return alias; } return encryptedValue; }
public String getEncryptedData(String alias){ if (alias == null || "".equals(alias)) { return alias; } if (!initialize || encryptedData.isEmpty()) { if (log.isDebugEnabled()) { log.debug("There is no secret found for alias '" + alias + "' returning itself"); } return alias; } String encryptedValue = encryptedData.get(alias); if (encryptedValue == null || "".equals(encryptedValue)) { if (log.isDebugEnabled()) { log.debug("There is no secret found for alias '" + alias + "' returning itself"); } return alias; } return encryptedValue; }
96
public static PrivateKey readKeyFile(String filePath) throws IOException, PKCSException, NoSuchAlgorithmException, InvalidKeySpecException{ Security.addProvider(new BouncyCastleProvider()); File file = ResourceUtils.getFile(filePath); logger.info(String.format("path is %s and %s and %s ", filePath, file.exists(), file)); PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(file))); KeyFactory factory = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()); byte[] content = pemReader.readPemObject().getContent(); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content); return factory.generatePrivate(privKeySpec); }
public static PrivateKey readKeyFile(String filePath) throws IOException, PKCSException, NoSuchAlgorithmException, InvalidKeySpecException{ Security.addProvider(new BouncyCastleProvider()); File file = ResourceUtils.getFile(filePath); PemReader pemReader = new PemReader(new InputStreamReader(new FileInputStream(file))); KeyFactory factory = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()); byte[] content = pemReader.readPemObject().getContent(); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content); return factory.generatePrivate(privKeySpec); }
97
public synchronized int read(byte[] data){ this.data = data; this.header = getHeaderParser().setData(data).parseHeader(); if (data != null) { rawData = ByteBuffer.wrap(data); rawData.rewind(); rawData.order(ByteOrder.LITTLE_ENDIAN); mainPixels = new byte[header.width * header.height]; mainScratch = new int[header.width * header.height]; savePrevious = false; for (GifFrame frame : header.frames) { if (frame.dispose == DISPOSAL_PREVIOUS) { savePrevious = true; break; } } } return status; }
public synchronized int read(byte[] data){ this.header = getHeaderParser().setData(data).parseHeader(); if (data != null) { rawData = ByteBuffer.wrap(data); rawData.rewind(); rawData.order(ByteOrder.LITTLE_ENDIAN); mainPixels = new byte[header.width * header.height]; mainScratch = new int[header.width * header.height]; savePrevious = false; for (GifFrame frame : header.frames) { if (frame.dispose == DISPOSAL_PREVIOUS) { savePrevious = true; break; } } } return status; }
98
public void terminateFault(){ System.out.println("TerminateFault: Begin"); dispenseCtrl.allowSelection(false); coinReceiver.refundCash(); mediator.controllerChanged(this, new MediatorNotification(NotificationType.RefreshMachineryPanel)); System.out.println("TerminateFault: End"); }
public void terminateFault(){ System.out.println("TerminateFault: Begin"); dispenseCtrl.allowSelection(false); mediator.controllerChanged(this, new MediatorNotification(NotificationType.RefreshMachineryPanel)); System.out.println("TerminateFault: End"); }
99
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.createSampleData(); this.getSupportFragmentManager().registerFragmentLifecycleCallbacks(new FragmentLifecycleCallbacks(), false); if (savedInstanceState == null) { this.getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, ShoppingListFragment.newInstance(), FRAGMENT_SHOPPING_LIST).commit(); } this.mDrawerLayout = findViewById(R.id.drawer_layout); this.mDrawer = findViewById(R.id.drawer); this.mToolbar = findViewById(R.id.toolbar); this.setSupportActionBar(this.mToolbar); this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); this.mDrawer.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { return MainActivity.this.onDrawerMenuItemSelected(item); } }); this.mFab = findViewById(R.id.fab_plus); this.mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainActivity.this.onFabClick((FloatingActionButton) view); } }); this.mDrawerToggle = new ActionBarDrawerToggle(this, this.mDrawerLayout, R.string.message_drawer_open, R.string.message_drawer_close); this.mDrawerLayout.addDrawerListener(this.mDrawerToggle); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.getSupportFragmentManager().registerFragmentLifecycleCallbacks(new FragmentLifecycleCallbacks(), false); if (savedInstanceState == null) { this.getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, ShoppingListFragment.newInstance(), FRAGMENT_SHOPPING_LIST).commit(); } this.mDrawerLayout = findViewById(R.id.drawer_layout); this.mDrawer = findViewById(R.id.drawer); this.mToolbar = findViewById(R.id.toolbar); this.setSupportActionBar(this.mToolbar); this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); this.mDrawer.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { return MainActivity.this.onDrawerMenuItemSelected(item); } }); this.mFab = findViewById(R.id.fab_plus); this.mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainActivity.this.onFabClick((FloatingActionButton) view); } }); this.mDrawerToggle = new ActionBarDrawerToggle(this, this.mDrawerLayout, R.string.message_drawer_open, R.string.message_drawer_close); this.mDrawerLayout.addDrawerListener(this.mDrawerToggle); }