Unnamed: 0
int64
0
9.45k
cwe_id
stringclasses
1 value
source
stringlengths
37
2.53k
target
stringlengths
19
2.4k
300
public Map<String, SubmoduleStatus> call() throws GitAPIException{ checkCallable(); try (SubmoduleWalk generator = SubmoduleWalk.forIndex(repo)) { if (!paths.isEmpty()) generator.setFilter(PathFilterGroup.createFromStrings(paths)); Map<String, SubmoduleStatus> statuses = new HashMap<>(); while (generator.next()) { SubmoduleStatus status = getStatus(generator); statuses.put(status.getPath(), status); } return statuses; } catch (IOException e) { throw new JGitInternalException(e.getMessage(), e); } catch (ConfigInvalidException e) { throw new JGitInternalException(e.getMessage(), e); } }
public Map<String, SubmoduleStatus> call() throws GitAPIException{ checkCallable(); try (SubmoduleWalk generator = SubmoduleWalk.forIndex(repo)) { if (!paths.isEmpty()) generator.setFilter(PathFilterGroup.createFromStrings(paths)); Map<String, SubmoduleStatus> statuses = new HashMap<>(); while (generator.next()) { SubmoduleStatus status = getStatus(generator); statuses.put(status.getPath(), status); } return statuses; } catch (IOException | ConfigInvalidException e) { throw new JGitInternalException(e.getMessage(), e); } }
301
public ExtractedFileSet extract(DownloadConfig runtime, File source, FilesToExtract toExtract) throws IOException{ Builder builder = ExtractedFileSet.builder(toExtract.baseDir()).baseDirIsGenerated(toExtract.baseDirIsGenerated()); ProgressListener progressListener = runtime.getProgressListener(); String progressLabel = "Extract (not really) " + source; progressListener.start(progressLabel); IExtractionMatch match = toExtract.find(new FileAsArchiveEntry(source)); if (match != null) { FileInputStream fin = new FileInputStream(source); try { BufferedInputStream in = new BufferedInputStream(fin); File file = match.write(in, source.length()); FileType type = match.type(); if (type == FileType.Executable) { builder.executable(file); } else { builder.addLibraryFiles(file); } if (!toExtract.nothingLeft()) { progressListener.info(progressLabel, "Something went a little wrong. Listener say something is left, but we dont have anything"); } progressListener.done(progressLabel); } finally { fin.close(); } } return builder.build(); }
public ExtractedFileSet extract(DownloadConfig runtime, File source, FilesToExtract toExtract) throws IOException{ Builder builder = ExtractedFileSet.builder(toExtract.baseDir()).baseDirIsGenerated(toExtract.baseDirIsGenerated()); ProgressListener progressListener = runtime.getProgressListener(); String progressLabel = "Extract (not really) " + source; progressListener.start(progressLabel); IExtractionMatch match = toExtract.find(new FileAsArchiveEntry(source)); if (match != null) { try (FileInputStream fin = new FileInputStream(source); BufferedInputStream in = new BufferedInputStream(fin)) { File file = match.write(in, source.length()); FileType type = match.type(); if (type == FileType.Executable) { builder.executable(file); } else { builder.addLibraryFiles(file); } if (!toExtract.nothingLeft()) { progressListener.info(progressLabel, "Something went a little wrong. Listener say something is left, but we dont have anything"); } progressListener.done(progressLabel); } } return builder.build(); }
302
public String trackAllStuffByStuffTypes(Model model, @PathVariable("stuffType.id") Long stuffTypeId, HttpSession session){ 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("active", "active"); Long currUserId = (Long) session.getAttribute("currUserId"); User user = userService.getById(currUserId); model.addAttribute("userLogo", user.getName()); StuffType stuffType = stuffTypeService.getById(stuffTypeId); model.addAttribute("h1name", "Переглянути всі - " + stuffType.getType()); model.addAttribute("stuffBySubdv", stuffService.findAllStuffByStuffType(stuffType)); return "/stuff/trackAllBySubdivision"; }
public String trackAllStuffByStuffTypes(Model model, @PathVariable("stuffType.id") Long stuffTypeId, HttpSession session){ List<Buttons> buttons = buttonsService.getAllWhereParentIdIsNull(new Sort(Sort.Direction.ASC, "id")); model.addAttribute("buttons", buttons); List<Buttons> button = buttonsService.getAllWhereParentIdIsNotNull(); model.addAttribute("button", button); StuffType stuffType = stuffTypeService.getById(stuffTypeId); model.addAttribute("h1name", "Переглянути всі - " + stuffType.getType()); model.addAttribute("stuffBySubdv", stuffService.findAllStuffByStuffType(stuffType)); return "/stuff/trackAllBySubdivision"; }
303
public void getBugHTML() throws ServletException, IOException{ final String bugURI = getRequestURI(); final Model model = getBugModel(getRequestURI()); setBugResponseHeaders(); final String etag = ETag.generate(model); testIfNoneMatch(etag); setETagHeader(etag); setBugAttributes(model, bugURI); request.getRequestDispatcher("/WEB-INF/bug.jsp").forward(request, response); }
public void getBugHTML() throws ServletException, IOException{ final String bugURI = getRequestURI(); final Model model = getBugModel(getRequestURI()); setBugResponseHeaders(); handleETags(model); setBugAttributes(model, bugURI); request.getRequestDispatcher("/WEB-INF/bug.jsp").forward(request, response); }
304
public ArrayList<Person> readFile(){ ArrayList<Person> records = new ArrayList<Person>(); Scanner in; try { in = new Scanner(new FileInputStream(this.fileName), "UTF-8"); in.nextLine(); while (in.hasNext()) { String line = in.nextLine(); String[] fields = line.split("\\,"); if (fields.length > 1) { Person person = new Person(Integer.parseInt(fields[0]), fields[1], fields[2], fields[3], fields[4]); records.add(person); } } in.close(); } catch (FileNotFoundException e) { System.out.println("Error reading File " + this.fileName); e.printStackTrace(); } return records; }
public ArrayList<Person> readFile(){ ArrayList<Person> records = new ArrayList<Person>(); Scanner in; try { in = new Scanner(new FileInputStream(this.fileName), "UTF-8"); in.nextLine(); while (in.hasNext()) { Person personRecord = mapLineToRecord(in.nextLine()); if (personRecord != null) records.add(personRecord); } in.close(); } catch (FileNotFoundException e) { System.out.println("Error reading File " + this.fileName); e.printStackTrace(); } return records; }
305
public FormattedParameters checkParams(ExecRootBlock _rootBlock, String _classNameFound, Argument _previous, Cache _cache, ContextEl _conf, MethodAccessKind _kind, StackCall _stackCall){ LgNames stds_ = _conf.getStandards(); String cast_ = stds_.getContent().getCoreNames().getAliasCastType(); String classFormat_ = _classNameFound; FormattedParameters f_ = new FormattedParameters(); if (_kind == MethodAccessKind.INSTANCE) { String className_ = Argument.getNullableValue(_previous).getStruct().getClassName(_conf); classFormat_ = ExecInherits.getQuickFullTypeByBases(className_, classFormat_, _conf); if (classFormat_.isEmpty()) { _stackCall.setCallingState(new CustomFoundExc(new ErrorStruct(_conf, getBadCastMessage(_classNameFound, className_), cast_, _stackCall))); return f_; } } Parameters parameters_ = check(_rootBlock, classFormat_, _cache, _conf, _stackCall); if (parameters_.getError() != null) { return f_; } f_.setParameters(parameters_); f_.setFormattedClass(classFormat_); return f_; }
public Argument checkParams(String _classNameFound, Argument _previous, Cache _cache, ContextEl _conf, MethodAccessKind _kind, StackCall _stackCall){ LgNames stds_ = _conf.getStandards(); String cast_ = stds_.getContent().getCoreNames().getAliasCastType(); String classFormat_ = _classNameFound; FormattedParameters f_ = new FormattedParameters(); if (_kind == MethodAccessKind.INSTANCE) { String className_ = Argument.getNullableValue(_previous).getStruct().getClassName(_conf); classFormat_ = ExecInherits.getQuickFullTypeByBases(className_, classFormat_, _conf); if (classFormat_.isEmpty()) { _stackCall.setCallingState(new CustomFoundExc(new ErrorStruct(_conf, getBadCastMessage(_classNameFound, className_), cast_, _stackCall))); return Argument.createVoid(); } } Parameters parameters_ = check(classFormat_, _cache, _conf, _stackCall); f_.setParameters(parameters_); f_.setFormattedClass(classFormat_); return redirect(_conf, _classNameFound, _previous, _stackCall, f_); }
306
private void parseTerm(){ Intent intent = getIntent(); currentTermUri = intent.getParcelableExtra(DataProvider.TERM_CONTENT_TYPE); termId = Integer.parseInt(currentTermUri.getLastPathSegment()); currentTerm = DataManager.getTerm(this, termId); }
private void parseTerm(){ Intent intent = getIntent(); termId = intent.getIntExtra(DBOpenHelper.TERM_ID, 0); currentTerm = DataManager.getTerm(this, termId); }
307
private void patchRequestSalesOffer(){ RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); String url = getRequestUrl() + "salesoffers/" + getIntent().getExtras().getLong("id"); JSONObject postData = makeSalesOfferDataJson(); Log.v(TAG, String.valueOf(postData)); JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.PATCH, url, postData, new Response.Listener<JSONObject>() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onResponse(JSONObject response) { onPostResponseSalesOffer(response); Intent intent = new Intent(getApplicationContext(), ForumTabsActivity.class); startActivity(intent); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { onErrorResponseSalesOffer(error); } }) { @Override public Map<String, String> getHeaders() { return prepareRequestHeaders(); } }; queue.add(jsonArrayRequest); }
private void patchRequestSalesOffer(){ String url = getRequestUrl() + "salesoffers/" + getIntent().getExtras().getLong("id"); JSONObject postData = makeSalesOfferDataJson(); Log.v(TAG, String.valueOf(postData)); Log.v(TAG, "Invoking categoryRequestProcessor"); requestProcessor.makeRequest(Request.Method.PATCH, url, postData, RequestType.OBJECT, new Response.Listener<JSONObject>() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onResponse(JSONObject response) { onPostResponseSalesOffer(response); Intent intent = new Intent(getApplicationContext(), ForumTabsActivity.class); startActivity(intent); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { onErrorResponseSalesOffer(error); } }); }
308
public void applyApplications(@Nonnull Map<String, ApplicationBean> desiredApplications){ checkNotNull(desiredApplications); ApplicationsOperations applicationsOperations = new ApplicationsOperations(cfOperations); log.info("Fetching information about applications..."); Map<String, ApplicationBean> liveApplications = applicationsOperations.getAll().block(); log.info("Information fetched."); ConfigBean desiredApplicationsConfig = createConfigFromApplications(desiredApplications); ConfigBean liveApplicationsConfig = createConfigFromApplications(liveApplications); DiffLogic diffLogic = new DiffLogic(); log.info("Comparing the applications..."); DiffResult wrappedDiff = diffLogic.createDiffResult(liveApplicationsConfig, desiredApplicationsConfig); log.info("Applications compared."); Map<String, List<CfChange>> allApplicationChanges = wrappedDiff.getApplicationChanges(); Flux<Void> applicationRequests = Flux.fromIterable(allApplicationChanges.entrySet()).flatMap(appChangeEntry -> ApplicationRequestsPlaner.create(applicationsOperations, appChangeEntry.getKey(), appChangeEntry.getValue())).onErrorContinue(log::error); applicationRequests.blockLast(); log.info("Applying changes to applications..."); }
public void applyApplications(@Nonnull Map<String, ApplicationBean> desiredApplications){ checkNotNull(desiredApplications); ApplicationsOperations applicationsOperations = new ApplicationsOperations(cfOperations); log.info("Fetching information about applications..."); Map<String, ApplicationBean> liveApplications = applicationsOperations.getAll().block(); log.info("Information fetched."); ConfigBean desiredApplicationsConfig = createConfigFromApplications(desiredApplications); ConfigBean liveApplicationsConfig = createConfigFromApplications(liveApplications); log.info("Comparing the applications..."); DiffResult wrappedDiff = this.diffLogic.createDiffResult(liveApplicationsConfig, desiredApplicationsConfig); log.info("Applications compared."); Map<String, List<CfChange>> allApplicationChanges = wrappedDiff.getApplicationChanges(); Flux<Void> applicationRequests = Flux.fromIterable(allApplicationChanges.entrySet()).flatMap(appChangeEntry -> ApplicationRequestsPlaner.create(applicationsOperations, appChangeEntry.getKey(), appChangeEntry.getValue())).onErrorContinue(log::error); applicationRequests.blockLast(); log.info("Applying changes to applications..."); }
309
private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException("got insane sequence number"); } int offset = seqNum * DATA_PER_FULL_PACKET_WITH_SEQUENCE_NUM * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException("received more data than expected"); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { if (!checkAllReceived()) { finished |= retransmitMissingSequences(); } else { finished = true; } } }
private void processData(ByteBuffer data) throws IOException, InterruptedException{ int firstPacketElement = data.getInt(); int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK; boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0); if (seqNum > maxSeqNum || seqNum < 0) { throw new IllegalStateException("got insane sequence number"); } int offset = seqNum * DATA_WORDS_PER_PACKET * WORD_SIZE; int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE; if (trueDataLength > dataReceiver.capacity()) { throw new IllegalStateException("received more data than expected"); } if (!isEndOfStream || data.limit() != END_FLAG_SIZE) { data.position(SEQUENCE_NUMBER_SIZE); data.get(dataReceiver.array(), offset, trueDataLength - offset); } receivedSeqNums.set(seqNum); if (isEndOfStream) { finished = retransmitMissingSequences(); } }
310
public String GetEmployeeInformation(){ String value = this.GetId() + " " + this.GetName(); return value; }
public String GetEmployeeInformation(){ return this.GetId() + " " + this.GetName(); }
311
public PaymentRequest createPaymentRequest(IPaymentRequestSpecification spec){ if (!(spec.getWallet() instanceof IGeneratesNewDepositCryptoAddress)) { throw new IllegalArgumentException("Wallet '" + spec.getWallet().getClass() + "' does not implement " + IGeneratesNewDepositCryptoAddress.class.getSimpleName()); } if (!(spec.getWallet() instanceof IQueryableWallet)) { throw new IllegalArgumentException("Wallet '" + spec.getWallet().getClass() + "' does not implement " + IQueryableWallet.class.getSimpleName()); } if (spec.getTotal().stripTrailingZeros().scale() > decimals) { throw new IllegalArgumentException(cryptoCurrency + " has " + decimals + " decimals"); } return super.createPaymentRequest(spec); }
public PaymentRequest createPaymentRequest(IPaymentRequestSpecification spec){ if (spec.getTotal().stripTrailingZeros().scale() > decimals) { throw new IllegalArgumentException(cryptoCurrency + " has " + decimals + " decimals"); } return super.createPaymentRequest(spec); }
312
void syncMojitoWithThirdPartyTMS(Long repositoryId, String thirdPartyProjectId, List<ThirdPartySyncAction> actions, String pluralSeparator, String localeMapping, String skipTextUnitsWithPattern, String skipAssetsWithPathPattern, List<String> options){ pluralSeparator = replaceSpacePlaceholder(pluralSeparator); logger.debug("Thirdparty TMS Sync: repositoryId={} thirdPartyProjectId={} " + "actions={} pluralSeparator={} localeMapping={} " + "skipTextUnitsWithPattern={} skipAssetsWithPattern={} " + "options={}", repositoryId, thirdPartyProjectId, actions, pluralSeparator, localeMapping, skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); Repository repository = repositoryRepository.findById(repositoryId).orElse(null); if (actions.contains(ThirdPartySyncAction.PUSH)) { thirdPartyTMS.push(repository, thirdPartyProjectId, pluralSeparator, skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); } if (actions.contains(ThirdPartySyncAction.PUSH_TRANSLATION)) { thirdPartyTMS.pushTranslations(repository, thirdPartyProjectId, pluralSeparator, parseLocaleMapping(localeMapping), skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); } if (actions.contains(ThirdPartySyncAction.PULL)) { thirdPartyTMS.pull(repository, thirdPartyProjectId, pluralSeparator, parseLocaleMapping(localeMapping), skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); } if (actions.contains(ThirdPartySyncAction.MAP_TEXTUNIT)) { mapMojitoAndThirdPartyTextUnits(repository, thirdPartyProjectId, pluralSeparator); } if (actions.contains(ThirdPartySyncAction.PUSH_SCREENSHOT)) { uploadScreenshotsAndCreateMappings(repository, thirdPartyProjectId); } }
void syncMojitoWithThirdPartyTMS(Long repositoryId, String thirdPartyProjectId, List<ThirdPartySyncAction> actions, String pluralSeparator, String localeMapping, String skipTextUnitsWithPattern, String skipAssetsWithPathPattern, List<String> options){ logger.debug("Thirdparty TMS Sync: repositoryId={} thirdPartyProjectId={} " + "actions={} pluralSeparator={} localeMapping={} " + "skipTextUnitsWithPattern={} skipAssetsWithPattern={} " + "options={}", repositoryId, thirdPartyProjectId, actions, pluralSeparator, localeMapping, skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); Repository repository = repositoryRepository.findById(repositoryId).orElse(null); if (actions.contains(ThirdPartySyncAction.PUSH)) { thirdPartyTMS.push(repository, thirdPartyProjectId, pluralSeparator, skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); } if (actions.contains(ThirdPartySyncAction.PUSH_TRANSLATION)) { thirdPartyTMS.pushTranslations(repository, thirdPartyProjectId, pluralSeparator, parseLocaleMapping(localeMapping), skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); } if (actions.contains(ThirdPartySyncAction.PULL)) { thirdPartyTMS.pull(repository, thirdPartyProjectId, pluralSeparator, parseLocaleMapping(localeMapping), skipTextUnitsWithPattern, skipAssetsWithPathPattern, options); } if (actions.contains(ThirdPartySyncAction.MAP_TEXTUNIT)) { mapMojitoAndThirdPartyTextUnits(repository, thirdPartyProjectId, pluralSeparator); } if (actions.contains(ThirdPartySyncAction.PUSH_SCREENSHOT)) { uploadScreenshotsAndCreateMappings(repository, thirdPartyProjectId); } }
313
public List<ItemStack> getCraftedItems(){ if (alreadyProcessing || !isEnabled()) return Collections.emptyList(); if (stillNeedReplace()) { return new ArrayList<>(); } try { alreadyProcessing = true; IRouter myRouter = getRouter(); List<ExitRoute> exits = new ArrayList<>(myRouter.getIRoutersByCost()); exits.removeIf(e -> e.destination == myRouter); LinkedList<ItemIdentifier> items = SimpleServiceLocator.logisticsManager.getCraftableItems(exits); List<ItemStack> list = new ArrayList<>(items.size()); for (ItemIdentifier item : items) { ItemStack is = item.unsafeMakeNormalStack(1); list.add(is); } return list; } finally { alreadyProcessing = false; } }
public List<ItemStack> getCraftedItems(){ if (alreadyProcessing || !isEnabled()) return Collections.emptyList(); if (stillNeedReplace()) return new ArrayList<>(); try { alreadyProcessing = true; IRouter myRouter = getRouter(); List<ExitRoute> exits = new ArrayList<>(myRouter.getIRoutersByCost()); exits.removeIf(e -> e.destination == myRouter); LinkedList<ItemIdentifier> items = SimpleServiceLocator.logisticsManager.getCraftableItems(exits); List<ItemStack> list = new ArrayList<>(items.size()); for (ItemIdentifier item : items) { ItemStack is = item.unsafeMakeNormalStack(1); list.add(is); } return list; } finally { alreadyProcessing = false; } }
314
public void failsIfBodyAssertionFails() throws IOException{ exceptionRule.expect(RequestAssertionException.class); exceptionRule.expectMessage(allOf(containsString("Expected: a string containing \"\\\"property\\\": \\\"value\\\"\""), containsString("but: was \"{\"another\": \"someother\"}\""))); server.enqueue(200, "body.json").assertBody(new BodyAssertion() { @Override public void doAssert(String body) { assertThat(body, containsString("\"property\": \"value\"")); } }); this.request = new Request.Builder().url(server.url("/body").toString()).post(RequestBody.create(MediaType.parse("application/json"), "{\"another\": \"someother\"}")).build(); client.newCall(request).execute(); }
public void failsIfBodyAssertionFails() throws IOException{ exceptionRule.expect(RequestAssertionException.class); exceptionRule.expectMessage(containsString("bodyMatcher = a string containing \"\\\"property\\\": \\\"value\\\"\"")); server.addFixture(200, "body.json").ifRequestMatches().bodyMatches(containsString("\"property\": \"value\"")); this.request = new Request.Builder().url(server.url("/body").toString()).post(RequestBody.create(MediaType.parse("application/json"), "{\"another\": \"someother\"}")).build(); client.newCall(request).execute(); }
315
public double calculateF(Cell start, Cell end){ int deltaX = this.x - end.getX(); if (deltaX < 0) deltaX *= -1; int deltaY = this.y - end.getY(); if (deltaY < 0) deltaY *= -1; return Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)) + getG(start, end); }
public double calculateF(Cell start, Cell end){ int deltaX = Math.abs(this.x - end.getX()); int deltaY = Math.abs(this.y - end.getY()); double h = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); return getG(start, end) + h; }
316
static MapToList<Ability, CNAbility> buildAbilityList(List<String> types, List<String> negate, String abilityType, View view, String aspect, MapToList<Ability, CNAbility> listOfAbilities){ List<Ability> aList = new ArrayList<>(listOfAbilities.getKeySet()); Globals.sortPObjectListByName(aList); boolean matchTypeDef = false; boolean matchVisibilityDef = false; boolean matchAspectDef = false; List<Ability> bList = new ArrayList<>(); for (Ability aAbility : aList) { matchTypeDef = abilityMatchesType(abilityType, aAbility, types, negate); matchVisibilityDef = abilityVisibleTo(view, aAbility); matchAspectDef = abilityMatchesAspect(aspect, aAbility); if (matchTypeDef && matchVisibilityDef && matchAspectDef) { bList.add(aAbility); } } try { MapToList<Ability, CNAbility> mtl = new GenericMapToList<>(LinkedHashMap.class); for (Ability a : bList) { mtl.addAllToListFor(a, listOfAbilities.getListFor(a)); } return mtl; } catch (InstantiationException | IllegalAccessException e) { throw new UnreachableError(e); } }
static MapToList<Ability, CNAbility> buildAbilityList(List<String> types, List<String> negate, String abilityType, View view, String aspect, MapToList<Ability, CNAbility> listOfAbilities){ List<Ability> aList = new ArrayList<>(listOfAbilities.getKeySet()); Globals.sortPObjectListByName(aList); boolean matchTypeDef = false; boolean matchVisibilityDef = false; boolean matchAspectDef = false; List<Ability> bList = new ArrayList<>(); for (Ability aAbility : aList) { matchTypeDef = abilityMatchesType(abilityType, aAbility, types, negate); matchVisibilityDef = abilityVisibleTo(view, aAbility); matchAspectDef = abilityMatchesAspect(aspect, aAbility); if (matchTypeDef && matchVisibilityDef && matchAspectDef) { bList.add(aAbility); } } try { MapToList<Ability, CNAbility> mtl = new GenericMapToList<>(LinkedHashMap.class); bList.forEach(a -> mtl.addAllToListFor(a, listOfAbilities.getListFor(a))); return mtl; } catch (InstantiationException | IllegalAccessException e) { throw new UnreachableError(e); } }
317
public void onCreate(@Nullable Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_trailer); final Bundle extras = getIntent().getExtras(); if (extras != null && extras.containsKey(EXTRA_VIDEO_ID)) { videoId = extras.getString(EXTRA_VIDEO_ID); } else { finish(); } unbinder = ButterKnife.bind(this); frameLayout.setOnClickListener(v -> { onBackPressed(); overridePendingTransition(R.anim.fade_in, R.anim.fade_out); }); youTubePlayerView.initialize(BuildConfig.YOU_TUBE_DATA_API_KEY, this); if (savedInstanceState != null) { videoTime = savedInstanceState.getInt(EXTRA_VIDEO_TIME); } }
public void onCreate(@Nullable Bundle savedInstanceState){ super.onCreate(savedInstanceState); final Bundle extras = getIntent().getExtras(); if (extras != null && extras.containsKey(EXTRA_VIDEO_ID)) { videoId = extras.getString(EXTRA_VIDEO_ID); } else { finish(); } setContentView(R.layout.activity_trailer); unbinder = ButterKnife.bind(this); youTubePlayerView.initialize(BuildConfig.YOU_TUBE_DATA_API_KEY, this); if (savedInstanceState != null) { videoTime = savedInstanceState.getInt(EXTRA_VIDEO_TIME); } }
318
public void choose(){ if (listInfo.getNumNames() == 0) { return; } if (settings.isPresentationModeEnabled()) { if (!canShowPresentationScreen) { return; } canShowPresentationScreen = false; Intent intent = new Intent(this, PresentationActivity.class); intent.putExtra(PresentationActivity.LIST_ID_KEY, listId); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivityForResult(intent, PRESENTATION_MODE_REQUEST_CODE); } else { if (choicesDisplayDialog.isShowing()) { return; } List<Integer> chosenIndexes = NameUtils.getRandomNumsInRange(settings.getNumNamesToChoose(), listInfo.getNumInstances() - 1); String chosenNames = listInfo.chooseNames(chosenIndexes, settings); if (!settings.getWithReplacement()) { nameChoosingAdapter.notifyDataSetChanged(); setViews(); } choicesDisplayDialog.showChoices(chosenNames, chosenIndexes.size()); if (settings.getAutomaticTts()) { sayNames(chosenNames); } } }
public void choose(){ if (listInfo.getNumNames() == 0) { return; } if (settings.isPresentationModeEnabled()) { if (!canShowPresentationScreen) { return; } canShowPresentationScreen = false; Intent intent = new Intent(this, PresentationActivity.class); intent.putExtra(PresentationActivity.LIST_ID_KEY, listId); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivityForResult(intent, PRESENTATION_MODE_REQUEST_CODE); } else { if (choicesDisplayDialog.isShowing()) { return; } List<String> chosenNames = listInfo.chooseNames(settings); if (!settings.getWithReplacement()) { nameChoosingAdapter.notifyDataSetChanged(); setViews(); } choicesDisplayDialog.showChoices(chosenNames); if (settings.getAutomaticTts()) { sayNames(NameUtils.flattenListToString(chosenNames, settings)); } } }
319
private static void goHome(){ int distance = Integer.MAX_VALUE; SensorMode seek = Fetchy.seekerSensor.getSeekMode(); float[] sample = new float[seek.sampleSize()]; seek.fetchSample(sample, 0); int direction = (int) sample[0]; System.out.println("Direction: " + direction); distance = (int) sample[1]; System.out.println("Distance: " + distance); Fetchy.pilot.rotate(direction); Delay.msDelay(200); if (distance < Integer.MAX_VALUE) { Fetchy.backward(); while (distance > 0 && !suppressed) { seek.fetchSample(sample, 0); distance = (int) sample[1]; System.out.println("Distance: " + distance); } } Fetchy.stop(); Fetchy.turn(180); Fetchy.letGo(); Fetchy.navigator.goTo(0, 0); Fetchy.currentState = State.WAITING_FOR_COMMAND; Fetchy.requestQueue.remove(0); }
private static void goHome(){ SensorMode seek = Fetchy.seekerSensor.getSeekMode(); float[] sample = new float[seek.sampleSize()]; seek.fetchSample(sample, 0); int direction = (int) sample[0]; System.out.println("Direction: " + direction); int distance = (int) sample[1]; System.out.println("Distance: " + distance); Fetchy.turn(direction); if (distance < Integer.MAX_VALUE) { Fetchy.backward(); while (distance > 0 && !suppressed) { seek.fetchSample(sample, 0); distance = (int) sample[1]; System.out.println("Distance: " + distance); } } Fetchy.stop(); Fetchy.turn(180); Fetchy.letGo(); Fetchy.navigator.goTo(0, 0); Fetchy.currentState = State.WAITING_FOR_COMMAND; Fetchy.requestQueue.remove(0); }
320
public void userActivate(Feature feature, String user){ { FeatureMetadata metadata = repository().getFeature(feature, null); if (metadata == null) { metadata = new DefaultFeatureMetadata(feature); } metadata.set(FeatureKeys.STATUS, String.valueOf(Status.RESTRICTED.getCode())); repository().updateFeature(metadata, null); } { FeatureMetadata metadata = repository().getFeature(feature, user); if (metadata == null) { metadata = new DefaultFeatureMetadata(feature); } metadata.set(FeatureKeys.STATUS, String.valueOf(Status.ACTIVE.getCode())); repository().updateFeature(metadata, user); } }
public void userActivate(Feature feature, String user){ { final FeatureMetadata metadata = getMetadata(feature, user).set(FeatureKeys.STATUS, String.valueOf(Status.RESTRICTED.getCode())); repository().updateFeature(metadata, null); } { FeatureMetadata metadata = repository().getFeature(feature, user); if (metadata == null) { metadata = new DefaultFeatureMetadata(feature); } metadata.set(FeatureKeys.STATUS, String.valueOf(Status.ACTIVE.getCode())); repository().updateFeature(metadata, user); } }
321
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_category); binding = ActivityCategoryBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); String category = getIntent().getStringExtra("ISCATEGORY"); getSupportActionBar().setTitle(category); if (savedInstanceState == null) { onSetData(category); } }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_category); binding = ActivityCategoryBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); String category = getIntent().getStringExtra("CATEGORY"); getSupportActionBar().setTitle(category); if (savedInstanceState == null) onSetData(category); }
322
void transferVideo(File[] videoCollection, Socket clientSocket) throws IOException{ OutputStream clientSocketOS = clientSocket.getOutputStream(); BufferedOutputStream clientSocketBOS = new BufferedOutputStream(clientSocketOS); DataOutputStream clientSocketDOS = new DataOutputStream(clientSocketBOS); clientSocketDOS.writeInt(videoCollection.length); for (int i = 0; i < videoCollection.length; i++) { clientSocketDOS.writeLong(videoCollection[i].length()); clientSocketDOS.flush(); clientSocketDOS.writeChars(videoCollection[i].getName()); } for (int i = 0; i < videoCollection.length; i++) { FileInputStream videoFileInputStream = new FileInputStream(videoCollection[i]); byte[] buffer = videoFileInputStream.readAllBytes(); clientSocketDOS.write(buffer); } clientSocketDOS.close(); }
void transferVideo(File[] videoCollection, Socket clientSocket) throws IOException{ OutputStream clientSocketOS = clientSocket.getOutputStream(); BufferedOutputStream clientSocketBOS = new BufferedOutputStream(clientSocketOS); DataOutputStream clientSocketDOS = new DataOutputStream(clientSocketBOS); clientSocketDOS.writeInt(videoCollection.length); for (int i = 0; i < videoCollection.length; i++) { clientSocketDOS.writeLong(videoCollection[i].length()); clientSocketDOS.writeUTF(videoCollection[i].getName()); } for (int i = 0; i < videoCollection.length; i++) { FileInputStream videoFileInputStream = new FileInputStream(videoCollection[i]); byte[] buffer = videoFileInputStream.readAllBytes(); clientSocketDOS.write(buffer); } clientSocketDOS.close(); }
323
public void process7Test(){ String locale_ = "en"; String folder_ = "messages"; String relative_ = "sample/file"; String content_ = "one=Description one\ntwo=Description two\nthree=desc &lt;{0}&gt;"; String html_ = "<html><body><ul><c:for var=\"s\" list=\"$new java.lang.Integer[]{}\" className='$int'><li>{s;}</li></c:for></ul></body></html>"; StringMap<String> files_ = new StringMap<String>(); files_.put(EquallableExUtil.formatFile(folder_, locale_, relative_), content_); BeanOne bean_ = new BeanOne(); bean_.getComposite().getStrings().add("FIRST"); bean_.getComposite().getStrings().add("SECOND"); bean_.getComposite().setInteger(5); Configuration context_ = contextElThird(); context_.setBeans(new StringMap<Bean>()); context_.setMessagesFolder(folder_); context_.setProperties(new StringMap<String>()); context_.getProperties().put("msg_example", relative_); RendDocumentBlock rendDocumentBlock_ = buildRendWithOneNativeBean(html_, bean_, context_); assertTrue(context_.isEmptyErrors()); assertEq("<html><body><ul/></body></html>", RendBlock.getRes(rendDocumentBlock_, context_)); assertNull(getException(context_)); }
public void process7Test(){ String locale_ = "en"; String folder_ = "messages"; String relative_ = "sample/file"; String content_ = "one=Description one\ntwo=Description two\nthree=desc &lt;{0}&gt;"; String html_ = "<html><body><ul><c:for var=\"s\" list=\"$new java.lang.Integer[]{}\" className='$int'><li>{s;}</li></c:for></ul></body></html>"; StringMap<String> files_ = new StringMap<String>(); files_.put(EquallableExUtil.formatFile(folder_, locale_, relative_), content_); Configuration context_ = contextElThird(); context_.setBeans(new StringMap<Bean>()); context_.setMessagesFolder(folder_); context_.setProperties(new StringMap<String>()); context_.getProperties().put("msg_example", relative_); RendDocumentBlock rendDocumentBlock_ = buildRendWithoutBean(html_, context_); assertTrue(context_.isEmptyErrors()); assertEq("<html><body><ul/></body></html>", RendBlock.getRes(rendDocumentBlock_, context_)); assertNull(getException(context_)); }
324
public void shouldReturn200IfLoginSucceed() throws Exception{ final PiggyBankUser piggyBankUser = new PiggyBankUser(); piggyBankUser.setUsername("username"); piggyBankUser.setPassword("password"); piggyBankUser.setToken("token"); final String requestBody = "{\n" + " \"username\": \"username\",\n" + " \"password\": \"password\"\n" + "}"; when(authenticationService.authenticate(anyString(), anyString())).thenReturn(Optional.of(piggyBankUser)); final MvcResult response = mockMvc.perform(post("/api/v1/users/authorize").contentType(MediaType.APPLICATION_JSON).content(requestBody)).andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); verify(authenticationService).authenticate("username", "password"); final LoggedUserDto actual = mapper.readValue(response.getResponse().getContentAsByteArray(), LoggedUserDto.class); final LoggedUserDto expected = LoggedUserDto.forUsernameAndToken("username", "token"); assertEquals(expected, actual); }
public void shouldReturn200IfLoginSucceed() throws Exception{ final PiggyBankUser piggyBankUser = forUsernamePasswordAndToken(USERNAME, PASSWORD, "token"); final String requestBody = "{\n" + " \"username\": \"username\",\n" + " \"password\": \"password\"\n" + "}"; when(authenticationService.authenticate(anyString(), anyString())).thenReturn(Optional.of(piggyBankUser)); final MvcResult response = mockMvc.perform(post("/api/v1/users/authorize").contentType(MediaType.APPLICATION_JSON).content(requestBody)).andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); verify(authenticationService).authenticate(USERNAME, PASSWORD); final LoggedUserDto actual = mapper.readValue(response.getResponse().getContentAsByteArray(), LoggedUserDto.class); final LoggedUserDto expected = LoggedUserDto.forUsernameAndToken(USERNAME, "token"); assertEquals(expected, actual); }
325
public DistributionQueue getQueue(@NotNull String queueName) throws DistributionException{ String key = getKey(queueName); return queueMap.computeIfAbsent(key, k -> { statusMap.put(key, new ConcurrentHashMap<>()); if (isActive) { return new ActiveResourceQueue(resolverFactory, serviceName, queueName, agentRootPath); } else { return new ResourceQueue(resolverFactory, serviceName, queueName, agentRootPath); } }); }
public DistributionQueue getQueue(@NotNull String queueName) throws DistributionException{ return queueMap.computeIfAbsent(queueName, name -> { if (isActive) { return new ActiveResourceQueue(resolverFactory, serviceName, name, agentRootPath); } else { return new ResourceQueue(resolverFactory, serviceName, name, agentRootPath); } }); }
326
public ResponseDTO deleteTask(@RequestBody TodoTaskDto taskDTO){ if (taskDTO.getId() == 0) { logger.error("Task Id is invalid."); return TodoTaskUtil.createResponseFalied("Task Id is invalid."); } try { ResponseDTO responseDTO = todoTaskService.delete(taskDTO); return responseDTO; } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); return TodoTaskUtil.createResponseFalied(e.getMessage()); } }
public ResponseDTO deleteTask(@RequestBody TodoTaskDto taskDTO){ if (taskDTO.getId() == 0) { logger.error("Task Id is invalid."); return TodoTaskUtil.createResponseFalied("Task Id is invalid."); } try { return todoTaskService.delete(taskDTO); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); return TodoTaskUtil.createResponseFalied(e.getMessage()); } }
327
public void initialize(URL url, ResourceBundle resourceBundle){ connectionsComboBox.itemsProperty().bind(Context.getInstance().getConnections()); queryArea = new CodeArea(); queryArea.setParagraphStyle(0, Collections.singletonList("has-caret")); queryArea.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getCode() == KeyCode.ENTER && event.isControlDown()) { runQuery(new ActionEvent()); } } }); mainArea.getItems().add(0, queryArea); }
public void initialize(URL url, ResourceBundle resourceBundle){ connectionsComboBox.itemsProperty().bind(Context.getInstance().getConnections()); queryArea = new CodeArea(); queryArea.setParagraphStyle(0, Collections.singletonList("has-caret")); queryArea.setOnKeyPressed(event -> { if (event.getCode() == KeyCode.ENTER && event.isControlDown()) { runQuery(new ActionEvent()); } }); VirtualizedScrollPane sp = new VirtualizedScrollPane(queryArea); mainArea.getItems().add(0, sp); }
328
public Result unauthorizedUser(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("alertgroupId") Integer alertgroupId){ logger.info("unauthorized user, login user:{}, alert group id:{}", loginUser.getUserName(), alertgroupId); Map<String, Object> result = usersService.unauthorizedUser(loginUser, alertgroupId); return returnDataList(result); }
public Result<List<User>> unauthorizedUser(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("alertgroupId") Integer alertgroupId){ logger.info("unauthorized user, login user:{}, alert group id:{}", loginUser.getUserName(), alertgroupId); return usersService.unauthorizedUser(loginUser, alertgroupId); }
329
public UserPojo getMe() throws DataNotFoundException, ExecutionFailException, ExistRecordException{ try { return userService.getMe(); } catch (ServiceException ex) { exceptionConverter.convert(ex); } throw new DataNotFoundException("No such user data is found"); }
public UserPojo getMe() throws DataNotFoundException{ return userService.getMe(); }
330
public boolean hasSameMethod(Invocation candidate){ Method m1 = invocation.getMethod(); Method m2 = candidate.getMethod(); if (m1.getName() != null && m1.getName().equals(m2.getName())) { Class<?>[] params1 = m1.getParameterTypes(); Class<?>[] params2 = m2.getParameterTypes(); if (params1.length == params2.length) { for (int i = 0; i < params1.length; i++) { if (params1[i] != params2[i]) return false; } return true; } } return false; }
public boolean hasSameMethod(Invocation candidate){ Method m1 = invocation.getMethod(); Method m2 = candidate.getMethod(); if (m1.getName() != null && m1.getName().equals(m2.getName())) { Class<?>[] params1 = m1.getParameterTypes(); Class<?>[] params2 = m2.getParameterTypes(); return Arrays.equals(params1, params2); } return false; }
331
public UserProfile getCurrentUserProfile(){ UserProfile user = new UserProfile("XXX", "jmcmahon", "apiKey", DateTime.now()); return userProfileDao.save(user); }
public UserProfile getCurrentUserProfile(){ return null; }
332
public static void close(){ try { CLIENT_HANDLER_SERVICE.awaitTermination(2000, TimeUnit.MILLISECONDS); VERIFICATION_HANDLER_SERVICE.awaitTermination(2000, TimeUnit.MILLISECONDS); DATABASE_SERVICE.awaitTermination(2000, TimeUnit.MILLISECONDS); SERVER_EXECUTOR.awaitTermination(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { } }
public static void close(){ try { CLIENT_HANDLER_SERVICE.awaitTermination(2000, TimeUnit.MILLISECONDS); DATABASE_SERVICE.awaitTermination(2000, TimeUnit.MILLISECONDS); SERVER_EXECUTOR.awaitTermination(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { } }
333
public Object clone() throws CloneNotSupportedException{ StatementTree v = (StatementTree) super.clone(); HashMap cloned_map = new HashMap(); v.map = cloned_map; Iterator i = map.keySet().iterator(); while (i.hasNext()) { Object key = i.next(); Object entry = map.get(key); entry = cloneSingleObject(entry); cloned_map.put(key, entry); } return v; }
public Object clone() throws CloneNotSupportedException{ StatementTree v = (StatementTree) super.clone(); HashMap cloned_map = new HashMap(); v.map = cloned_map; for (Object key : map.keySet()) { Object entry = map.get(key); entry = cloneSingleObject(entry); cloned_map.put(key, entry); } return v; }
334
public int onStartCommand(Intent intent, int flags, int id){ int audioType = intent != null ? intent.getIntExtra(EXTRA_AUDIO_TYPE, Utils.PREF_AUDIO_RECORDING_TYPE_DEFAULT) : Utils.PREF_AUDIO_RECORDING_TYPE_DEFAULT; mLayer = new OverlayLayer(this); mLayer.setOnActionClickListener(() -> { Intent fabIntent = new Intent(ScreencastService.ACTION_START_SCREENCAST); fabIntent.putExtra(ScreencastService.EXTRA_WITHAUDIO_TYPE, audioType); startService(fabIntent.setClass(this, ScreencastService.class)); Utils.setStatus(Utils.UiStatus.SCREEN); onDestroy(); }); mLayer.setSettingsButtonOnClickListener(() -> { Intent intent_ = new Intent(this, RecorderActivity.class); intent_.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent_); onDestroy(); }); mLayer.setCloseButtonOnClickListener(this::onDestroy); Notification notification = new NotificationCompat.Builder(this, SCREENCAST_OVERLAY_NOTIFICATION_CHANNEL).setContentTitle(getString(R.string.screen_overlay_notif_title)).setContentText(getString(R.string.screen_overlay_notif_message)).setSmallIcon(R.drawable.ic_action_screen_record).setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, RecorderActivity.class), 0)).build(); startForeground(FG_ID, notification); isRunning = true; return START_NOT_STICKY; }
public int onStartCommand(Intent intent, int flags, int id){ mLayer = new OverlayLayer(this); mLayer.setOnActionClickListener(() -> { Intent fabIntent = new Intent(ScreencastService.ACTION_START_SCREENCAST); startService(fabIntent.setClass(this, ScreencastService.class)); Utils.setStatus(Utils.UiStatus.SCREEN, this); onDestroy(); }); mLayer.setSettingsButtonOnClickListener(() -> { Intent intent_ = new Intent(this, RecorderActivity.class); intent_.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent_.putExtra(RecorderActivity.EXTRA_UI_TYPE, Utils.SCREEN_PREFS); startActivity(intent_); onDestroy(); }); mLayer.setCloseButtonOnClickListener(this::onDestroy); Notification notification = new NotificationCompat.Builder(this, SCREENCAST_OVERLAY_NOTIFICATION_CHANNEL).setContentTitle(getString(R.string.screen_overlay_notif_title)).setContentText(getString(R.string.screen_overlay_notif_message)).setSmallIcon(R.drawable.ic_action_screen_record).setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, RecorderActivity.class), 0)).build(); startForeground(FG_ID, notification); isRunning = true; return START_NOT_STICKY; }
335
private void updateUpButtonPosition(){ int upButtonNormalBottom = mTopInset + mUpButton.getHeight(); mUpButton.setTranslationY(Math.min(mSelectedItemUpButtonFloor - upButtonNormalBottom, 0)); }
private void updateUpButtonPosition(){ }
336
public static void forkSystemServerPre(int uid, int gid, int[] gids, int debugFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities){ Router.onForkStart(); Router.initResourcesHook(); final boolean isDynamicModulesMode = Main.isDynamicModulesEnabled(); ConfigManager.setDynamicModulesMode(isDynamicModulesMode); Router.prepare(true); PrebuiltMethodsDeopter.deoptBootMethods(); Router.installBootstrapHooks(true); Router.loadModulesSafely(true); Main.closeFilesBeforeForkNative(); }
public static void forkSystemServerPre(int uid, int gid, int[] gids, int debugFlags, int[][] rlimits, long permittedCapabilities, long effectiveCapabilities){ Router.onForkStart(); Router.initResourcesHook(); Router.prepare(true); PrebuiltMethodsDeopter.deoptBootMethods(); Router.installBootstrapHooks(true); Router.loadModulesSafely(true); Zygote.closeFilesBeforeFork(); }
337
public Vector2f add(Vector2fc v){ x += v.x(); y += v.y(); return this; }
public Vector2f add(Vector2fc v){ return add(v, this); }
338
public void bind(VideoItem videoItem){ videoImage.post(() -> Glide.with(context).load(videoItem.getThumb()).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { videoImage.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.sync_error_icon, null)); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { return false; } }).into(videoImage)); videoTitle.setText(videoItem.getTitle()); videoSubtitle.setText(videoItem.getSubtitle()); }
public void bind(VideoItem videoItem){ loadImageFromVideoItem(videoItem, videoImage, context); videoTitle.setText(videoItem.getTitle()); videoSubtitle.setText(videoItem.getSubtitle()); }
339
private Document getDocument(String xml){ try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return parser.parse(new InputSource(new StringReader(xml))); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } return null; }
private Document getDocument(String xml){ try { DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return parser.parse(new InputSource(new StringReader(xml))); } catch (ParserConfigurationException | SAXException | IOException e) { throw new RuntimeException(e); } }
340
public static OwnerNodeProperty getOwnerProperty(@Nonnull Node node){ NodeProperty prop = node.getNodeProperties().get(OwnerNodeProperty.class); return prop != null ? (OwnerNodeProperty) prop : null; }
public static OwnerNodeProperty getOwnerProperty(@Nonnull Node node){ return node.getNodeProperties().get(OwnerNodeProperty.class); }
341
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){ String currentHost = "http://" + Uri.parse(view.getUrl()).getHost(); if (!currentHost.equals(prodUrl) && !currentHost.equals(devUrl)) { return true; } String query = request.getUrl().getQuery(); if (query != null) { String queryCommand = query.substring(0, query.indexOf('&')); callback = query.substring(query.indexOf('=') + 1); if (queryCommand.equals("scan")) { scanBarcode(); return true; } else if (queryCommand.equals("acquirePhoto")) { takePhoto(); return true; } } String requestHost = "http://" + request.getUrl().getHost(); return !requestHost.equals(prodUrl) && !requestHost.equals(devUrl); }
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){ if (!Utilities.urlIsTrusted(view.getUrl())) { return true; } String query = request.getUrl().getQuery(); if (query != null) { String queryCommand = query.substring(0, query.indexOf('&')); callback = query.substring(query.indexOf('=') + 1); if (queryCommand.equals("scan")) { scanBarcode(); return true; } else if (queryCommand.equals("acquirePhoto")) { takePhoto(); return true; } } return !Utilities.urlIsTrusted(request.getUrl().toString()); }
342
public void removeDuplicates(){ int i_ = FIRST_INDEX; while (true) { if (i_ >= size()) { break; } T e_ = get(i_); boolean rem_ = false; int next_ = indexOfObj(e_, i_ + 1); while (next_ != INDEX_NOT_FOUND_ELT) { removeAt(next_); rem_ = true; next_ = indexOfObj(e_, next_ + 1); } if (!rem_) { i_++; } } }
public void removeDuplicates(){ int i_ = FIRST_INDEX; while (i_ < size()) { T e_ = get(i_); boolean rem_ = false; int next_ = indexOfObj(e_, i_ + 1); while (next_ != INDEX_NOT_FOUND_ELT) { removeAt(next_); rem_ = true; next_ = indexOfObj(e_, i_ + 1); } if (!rem_) { i_++; } } }
343
public void call(java.lang.Integer numTimes, Float32Member a, Float32Member b){ assign().call(a, b); for (int i = 0; i < numTimes; i++) divide().call(b, TWO, b); }
public void call(java.lang.Integer numTimes, Float32Member a, Float32Member b){ ScaleHelper.compute(G.FLT, G.FLT, new Float32Member(0.5f), numTimes, a, b); }
344
public Profile enableProfile(String profileId, String... attributesToReturn) throws ProfileException{ Profile profile = updateProfile(profileId, new UpdateCallback() { @Override public void doWithProfile(ProfileUpdater profileUpdater) throws ProfileException { profileUpdater.setEnabled(true); } }, attributesToReturn); logger.debug(LOG_KEY_PROFILE_ENABLED, profileId); return profile; }
public Profile enableProfile(String profileId, String... attributesToReturn) throws ProfileException{ Profile profile = updateProfile(profileId, profileUpdater -> profileUpdater.setEnabled(true), attributesToReturn); logger.debug(LOG_KEY_PROFILE_ENABLED, profileId); return profile; }
345
private void displayPlace(Place place){ if (place == null) return; String content = ""; if (!TextUtils.isEmpty(place.getAddress())) { content += place.getAddress(); } if (!TextUtils.isEmpty(String.valueOf(place.getLatLng()))) { Log.e("MainActivity", "Latlong: " + String.valueOf(place.getLatLng())); LatLng mLatLng = place.getLatLng(); lat = String.valueOf(mLatLng.latitude); lng = String.valueOf(mLatLng.longitude); } Log.e("Main ac", "address: " + content); if (content != null && !content.equals("")) { edtAddress.setText(content); } else { edtAddress.setText(""); } }
private void displayPlace(Place place){ if (place == null) return; String content = ""; if (!TextUtils.isEmpty(place.getAddress())) { content += place.getAddress(); } if (!TextUtils.isEmpty(String.valueOf(place.getLatLng()))) { LatLng mLatLng = place.getLatLng(); lat = String.valueOf(mLatLng.latitude); lng = String.valueOf(mLatLng.longitude); } if (content != null && !content.equals("")) { edtAddress.setText(content); } else { edtAddress.setText(""); } }
346
public Set<InternalNode> getNodes(NodeState state){ switch(state) { case ACTIVE: return getAllNodes().getActiveNodes(); case INACTIVE: return getAllNodes().getInactiveNodes(); case SHUTTING_DOWN: return getAllNodes().getShuttingDownNodes(); default: throw new IllegalArgumentException("Unknown node state " + state); } }
public Set<InternalNode> getNodes(NodeState state){ switch(state) { case ACTIVE: return getAllNodes().getActiveNodes(); case INACTIVE: return getAllNodes().getInactiveNodes(); case SHUTTING_DOWN: return getAllNodes().getShuttingDownNodes(); } throw new IllegalArgumentException("Unknown node state " + state); }
347
public void run(){ if (sendError) { callback.onError(ActiveMQExceptionType.UNSUPPORTED_PACKET.getCode(), "Fake aio error"); } else { try { file.data.put(bytes); if (callback != null) { callback.done(); } if (file.bufferCallback != null) { file.bufferCallback.bufferDone(bytes); } } catch (Throwable e) { e.printStackTrace(); callback.onError(ActiveMQExceptionType.GENERIC_EXCEPTION.getCode(), e.getMessage()); } } }
public void run(){ if (sendError) { callback.onError(ActiveMQExceptionType.UNSUPPORTED_PACKET.getCode(), "Fake aio error"); } else { try { file.data.put(bytes); if (callback != null) { callback.done(); } } catch (Throwable e) { e.printStackTrace(); callback.onError(ActiveMQExceptionType.GENERIC_EXCEPTION.getCode(), e.getMessage()); } } }
348
void loadBlock(int count){ new Thread(() -> { JSONObject requestParams; rpcRequest request; rpcResponse response; Block block; String prevBlockHash; int i = 0; try { if (mBlockListAdpater.dataList.size() == 0) { request = new rpcRequest(rpcRequest.ICX_GET_LAST_BLOCK); response = rpcConnection.connect(request); block = new Block(((JSONObject) response.result)); prevBlockHash = block.getPrevBlockHash(); mBlockListAdpater.dataList.add(block); i++; } else { int length = mBlockListAdpater.dataList.size(); block = mBlockListAdpater.dataList.get(length - 1); prevBlockHash = block.getPrevBlockHash(); } for (; count > i; i++) { requestParams = new JSONObject(); requestParams.put("hash", "0x" + prevBlockHash); request = new rpcRequest(rpcRequest.ICX_GET_BLOCK_BY_HASH, requestParams); response = rpcConnection.connect(request); block = new Block(((JSONObject) response.result)); prevBlockHash = block.getPrevBlockHash(); mBlockListAdpater.dataList.add(block); } } catch (JSONException e) { e.printStackTrace(); } catch (rpcRequestException e) { e.printStackTrace(); } catch (rpcResponseException e) { e.printStackTrace(); } finally { Message msg = new Message(); msg.what = COMPLETE_LOAD_BLOCKS; msg.arg1 = i; mHandler.sendMessage(msg); } }).start(); }
void loadBlock(int count, Block lastBlock){ new Thread(() -> { ArrayList<Block> blocks = new ArrayList<>(); JSONObject requestParams; rpcRequest request; rpcResponse response; Block block; String prevBlockHash; int i = 0; try { if (lastBlock == null) { request = new rpcRequest(rpcRequest.ICX_GET_LAST_BLOCK); response = rpcConnection.connect(request); block = new Block(((JSONObject) response.result)); prevBlockHash = block.getPrevBlockHash(); blocks.add(block); i++; } else prevBlockHash = lastBlock.getPrevBlockHash(); for (; count > i; i++) { requestParams = new JSONObject(); requestParams.put("hash", "0x" + prevBlockHash); request = new rpcRequest(rpcRequest.ICX_GET_BLOCK_BY_HASH, requestParams); response = rpcConnection.connect(request); block = new Block(((JSONObject) response.result)); prevBlockHash = block.getPrevBlockHash(); blocks.add(block); } } catch (JSONException e) { e.printStackTrace(); } catch (rpcRequestException e) { e.printStackTrace(); } catch (rpcResponseException e) { e.printStackTrace(); } finally { Message msg = new Message(); msg.what = COMPLETE_LOAD_BLOCKS; msg.obj = blocks; mHandler.sendMessage(msg); } }).start(); }
349
public static int getForegroundWhiteOrBlack(int backgroundColor){ int alpha = Color.alpha(backgroundColor); Log.d("TempTag", "alpha : " + alpha); int blue = Color.blue(backgroundColor); int green = Color.green(backgroundColor); int red = Color.red(backgroundColor); double luminanceGris = (0.2126 * red) + (0.7152 * green) + (0.0722 * blue); if (luminanceGris < 128) { return Color.WHITE; } return Color.BLACK; }
public static int getForegroundWhiteOrBlack(int backgroundColor){ int blue = Color.blue(backgroundColor); int green = Color.green(backgroundColor); int red = Color.red(backgroundColor); double luminanceGris = (0.2126 * red) + (0.7152 * green) + (0.0722 * blue); if (luminanceGris < 128) { return Color.WHITE; } return Color.BLACK; }
350
private void selectCity(){ isBuildingUi = true; if (cityInformationPanel != null) { } cityData.removeAll(); currentlySelectedCity = cityList.getSelectedValue(); if (currentlySelectedCity != null) { cityInformationPanel = new CityInformationPanel(gameState, this, currentlySelectedCity, planet, owner, provider); cityData.add(cityInformationPanel, BorderLayout.CENTER); isBuildingUi = false; revalidate(); repaint(); } }
private void selectCity(){ isBuildingUi = true; cityData.removeAll(); currentlySelectedCity = cityList.getSelectedValue(); if (currentlySelectedCity != null) { cityInformationPanel = new CityInformationPanel(gameState, this, currentlySelectedCity, planet, owner, provider); cityData.add(cityInformationPanel, BorderLayout.CENTER); isBuildingUi = false; revalidate(); repaint(); } }
351
public void onViewCreated(View view, Bundle savedInstanceState){ super.onViewCreated(view, savedInstanceState); boolean dozeEnabled = Utils.isDozeEnabled(getActivity()); mTextView = (TextView) view.findViewById(R.id.switch_text); mTextView.setText(getString(dozeEnabled ? R.string.switch_bar_on : R.string.switch_bar_off)); View switchBar = view.findViewById(R.id.switch_bar); Switch switchWidget = (Switch) switchBar.findViewById(android.R.id.switch_widget); switchWidget.setChecked(dozeEnabled); switchWidget.setOnCheckedChangeListener(this); switchBar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switchWidget.setChecked(!switchWidget.isChecked()); } }); }
public void onViewCreated(View view, Bundle savedInstanceState){ super.onViewCreated(view, savedInstanceState); boolean dozeEnabled = Utils.isDozeEnabled(getActivity()); mTextView = view.findViewById(R.id.switch_text); mTextView.setText(getString(dozeEnabled ? R.string.switch_bar_on : R.string.switch_bar_off)); View switchBar = view.findViewById(R.id.switch_bar); Switch switchWidget = switchBar.findViewById(android.R.id.switch_widget); switchWidget.setChecked(dozeEnabled); switchWidget.setOnCheckedChangeListener(this); switchBar.setOnClickListener(v -> switchWidget.setChecked(!switchWidget.isChecked())); }
352
public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { switch(sccalgorithmID) { case RSA_SHA_512: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_512, key); case RSA_SHA_256: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_256, key); case RSA_ECB: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_ECB, key); default: break; } } } } else { switch(usedAlgorithm) { case RSA_SHA_512: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_512, key); case RSA_SHA_256: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_256, key); case RSA_ECB: return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_ECB, key); default: break; } } } else { throw new SCCException("The used SCCKey has the wrong KeyType for this use case.", new InvalidKeyException()); } throw new SCCException("No supported algorithm", new CoseException(null)); }
public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{ if (key.getKeyType() == KeyType.Asymmetric) { if (usedAlgorithm == null) { ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption(); for (int i = 0; i < algorithms.size(); i++) { SCCAlgorithm sccalgorithmID = algorithms.get(i); if (getEnums().contains(sccalgorithmID)) { return decideForAlgoAsymmetric(sccalgorithmID, key, plaintext); } } } else { return decideForAlgoAsymmetric(usedAlgorithm, key, plaintext); } } else { throw new SCCException("The used SCCKey has the wrong KeyType for this use case.", new InvalidKeyException()); } throw new SCCException("No supported algorithm", new CoseException(null)); }
353
public Integer getDeduplicationSnapshotInterval(String topic) throws PulsarAdminException{ try { return getDeduplicationSnapshotIntervalAsync(topic).get(this.readTimeoutMs, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw (PulsarAdminException) e.getCause(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new PulsarAdminException(e); } catch (TimeoutException e) { throw new PulsarAdminException.TimeoutException(e); } }
public Integer getDeduplicationSnapshotInterval(String topic) throws PulsarAdminException{ return sync(() -> getDeduplicationSnapshotIntervalAsync(topic)); }
354
public void visit(MethodCallExpr callExpr, Object arg){ String name = callExpr.getName(); Expression expr = callExpr.getScope(); String scope = expr == null ? null : expr.toString(); List<Expression> args = callExpr.getArgs(); ContractElement p = initConstraint(); p.setProgramVersion(ProgramVersion.getOrCreate(programName, this.version)); p.setCuName(this.cuName); p.setMethodDeclaration(this.methodDeclaration); p.setLineNo(callExpr.getBeginLine()); if (args.size() > 0 && checkImports(name, scope)) { if (name.equals("allElementsOfType")) { p.setKind(ConstraintType.CommonsLang2AllElementsOfType); p.setCondition("all of " + args.get(0).toString() + " instanceOf " + args.get(1).toString()); p.setAdditionalInfo(encodeMessageArgs(args, 2)); consumer.constraintFound(p); } } super.visit(callExpr, arg); }
public void visit(MethodCallExpr callExpr, Object arg){ String name = callExpr.getName(); Expression expr = callExpr.getScope(); String scope = expr == null ? null : expr.toString(); List<Expression> args = callExpr.getArgs(); ContractElement p = initConstraint(); p.setLineNo(callExpr.getBeginLine()); p.setProgramVersion(ProgramVersion.getOrCreate(programName, this.version)); if (args.size() > 0 && checkImports(name, scope)) { if (name.equals("allElementsOfType")) { p.setKind(ConstraintType.CommonsLang2AllElementsOfType); p.setCondition("all of " + args.get(0).toString() + " instanceOf " + args.get(1).toString()); p.setAdditionalInfo(encodeMessageArgs(args, 2)); consumer.constraintFound(p); } } super.visit(callExpr, arg); }
355
protected void run(String[] args) throws Exception{ LOG.info("Running 'run' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); final ProgramOptions programOptions = new ProgramOptions(commandLine); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } if (!programOptions.isPython()) { if (programOptions.getJarFilePath() == null) { throw new CliArgsException("Java program should be specified a JAR file."); } } final PackagedProgram program; try { LOG.info("Building program from JAR file"); program = buildProgram(programOptions); } catch (FileNotFoundException e) { throw new CliArgsException("Could not build the program from JAR file: " + e.getMessage(), e); } final List<URL> jobJars = program.getJobJarAndDependencies(); final Configuration effectiveConfiguration = getEffectiveConfiguration(commandLine, programOptions, jobJars); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); try { executeProgram(effectiveConfiguration, program); } finally { program.deleteExtractedLibraries(); } }
protected void run(String[] args) throws Exception{ LOG.info("Running 'run' command."); final Options commandOptions = CliFrontendParser.getRunCommandOptions(); final CommandLine commandLine = getCommandLine(commandOptions, args, true); final ProgramOptions programOptions = ProgramOptions.create(commandLine); if (commandLine.hasOption(HELP_OPTION.getOpt())) { CliFrontendParser.printHelpForRun(customCommandLines); return; } programOptions.validate(); final PackagedProgram program; try { LOG.info("Building program from JAR file"); program = buildProgram(programOptions); } catch (FileNotFoundException e) { throw new CliArgsException("Could not build the program from JAR file: " + e.getMessage(), e); } final List<URL> jobJars = program.getJobJarAndDependencies(); final Configuration effectiveConfiguration = getEffectiveConfiguration(commandLine, programOptions, jobJars); LOG.debug("Effective executor configuration: {}", effectiveConfiguration); try { executeProgram(effectiveConfiguration, program); } finally { program.deleteExtractedLibraries(); } }
356
private int[] getKavaImpressionInfo(PKMediaConfig pkMediaConfig){ int[] impressionResponse = new int[] { -1, 0 }; if (pkMediaConfig.getMediaEntry() != null && pkMediaConfig.getMediaEntry().getMetadata() != null && pkMediaConfig.getMediaEntry().getMetadata().containsKey(kavaPartnerIdKey)) { String partnerId = pkMediaConfig.getMediaEntry().getMetadata().get(kavaPartnerIdKey); impressionResponse[0] = !TextUtils.isEmpty(partnerId) ? Integer.parseInt(partnerId) : 0; if (impressionResponse[0] <= 0) { impressionResponse[1] = 1; } } if (!loadedPlugins.containsKey(kavaPluginKey) && impressionResponse[0] > 0) { impressionResponse[1] = 1; } else if (!loadedPlugins.containsKey(kavaPluginKey) && impressionResponse[0] <= 0) { impressionResponse[1] = 1; } else if (!loadedPlugins.containsKey(kavaPluginKey)) { impressionResponse[1] = 1; } else if (loadedPlugins.containsKey(kavaPluginKey) && impressionResponse[0] <= 0) { impressionResponse[1] = 1; } return impressionResponse; }
private Pair<Integer, String> getKavaImpressionInfo(PKMediaConfig pkMediaConfig){ final String kavaPartnerIdKey = "kavaPartnerId"; final String kavaEntryIdKey = "entryId"; int kavaPartnerId = 0; String kavaEntryId = null; if (pkMediaConfig.getMediaEntry() != null && pkMediaConfig.getMediaEntry().getMetadata() != null) { if (pkMediaConfig.getMediaEntry().getMetadata().containsKey(kavaPartnerIdKey)) { String partnerId = pkMediaConfig.getMediaEntry().getMetadata().get(kavaPartnerIdKey); kavaPartnerId = Integer.parseInt(partnerId != null && TextUtils.isDigitsOnly(partnerId) && !TextUtils.isEmpty(partnerId) ? partnerId : "0"); } if (pkMediaConfig.getMediaEntry().getMetadata().containsKey(kavaEntryIdKey)) { kavaEntryId = pkMediaConfig.getMediaEntry().getMetadata().get(kavaEntryIdKey); } } return Pair.create(kavaPartnerId, kavaEntryId); }
357
public Map<String, Object> queryDataSourceList(User loginUser, Integer type){ Map<String, Object> result = new HashMap<>(); List<DataSource> datasourceList; if (isAdmin(loginUser)) { datasourceList = dataSourceMapper.listAllDataSourceByType(type); } else { datasourceList = dataSourceMapper.queryDataSourceByType(loginUser.getId(), type); } result.put(Constants.DATA_LIST, datasourceList); putMsg(result, Status.SUCCESS); return result; }
public Result<List<DataSource>> queryDataSourceList(User loginUser, Integer type){ List<DataSource> datasourceList; if (isAdmin(loginUser)) { datasourceList = dataSourceMapper.listAllDataSourceByType(type); } else { datasourceList = dataSourceMapper.queryDataSourceByType(loginUser.getId(), type); } return Result.success(datasourceList); }
358
public static void setShapeType(EntityPlayer player, ItemStack stack, boolean isCurved, int shapeType){ World world = player.worldObj; if ((isCurved ? Configs.sculptShapeTypeCurved : Configs.sculptShapeTypeFlat).isPerTool()) { if (!world.isRemote) { setInt(player, stack, shapeType, NBTKeys.SHAPE_TYPE); } } else { ISculptSettingsHandler cap = SculptSettingsHandler.getCapability(player); if (cap != null) { if (isCurved) { cap.setShapeTypeCurved(shapeType); } else { cap.setShapeTypeFlat(shapeType); } } } if (world.isRemote) { ExtraBitManipulation.packetNetwork.sendToServer(new PacketSetShapeType(isCurved, shapeType)); } }
public static void setShapeType(EntityPlayer player, ItemStack stack, boolean isCurved, int shapeType){ World world = player.worldObj; if ((isCurved ? Configs.sculptShapeTypeCurved : Configs.sculptShapeTypeFlat).isPerTool()) { if (!world.isRemote) setInt(player, stack, shapeType, NBTKeys.SHAPE_TYPE); } else { ISculptSettingsHandler cap = SculptSettingsHandler.getCapability(player); if (cap != null) { if (isCurved) { cap.setShapeTypeCurved(shapeType); } else { cap.setShapeTypeFlat(shapeType); } } } if (world.isRemote) ExtraBitManipulation.packetNetwork.sendToServer(new PacketSetShapeType(isCurved, shapeType)); }
359
protected DDMFormField createNestedDDMFormFields(String parentName, String childName){ DDMFormField parentDDMFormField = createTextDDMFormField(parentName); List<DDMFormField> nestedDDMFormFields = new ArrayList<>(); nestedDDMFormFields.add(createSelectDDMFormField(childName)); parentDDMFormField.setNestedDDMFormFields(nestedDDMFormFields); return parentDDMFormField; }
protected DDMFormField createNestedDDMFormFields(String parentName, String childName){ DDMFormField parentDDMFormField = createTextDDMFormField(parentName); parentDDMFormField.setNestedDDMFormFields(Arrays.asList(createSelectDDMFormField(childName))); return parentDDMFormField; }
360
public void doNotFail_WhenOsIsNotWindows_And_NoCS_FilesDetected() throws MessageException{ tester = SensorContextTester.create(new File("src/test/resources")); when(system.isOsWindows()).thenReturn(false); sensor.execute(tester); }
public void doNotFail_WhenOsIsNotWindows_And_NoCS_FilesDetected() throws MessageException{ when(system.isOsWindows()).thenReturn(false); sensor.execute(tester); }
361
private void exitTwillio(){ if (twillioPhone != null) { twillioPhone.shutDownTwillio(); twillioPhone.setListeners(null, null, null); twillioPhone = null; } int pid = android.os.Process.myPid(); android.os.Process.killProcess(pid); }
private void exitTwillio(){ if (twillioPhone != null) { twillioPhone.shutDownTwillio(); twillioPhone.setListeners(null, null, null); twillioPhone = null; } }
362
public DataType getDataType(Type type){ OriginalType originalType = type.getOriginalType(); if (originalType == OriginalType.DECIMAL) { return DataType.NUMERIC; } return DataType.BIGINT; }
public DataType getDataType(Type type){ if (type.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation) { return DataType.NUMERIC; } return DataType.BIGINT; }
363
protected void onProduce(StreamDataAcceptor<T> dataAcceptor){ assert dataAcceptor != null; if (supplier == null) { if (!iterator.hasNext()) { eventloop.post(this::sendEndOfStream); return; } supplier = iterator.next(); internalConsumer = new InternalConsumer(); supplier.streamTo(internalConsumer); } supplier.resume(dataAcceptor); }
protected void onProduce(@NotNull StreamDataAcceptor<T> dataAcceptor){ if (supplier == null) { if (!iterator.hasNext()) { eventloop.post(this::sendEndOfStream); return; } supplier = iterator.next(); internalConsumer = new InternalConsumer(); supplier.streamTo(internalConsumer); } supplier.resume(dataAcceptor); }
364
public static String parseEvent(String instruction) throws DukeException, IOException{ String result = ""; if (instruction.length() < 7) { throw new DukeException("Oops!!! The description of a event cannot be empty."); } else { String taskDescription = ""; int currIndex = 5; while (currIndex < instruction.length() && !instruction.substring(currIndex).startsWith(" /")) { taskDescription += instruction.substring(currIndex, currIndex + 1); currIndex++; } if (currIndex == instruction.length() || currIndex + 5 >= instruction.length()) { throw new DukeException("I think you forgot to key in your event timing!"); } else if (instruction.charAt(currIndex + 7) != '/' && instruction.charAt(currIndex + 10) != '/') { throw new DukeException("Please format the date as dd/mm/yyy"); } else if (instruction.substring(currIndex).length() < 25) { throw new DukeException("Please include the start and end times in the 24 hour " + "format (e.g. 15:00-16:00)"); } else { String by = instruction.substring(currIndex + 5); Task newEvent = new Event(taskDescription, by); TaskList.addTaskAndUpdate(newEvent); result += "Got it! I've added this task:\n"; result += "\t" + newEvent.toString() + "\n"; result += "Now you have " + TaskList.getCounter() + " task(s) in the list.\n"; return result; } } }
public static String parseEvent(String instruction) throws DukeException, IOException{ if (instruction.length() < 7) { throw new DukeException(Ui.EMPTY_EVENT_DESCRIPTION); } else { String taskDescription = ""; int currIndex = 5; while (currIndex < instruction.length() && !instruction.substring(currIndex).startsWith(" /")) { taskDescription += instruction.substring(currIndex, currIndex + 1); currIndex++; } if (currIndex == instruction.length() || currIndex + 5 >= instruction.length()) { throw new DukeException(Ui.INCOMPLETE_EVENT_TIMINGS); } else if (instruction.charAt(currIndex + 7) != '/' && instruction.charAt(currIndex + 10) != '/') { throw new DukeException(Ui.WRONGLY_FORMATTED_DATE); } else if (instruction.substring(currIndex).length() < 25) { throw new DukeException(Ui.WRONGLY_FORMATTED_EVENT_TIMINGS); } else { String by = instruction.substring(currIndex + 5); Task newEvent = new Event(taskDescription, by); return TaskList.addTaskAndUpdate(newEvent); } } }
365
public void onBeaconServiceConnect(){ RangeNotifier rangeNotifier = (beacons, region) -> { if (!beacons.isEmpty()) { System.out.println("didRangeBeaconsInRegion called with beacon count: " + beacons.size()); System.out.println(">>>> RANGING " + Arrays.toString(beacons.toArray(new Beacon[] {}))); Beacon[] beaconsArray = beacons.toArray(new Beacon[] {}); Map<BeaconID, Integer> beaconsOverview = new HashMap<>(); for (Beacon b : beaconsArray) { beaconsOverview.put(new BeaconID(b.getId1(), b.getId2(), b.getId3()), b.getRssi()); } beaconLocationManager.addNewBeaconStatus(beaconsOverview); } }; try { beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); beaconManager.addRangeNotifier(rangeNotifier); beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); beaconManager.addRangeNotifier(rangeNotifier); } catch (RemoteException e) { e.printStackTrace(); } }
public void onBeaconServiceConnect(){ RangeNotifier rangeNotifier = (beacons, region) -> { if (!beacons.isEmpty()) { Log.d("BeaconRanging", "called with beacon count: " + beacons.size()); Beacon[] beaconsArray = beacons.toArray(new Beacon[] {}); Map<BeaconID, Integer> beaconsOverview = new HashMap<>(); for (Beacon b : beaconsArray) { beaconsOverview.put(new BeaconID(b.getId1(), b.getId2(), b.getId3()), b.getRssi()); } beaconLocationManager.addNewBeaconStatus(beaconsOverview); } }; try { beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); beaconManager.addRangeNotifier(rangeNotifier); beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); beaconManager.addRangeNotifier(rangeNotifier); } catch (RemoteException e) { e.printStackTrace(); } }
366
public void testThatWarningPetstoreSwaggerContainsWarnings() throws IOException{ String specification = resource("/swagger/invalid/warning-petstore.swagger.json"); SwaggerModelInfo info = SwaggerHelper.parse(specification, true); assertThat(info.getErrors()).isEmpty(); assertThat(info.getWarnings()).hasSize(3); System.out.println(info.getWarnings()); }
public void testThatWarningPetstoreSwaggerContainsWarnings() throws IOException{ final String specification = resource("/swagger/invalid/warning-petstore.swagger.json"); final SwaggerModelInfo info = SwaggerHelper.parse(specification, true); assertThat(info.getErrors()).isEmpty(); assertThat(info.getWarnings()).hasSize(3); }
367
public User parseToken(String token){ LOGGER.info("token processing has been started"); try { Claims body = Jwts.parser().setSigningKey(JwtTokenParams.SECRET).parseClaimsJws(token).getBody(); String username = body.getSubject(); boolean enabled = (Boolean) body.get("isEnabled"); Set<GrantedAuthority> authorities = parseAuthorities((List<Map<String, String>>) body.get("authorities")); return new User(username, null, enabled, authorities); } catch (Exception e) { String message = "Token is not valid!"; LOGGER.error(message); throw new JwtTokenMalformedException(message, e); } }
public User parseToken(String token) throws Exception{ LOGGER.info("token processing has been started"); Claims body = Jwts.parser().setSigningKey(JwtTokenParams.SECRET).parseClaimsJws(token).getBody(); String username = body.getSubject(); boolean enabled = (Boolean) body.get("isEnabled"); Set<GrantedAuthority> authorities = parseAuthorities((List<Map<String, String>>) body.get("authorities")); return new User(username, null, enabled, authorities); }
368
public void onForceRefresh(){ bookRowItems.clear(); try { fillListAdapter(); } catch (Exception e) { Log.e(this.getClass().getSimpleName(), e.getMessage(), e); } }
public void onForceRefresh(){ bookRowItems.clear(); fillListAdapter(); }
369
public List<RelationshipVector> getRelationships(final String relationshipName){ List<RelationshipVector> myrelationships = relationships.get(relationshipName.toLowerCase()); ArrayList<RelationshipVector> retRels = new ArrayList<RelationshipVector>(myrelationships); return retRels; }
public List<RelationshipVector> getRelationships(final String relationshipName){ List<RelationshipVector> myrelationships = relationships.get(relationshipName.toLowerCase()); return new ArrayList<>(myrelationships); }
370
public void openSecureChannel(EnumSet<SecurityLevel> securityLevel) throws IOException, JavaCardException{ if (securityLevel.contains(SecurityLevel.C_DECRYPTION) && !securityLevel.contains(SecurityLevel.C_MAC)) { throw new IllegalArgumentException("C_DECRYPTION must be combined with C_MAC"); } if (securityLevel.contains(SecurityLevel.R_DECRYPTION) && !securityLevel.contains(SecurityLevel.R_MAC)) { throw new IllegalArgumentException("R_DECRYPTION must be combined with R_MAC"); } byte hostKeyVersionNumber = context.getCardProperties().getKeyVersionNumber(); Scp02Context scp02Context = initializeUpdate(hostKeyVersionNumber); byte[] icv = externalAuthenticate(scp02Context, securityLevel); channel = new Scp02ApduChannel(context, securityLevel, icv); channel.setRicv(icv); }
public void openSecureChannel(EnumSet<SecurityLevel> securityLevel) throws IOException, JavaCardException{ if (securityLevel.contains(SecurityLevel.C_DECRYPTION) && !securityLevel.contains(SecurityLevel.C_MAC)) { throw new IllegalArgumentException("C_DECRYPTION must be combined with C_MAC"); } byte hostKeyVersionNumber = context.getCardProperties().getKeyVersionNumber(); Scp02Context scp02Context = initializeUpdate(hostKeyVersionNumber); byte[] icv = externalAuthenticate(scp02Context, securityLevel); channel = new Scp02ApduChannel(context, securityLevel, icv); channel.setRicv(icv); }
371
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); etUsernameSignup = findViewById(R.id.etUsernameSignup); etPasswordSignup = findViewById(R.id.etPasswordSignup); btnCreateAccount = findViewById(R.id.btnCreateAccount); ibBack = findViewById(R.id.ibBack); btnCreateAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ParseUser user = new ParseUser(); user.setUsername(etUsernameSignup.getText().toString()); user.setPassword(etPasswordSignup.getText().toString()); user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { if (e != null) { Log.e("SignupActivity", "Sign up unsuccessful", e); return; } Toast.makeText(SignupActivity.this, "success", Toast.LENGTH_SHORT).show(); Intent i = new Intent(SignupActivity.this, LoginActivity.class); startActivity(i); finish(); } }); } }); ibBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(SignupActivity.this, LoginActivity.class); startActivity(i); finish(); } }); }
protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); etUsernameSignup = findViewById(R.id.etUsernameSignup); etPasswordSignup = findViewById(R.id.etPasswordSignup); btnCreateAccount = findViewById(R.id.btnCreateAccount); ibBack = findViewById(R.id.ibBack); btnCreateAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ParseUser user = new ParseUser(); user.setUsername(etUsernameSignup.getText().toString()); user.setPassword(etPasswordSignup.getText().toString()); user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { if (e != null) { Log.e("SignupActivity", "Sign up unsuccessful", e); return; } Intent i = new Intent(SignupActivity.this, LoginActivity.class); startActivity(i); finish(); } }); } }); ibBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(SignupActivity.this, LoginActivity.class); startActivity(i); finish(); } }); }
372
public void sendSMS(String smscPDUStr, String pduStr, final Message response){ Rlog.d(TAG, "sendSMS"); if (smscPDUStr == null) smscPDUStr = "00"; final byte[] smscPDU = IccUtils.hexStringToBytes(smscPDUStr); final byte[] pdu = IccUtils.hexStringToBytes(pduStr); runOnDbusThread(new Runnable() { @Override public void run() { try { synchronized (mMapSmsDbusPathToSenderCallback) { Path sentMessage = mMessenger.SendPdu(smscPDU, pdu); mMapSmsDbusPathToSenderCallback.put(sentMessage.getPath(), response); } } catch (Throwable t) { Rlog.e(TAG, "Error sending msg", t); respondExc("sendSMS", response, GENERIC_FAILURE, null); } } }); }
public Object sendSMS(String smscPDUStr, String pduStr){ Rlog.d(TAG, "sendSMS"); if (smscPDUStr == null) smscPDUStr = "00"; final byte[] smscPDU = IccUtils.hexStringToBytes(smscPDUStr); final byte[] pdu = IccUtils.hexStringToBytes(pduStr); synchronized (mMapSmsDbusPathToSenderCallback) { Path sentMessage = mMessenger.SendPdu(smscPDU, pdu); mMapSmsDbusPathToSenderCallback.put(sentMessage.getPath(), RilWrapper.getCurrentMessage()); } return RilWrapper.RETURN_LATER; }
373
private void fetchDataNormalSearch(String query){ searchBooks = new ArrayList<>(); String url = Uri.parse(Constants.LOCAL_BOOK_SEARCH).buildUpon().appendQueryParameter("query", query).build().toString(); final ProgressDialog dialog = new ProgressDialog(this); dialog.setMessage("Searching"); dialog.setCancelable(false); dialog.setInverseBackgroundForced(false); dialog.show(); JsonObjectRequest jObject = new JsonObjectRequest(Method.GET, url, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { dialog.hide(); try { boolean status = response.getBoolean("status"); if (status) { searchBooks.add("Local Results"); extractSearchResponse(response, true); fetchDataGoogleSearch(myEditText.getText().toString()); size = searchBooks.size() - 1; } else { size = 0; fetchDataGoogleSearch(myEditText.getText().toString()); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { dialog.hide(); } }); RequestQueue queue = Volley.newRequestQueue(this); queue.add(jObject); }
private void fetchDataNormalSearch(String query){ searchBooks = new ArrayList<>(); String url = Uri.parse(Constants.LOCAL_BOOK_SEARCH).buildUpon().appendQueryParameter("query", query).build().toString(); AppUtils.getInstance().showProgressDialog(this, "Searching"); JsonObjectRequest jObject = new JsonObjectRequest(Method.GET, url, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { AppUtils.getInstance().dismissProgressDialog(); try { boolean status = response.getBoolean("status"); if (status) { searchBooks.add("Local Results"); extractSearchResponse(response, true); fetchDataGoogleSearch(myEditText.getText().toString()); size = searchBooks.size() - 1; } else { size = 0; fetchDataGoogleSearch(myEditText.getText().toString()); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppUtils.getInstance().dismissProgressDialog(); } }); RequestQueue queue = Volley.newRequestQueue(this); queue.add(jObject); }
374
public Result queryTenantlistPaging(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "searchVal", required = false) String searchVal, @RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize){ logger.info("login user {}, list paging, pageNo: {}, searchVal: {}, pageSize: {}", loginUser.getUserName(), pageNo, searchVal, pageSize); Map<String, Object> result = checkPageParams(pageNo, pageSize); if (result.get(Constants.STATUS) != Status.SUCCESS) { return returnDataListPaging(result); } searchVal = ParameterUtils.handleEscapes(searchVal); result = tenantService.queryTenantList(loginUser, searchVal, pageNo, pageSize); return returnDataListPaging(result); }
public Result<PageListVO<Tenant>> queryTenantlistPaging(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "searchVal", required = false) String searchVal, @RequestParam("pageNo") Integer pageNo, @RequestParam("pageSize") Integer pageSize){ logger.info("login user {}, list paging, pageNo: {}, searchVal: {}, pageSize: {}", loginUser.getUserName(), pageNo, searchVal, pageSize); CheckParamResult checkResult = checkPageParams(pageNo, pageSize); if (checkResult.getStatus() != Status.SUCCESS) { return Result.error(checkResult); } searchVal = ParameterUtils.handleEscapes(searchVal); return tenantService.queryTenantList(loginUser, searchVal, pageNo, pageSize); }
375
protected void azureNodeAction(NodeActionEvent event){ try { springCloudAppNodePresenter.onDeleteApp(id); } catch (IOException e) { DefaultLoader.getUIHelper().showException(String.format(FAILED_TO_DELETE_APP, SpringCloudAppNode.this.getName()), e, ERROR_DELETING_APP, false, true); } }
protected void azureNodeAction(NodeActionEvent event){ springCloudAppNodePresenter.onDeleteApp(id); }
376
public Result createProject(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("projectName") String projectName, @RequestParam(value = "description", required = false) String description){ logger.info("login user {}, create project name: {}, desc: {}", loginUser.getUserName(), projectName, description); Map<String, Object> result = projectService.createProject(loginUser, projectName, description); return returnDataList(result); }
public Result<Integer> createProject(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam("projectName") String projectName, @RequestParam(value = "description", required = false) String description){ logger.info("login user {}, create project name: {}, desc: {}", loginUser.getUserName(), projectName, description); return projectService.createProject(loginUser, projectName, description); }
377
protected Optional<PixelDiffFilter> load(final MatchResult regex){ final String value = regex.group(1); final boolean specifiedAsDouble = value.contains("."); final double pixelDiff = Double.parseDouble(value); return Optional.of(new PixelDiffFilter(specifiedAsDouble, pixelDiff)); }
protected Optional<PixelDiffFilter> load(final MatchResult regex){ final String value = regex.group(1); final double pixelDiff = Double.parseDouble(value); return Optional.of(new PixelDiffFilter(value, pixelDiff)); }
378
public void run(){ LOGGER_RECEIVER.info("Start the datagramm receiver."); byte[] receiveBuffer = new byte[512]; while (!exit) { try { DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length); LOGGER_RECEIVER.info("Wait for packet ..."); socket.receive(packet); LOGGER_RECEIVER.info("Received a packet: {}", packet); if (PacketConverter.responseFromPacket(packet) != null) { Z21Response response = PacketConverter.responseFromPacket(packet); for (Z21ResponseListener listener : responseListeners) { for (ResponseTypes type : listener.getListenerTypes()) { if (type == response.boundType) { listener.responseReceived(type, response); } } } } else { Z21Broadcast broadcast = PacketConverter.broadcastFromPacket(packet); if (broadcast != null) { for (Z21BroadcastListener listener : broadcastListeners) { for (BroadcastTypes type : listener.getListenerTypes()) { if (type == broadcast.boundType) { listener.onBroadCast(type, broadcast); } } } } } } catch (IOException e) { if (!exit) LOGGER_RECEIVER.warn("Failed to get a message from z21... ", e); } } LOGGER_RECEIVER.info("The receiver has terminated."); }
public void run(){ LOGGER_RECEIVER.info("Start the datagramm receiver."); byte[] receiveBuffer = new byte[512]; while (!exit) { try { DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length); LOGGER_RECEIVER.info("Wait for packet ..."); socket.receive(packet); z21Drive.record.Z21Record z21Record = Z21RecordFactory.fromPacket(packet); if (z21Record != null) { LOGGER_RECEIVER.info("Received '{}'", z21Record); if (z21Record.isResponse()) { for (Z21ResponseListener listener : responseListeners) { for (Z21RecordType type : listener.getListenerTypes()) { if (type == z21Record.getRecordType()) { listener.responseReceived(type, z21Record); } } } } else if (z21Record.isBroadCast()) { for (Z21BroadcastListener listener : broadcastListeners) { for (Z21RecordType type : listener.getListenerTypes()) { if (type == z21Record.getRecordType()) { listener.onBroadCast(type, z21Record); } } } } } } catch (IOException e) { if (!exit) LOGGER_RECEIVER.warn("Failed to get a message from z21... ", e); } } LOGGER_RECEIVER.info("The receiver has terminated."); }
379
protected Boolean removeExistingEntity(String localId){ boolean deleted = false; try { ObjectId tempEntId = projectRepo.getProjectIdById(localId).get(0).getId(); if (localId.equalsIgnoreCase(projectRepo.getProjectIdById(localId).get(0).getpId())) { projectRepo.delete(tempEntId); deleted = true; } } catch (IndexOutOfBoundsException ioobe) { logger.debug("Nothing matched the redundancy checking from the database"); } catch (Exception e) { logger.error("There was a problem validating the redundancy of the data model"); e.printStackTrace(); } return deleted; }
protected Boolean removeExistingEntity(String localId){ boolean deleted = false; try { ObjectId tempEntId = projectRepo.getProjectIdById(localId).get(0).getId(); if (localId.equalsIgnoreCase(projectRepo.getProjectIdById(localId).get(0).getpId())) { projectRepo.delete(tempEntId); deleted = true; } } catch (IndexOutOfBoundsException ioobe) { LOGGER.debug("Nothing matched the redundancy checking from the database", ioobe); } catch (Exception e) { LOGGER.error("There was a problem validating the redundancy of the data model", e); } return deleted; }
380
private boolean attemptToBreedCow(final ItemStack currentItemStack, final EntityPlayer entityPlayer){ if (isBreedingItem(currentItemStack) && getGrowingAge() == 0) { if (!entityPlayer.capabilities.isCreativeMode) { currentItemStack.shrink(1); if (currentItemStack.isEmpty()) { entityPlayer.inventory.setInventorySlotContents(entityPlayer.inventory.currentItem, ItemStack.EMPTY); } } setInLove(entityPlayer); return true; } return false; }
private boolean attemptToBreedCow(final ItemStack currentItemStack, final EntityPlayer entityPlayer){ if (isBreedingItem(currentItemStack) && getGrowingAge() == 0) { consumeItemFromStack(entityPlayer, currentItemStack); setInLove(entityPlayer); return true; } return false; }
381
public Program loadProgram(final Id.Program id) throws IOException, ApplicationNotFoundException, ProgramNotFoundException{ ApplicationMeta appMeta = appsTx.get().executeUnchecked(new TransactionExecutor.Function<AppMetadataStore, ApplicationMeta>() { @Override public ApplicationMeta apply(AppMetadataStore mds) throws Exception { return mds.getApplication(id.getNamespaceId(), id.getApplicationId()); } }, apps.get()); if (appMeta == null) { throw new ApplicationNotFoundException(Id.Application.from(id.getNamespaceId(), id.getApplicationId())); } if (!programExists(id, appMeta.getSpec())) { throw new ProgramNotFoundException(id); } Location programLocation = getProgramLocation(id); Preconditions.checkArgument(appMeta.getLastUpdateTs() >= programLocation.lastModified(), "Newer program update time than the specification update time. " + "Application must be redeployed"); return Programs.create(programLocation); }
public ProgramDescriptor loadProgram(final Id.Program id) throws IOException, ApplicationNotFoundException, ProgramNotFoundException{ ApplicationMeta appMeta = appsTx.get().executeUnchecked(new TransactionExecutor.Function<AppMetadataStore, ApplicationMeta>() { @Override public ApplicationMeta apply(AppMetadataStore mds) throws Exception { return mds.getApplication(id.getNamespaceId(), id.getApplicationId()); } }, apps.get()); if (appMeta == null) { throw new ApplicationNotFoundException(Id.Application.from(id.getNamespaceId(), id.getApplicationId())); } if (!programExists(id, appMeta.getSpec())) { throw new ProgramNotFoundException(id); } return new ProgramDescriptor(id.toEntityId(), appMeta.getSpec()); }
382
public void processEl187Test(){ StringBuilder xml_ = new StringBuilder(); xml_.append("$public $class pkg.ExTwo {\n"); xml_.append(" $private $int get(Integer... i){\n"); xml_.append(" $return 2i;\n"); xml_.append(" }\n"); xml_.append(" $public $int get(Number... i){\n"); xml_.append(" $return 1i;\n"); xml_.append(" }\n"); xml_.append("}\n"); String g_ = StringUtil.concat("pkg.ExTwo"); ClassMethodIdVarArg cid_ = getFct3(xml_, g_, "myvar.get((Integer[])$null)"); assertEq("pkg.ExTwo", cid_.getClassName()); MethodId id_ = cid_.getConstraints(); assertEq("get", id_.getName()); StringList params_ = id_.getParametersTypes(); assertEq(1, params_.size()); assertEq("java.lang.Number", params_.last()); assertTrue(id_.isVararg()); assertEq(-1, cid_.getNaturalVararg()); assertTrue(!id_.isStaticMethod()); }
public void processEl187Test(){ StringBuilder xml_ = new StringBuilder(); xml_.append("$public $class pkg.ExTwo {\n"); xml_.append(" $private $int get(Integer... i){\n"); xml_.append(" $return 2i;\n"); xml_.append(" }\n"); xml_.append(" $public $int get(Number... i){\n"); xml_.append(" $return 1i;\n"); xml_.append(" }\n"); xml_.append("}\n"); String g_ = StringUtil.concat("pkg.ExTwo"); ClassMethodIdVarArg cid_ = getFct3(xml_, g_, "myvar.get((Integer[])$null)"); assertEq("pkg.ExTwo", cid_.getClassName()); MethodId id_ = cid_.getConstraints(); assertEq("get", id_.getName()); assertEq(1, id_.getParametersTypesLength()); assertEq("java.lang.Number", id_.getParametersType(0)); assertTrue(id_.isVararg()); assertEq(-1, cid_.getNaturalVararg()); assertTrue(!id_.isStaticMethod()); }
383
public void consolidate(@RequestBody final TestSuite test){ if (test == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Test suite is null"); } if (test.getCpu() == null || test.getMemory() == null || test.getJvm() == null || test.getVendor() == null || test.getOsFamily() == null || test.getOsVersion() == null) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Invalid test suite information"); } if (test.getCallsList() == null || test.getCallsList().isEmpty()) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "No calls to consolidate"); } final TestSuiteDTO suite = TestSuiteBridge.fromProtobuf(test); final ArrayList<CallDTO> calls = new ArrayList<>(); for (final TestSuite.ClientCall ccall : test.getCallsList()) { CallDTO call = CallBridge.fromProtobuf(ccall); if (ccall == null) { continue; } call = cache.mergeCall(call); if (call != null) { calls.add(call); } } suite.setCalls(calls); dao.save(suite); }
public void consolidate(@RequestBody final TestSuite test){ try { business.consolidate(TestSuiteBridge.fromProtobuf(test)); } catch (final InvalidParametersException e) { throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, e.getMessage()); } }
384
public void onBlockDispensing(final BlockDispenseEvent e){ Block dispenser = e.getBlock(); if (dispenser.getType() == Material.DISPENSER) { final Dispenser d = (Dispenser) dispenser.getState(); BlockFace face = ((Directional) dispenser.getBlockData()).getFacing(); Block block = dispenser.getRelative(face); Block chest = dispenser.getRelative(face.getOppositeFace()); SlimefunItem machine = BlockStorage.check(dispenser); if (machine != null) { for (ItemHandler handler : SlimefunItem.getHandlers("AutonomousMachineHandler")) { if (((AutonomousMachineHandler) handler).onBlockDispense(e, dispenser, d, block, chest, machine)) break; } } else { for (int i = 0; i < d.getInventory().getContents().length; i++) { for (ItemHandler handler : SlimefunItem.getHandlers("AutonomousToolHandler")) { if (((AutonomousToolHandler) handler).onBlockDispense(e, dispenser, d, block, chest, i)) break; } } } } }
public void onBlockDispensing(final BlockDispenseEvent e){ Block dispenser = e.getBlock(); if (dispenser.getType() == Material.DISPENSER) { final Dispenser d = (Dispenser) dispenser.getState(); BlockFace face = ((Directional) dispenser.getBlockData()).getFacing(); Block block = dispenser.getRelative(face); Block chest = dispenser.getRelative(face.getOppositeFace()); SlimefunItem machine = BlockStorage.check(dispenser); if (machine != null) { for (ItemHandler handler : SlimefunItem.getHandlers("AutonomousMachineHandler")) { if (((AutonomousMachineHandler) handler).onBlockDispense(e, dispenser, d, block, chest, machine)) break; } } } }
385
public ValueHolder<V> getAndFault(K key) throws CacheAccessException{ getOperationObserver.begin(); checkKey(key); ValueHolder<V> mappedValue = null; try { mappedValue = backingMap().getAndPin(key); if (mappedValue != null && mappedValue.isExpired(timeSource.getTimeMillis(), TimeUnit.MILLISECONDS)) { if (backingMap().remove(key, mappedValue)) { onExpiration(key, mappedValue); } mappedValue = null; } } catch (CachePassThroughException cpte) { Throwable cause = cpte.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw wrapAsCacheAccessException(cause); } } catch (RuntimeException re) { throw wrapAsCacheAccessException(re); } finally { if (mappedValue == null) { getOperationObserver.end(StoreOperationOutcomes.GetOutcome.MISS); } else { getOperationObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } } return mappedValue; }
public ValueHolder<V> getAndFault(K key) throws CacheAccessException{ getOperationObserver.begin(); checkKey(key); ValueHolder<V> mappedValue = null; try { mappedValue = backingMap().getAndPin(key); if (mappedValue != null && mappedValue.isExpired(timeSource.getTimeMillis(), TimeUnit.MILLISECONDS)) { if (backingMap().remove(key, mappedValue)) { onExpiration(key, mappedValue); } mappedValue = null; } } catch (RuntimeException re) { handleRuntimeException(re); } finally { if (mappedValue == null) { getOperationObserver.end(StoreOperationOutcomes.GetOutcome.MISS); } else { getOperationObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } } return mappedValue; }
386
public Login readUniqueObject(String userName, String password){ Login login = null; System.out.println("in readuniqueobject method"); System.out.println("The username in DAO is: " + userName); System.out.println("The password in DAO is: " + password); try { System.out.println("in USERDAO"); transaction = session.beginTransaction(); Query query = session.createQuery("FROM Login as login where login.username= :loginName and login.password= :password"); query.setParameter("loginName", userName); query.setParameter("password", password); login = (Login) query.uniqueResult(); transaction.commit(); } catch (Exception hibernateException) { System.out.println("In userdao null pointer exception" + hibernateException); hibernateException.printStackTrace(); } finally { return login; } }
public Login readUniqueObject(String userName, String password){ Login login = null; try { System.out.println("in USERDAO"); transaction = session.beginTransaction(); Query query = session.createQuery("FROM Login as login where login.username= :loginName and login.password= :password"); query.setParameter("loginName", userName); query.setParameter("password", password); login = (Login) query.uniqueResult(); transaction.commit(); } catch (Exception hibernateException) { System.out.println("In userdao null pointer exception" + hibernateException); hibernateException.printStackTrace(); } finally { return login; } }
387
public void processAnnotation(final JNDIProperty jndiPropertyAnnotation, final Field field, final Object object) throws AnnotationProcessingException{ if (context == null) { try { context = new InitialContext(); } catch (NamingException e) { throw new AnnotationProcessingException("Unable to initialize JNDI context", e); } } String name = jndiPropertyAnnotation.value().trim(); if (name.isEmpty()) { throw new AnnotationProcessingException(missingAttributeValue("name", "@JNDIProperty", field, object)); } Object value; try { value = context.lookup(name); } catch (NamingException e) { throw new AnnotationProcessingException(String.format("Unable to lookup object %s from JNDI context", name), e); } if (value == null) { throw new AnnotationProcessingException("JNDI object " + name + " not found in JNDI context."); } processAnnotation(object, field, name, value); }
public void processAnnotation(final JNDIProperty jndiPropertyAnnotation, final Field field, final Object object) throws AnnotationProcessingException{ if (context == null) { try { context = new InitialContext(); } catch (NamingException e) { throw new AnnotationProcessingException("Unable to initialize JNDI context", e); } } String name = jndiPropertyAnnotation.value().trim(); checkIfEmpty(name, missingAttributeValue("name", "@JNDIProperty", field, object)); Object value; try { value = context.lookup(name); } catch (NamingException e) { throw new AnnotationProcessingException(format("Unable to lookup object %s from JNDI context", name), e); } if (value == null) { throw new AnnotationProcessingException(String.format("JNDI object %s not found in JNDI context.", name)); } processAnnotation(object, field, name, value); }
388
protected boolean serveStaticOrWebJarRequest(HttpServletRequest request, HttpServletResponse response) throws IOException{ if (staticFileHandler.isStaticResourceRequest(request)) { staticFileHandler.serveStaticResource(request, response); return true; } return false; }
protected boolean serveStaticOrWebJarRequest(HttpServletRequest request, HttpServletResponse response) throws IOException{ if (staticFileHandler.serveStaticResource(request, response)) { return true; } return false; }
389
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException{ String dotClassName = getDotClassName(className); if (isIgnoredClassName(dotClassName)) { return classfileBuffer; } else if (isInspectoredClassName(dotClassName)) { try { log("Transform class - " + dotClassName); ClassPool cp = ClassPool.getDefault(); CtClass cc = cp.get(dotClassName); for (CtMethod m : cc.getDeclaredMethods()) { if (isHackeableMethod(m)) { String beforeMethodCall = String.format(beforeMethodCallFormat, dotClassName + ".class", m.getLongName()); m.insertBefore(beforeMethodCall); String retClassName = getClassOrWrapperName(m.getReturnType()); String afterMethodCall = String.format(afterMethodCallFormat, dotClassName + ".class", m.getLongName(), retClassName + ".class"); m.insertAfter(afterMethodCall); CtClass exceptionClass = cp.get("java.lang.Exception"); String catchClause = String.format(catchClauseFormat, dotClassName + ".class", m.getLongName()); m.addCatch(catchClause, exceptionClass); } } for (CtConstructor ct : cc.getConstructors()) { String beforeMethodCall = String.format(beforeConstructorCallFormat, dotClassName + ".class", ct.getLongName()); ct.insertBefore(beforeMethodCall); String afterMethodCall = String.format(afterConstructorCallFormat, dotClassName + ".class", ct.getLongName()); ct.insertAfter(afterMethodCall); } classfileBuffer = cc.toBytecode(); cc.detach(); } catch (Exception ex) { ex.printStackTrace(); } } return classfileBuffer; }
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException{ String dotClassName = getDotClassName(className); if (isIgnoredClassName(dotClassName)) { return classfileBuffer; } else if (isInspectoredClassName(dotClassName)) { try { log("Transform class - " + dotClassName); ClassPool cp = ClassPool.getDefault(); CtClass cc = cp.get(dotClassName); for (CtMethod m : cc.getDeclaredMethods()) { if (isHackeableMethod(m)) { m.insertBefore(codeFormatter.formatBeforeMethod(dotClassName, m.getLongName())); m.insertAfter(codeFormatter.formatAfterMethod(dotClassName, m.getLongName(), getClassOrWrapperName(m.getReturnType()) + ".class")); m.addCatch(codeFormatter.formatCatchClause(dotClassName, m.getLongName()), cp.get("java.lang.Exception")); } } for (CtConstructor ct : cc.getConstructors()) { if (isHackeableMethod(ct)) { ct.insertBefore(codeFormatter.formatBeforeMethod(dotClassName, ct.getLongName())); ct.insertAfter(codeFormatter.formatAfterMethod(dotClassName, ct.getLongName(), "Void.TYPE")); ct.addCatch(codeFormatter.formatCatchClause(dotClassName, ct.getLongName()), cp.get("java.lang.Exception")); } } classfileBuffer = cc.toBytecode(); cc.detach(); } catch (Exception ex) { ex.printStackTrace(); } } return classfileBuffer; }
390
public Map<String, Object> querySubProcessInstanceByTaskId(User loginUser, String projectName, Integer taskId){ Map<String, Object> result = new HashMap<>(); Project project = projectMapper.queryByName(projectName); Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); Status resultEnum = (Status) checkResult.get(Constants.STATUS); if (resultEnum != Status.SUCCESS) { return checkResult; } TaskInstance taskInstance = processService.findTaskInstanceById(taskId); if (taskInstance == null) { putMsg(result, Status.TASK_INSTANCE_NOT_EXISTS, taskId); return result; } if (!taskInstance.isSubProcess()) { putMsg(result, Status.TASK_INSTANCE_NOT_SUB_WORKFLOW_INSTANCE, taskInstance.getName()); return result; } ProcessInstance subWorkflowInstance = processService.findSubProcessInstance(taskInstance.getProcessInstanceId(), taskInstance.getId()); if (subWorkflowInstance == null) { putMsg(result, Status.SUB_PROCESS_INSTANCE_NOT_EXIST, taskId); return result; } Map<String, Object> dataMap = new HashMap<>(); dataMap.put(Constants.SUBPROCESS_INSTANCE_ID, subWorkflowInstance.getId()); result.put(DATA_LIST, dataMap); putMsg(result, Status.SUCCESS); return result; }
public Result<Map<String, Object>> querySubProcessInstanceByTaskId(User loginUser, String projectName, Integer taskId){ Project project = projectMapper.queryByName(projectName); CheckParamResult checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName); if (!Status.SUCCESS.equals(checkResult.getStatus())) { return Result.error(checkResult); } TaskInstance taskInstance = processService.findTaskInstanceById(taskId); if (taskInstance == null) { putMsg(checkResult, Status.TASK_INSTANCE_NOT_EXISTS, taskId); return Result.error(checkResult); } if (!taskInstance.isSubProcess()) { putMsg(checkResult, Status.TASK_INSTANCE_NOT_SUB_WORKFLOW_INSTANCE, taskInstance.getName()); return Result.error(checkResult); } ProcessInstance subWorkflowInstance = processService.findSubProcessInstance(taskInstance.getProcessInstanceId(), taskInstance.getId()); if (subWorkflowInstance == null) { putMsg(checkResult, Status.SUB_PROCESS_INSTANCE_NOT_EXIST, taskId); return Result.error(checkResult); } Map<String, Object> dataMap = new HashMap<>(); dataMap.put(Constants.SUBPROCESS_INSTANCE_ID, subWorkflowInstance.getId()); return Result.success(dataMap); }
391
Argument getCommonSetting(ExecutableCode _conf, Argument _right){ PageEl ip_ = _conf.getOperationPageEl(); setRelativeOffsetPossibleLastPage(getIndexInEl() + off, _conf); LoopVariable locVar_ = ip_.getVars().getVal(variableName); Argument left_ = new Argument(); String formattedClassVar_ = locVar_.getClassName(); formattedClassVar_ = _conf.getOperationPageEl().formatVarType(formattedClassVar_, _conf); left_.setStruct(locVar_.getStruct()); if (!Templates.checkObject(formattedClassVar_, _right, _conf)) { return Argument.createVoid(); } locVar_.setStruct(_right.getStruct()); return _right; }
Argument getCommonSetting(ExecutableCode _conf, Argument _right){ PageEl ip_ = _conf.getOperationPageEl(); setRelativeOffsetPossibleLastPage(getIndexInEl() + off, _conf); LoopVariable locVar_ = ip_.getVars().getVal(variableName); return ExecMutableLoopVariableOperation.checkSet(_conf, locVar_, _right); }
392
protected void onMeasure(int widthSpec, int heightSpec){ int widthSize = MeasureSpec.getSize(widthSpec); int heightSize = MeasureSpec.getSize(heightSpec); int widthMode = MeasureSpec.getMode(widthSpec); int heightMode = MeasureSpec.getMode(heightSpec); if (widthMode != MeasureSpec.EXACTLY) { widthMode = MeasureSpec.EXACTLY; widthSize = heightSize / 9 * 16; } if (heightMode != MeasureSpec.EXACTLY) { heightMode = MeasureSpec.EXACTLY; heightSize = widthSize / 16 * 9; } int measuredWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); int measuredHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); setMeasuredDimension(measuredWidthSpec, measuredHeightSpec); super.onMeasure(measuredWidthSpec, measuredHeightSpec); }
protected void onMeasure(int widthSpec, int heightSpec){ int widthSize = MeasureSpec.getSize(widthSpec); int heightSize = MeasureSpec.getSize(heightSpec); int widthMode = MeasureSpec.getMode(widthSpec); int heightMode = MeasureSpec.getMode(heightSpec); if (widthMode != MeasureSpec.EXACTLY) { widthMode = MeasureSpec.EXACTLY; widthSize = heightSize / 9 * 16; } else if (heightMode != MeasureSpec.EXACTLY) { heightMode = MeasureSpec.EXACTLY; heightSize = widthSize / 16 * 9; } int measuredWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); int measuredHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); setMeasuredDimension(measuredWidthSpec, measuredHeightSpec); super.onMeasure(measuredWidthSpec, measuredHeightSpec); }
393
public void showLogoInToolbar(){ getSupportActionBar().setTitle(""); if (session == null || session.getInstituteSettings() == null) { return; } String url = session.getInstituteSettings().getAppToolbarLogo(); ImageLoader imageLoader = ImageUtils.initImageLoader(this); DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build(); imageLoader.displayImage(url, logo, options); }
public void showLogoInToolbar(){ getSupportActionBar().setTitle(""); if (session == null || session.getInstituteSettings() == null) { return; } UIUtils.loadLogoInView(logo, this); }
394
private void updateHashrate(float fSpeed, float fMax){ if (!isDeviceMining() || fSpeed < 0.0f) return; SpeedView meterTicks = findViewById(R.id.meter_hashrate_ticks); if (meterTicks.getTickNumber() == 0) { updateHashrateTicks(fMax); new Handler().postDelayed(new Runnable() { @Override public void run() { updateHashrateMeter(fSpeed, fMax); } }, 2000); } else { updateHashrateTicks(fMax); updateHashrateMeter(fSpeed, fMax); } }
private void updateHashrate(float fSpeed, float fMax){ if (!isDeviceMining() || fSpeed < 0.0f) return; SpeedView meterTicks = findViewById(R.id.meter_hashrate_ticks); if (meterTicks.getTickNumber() == 0) { updateHashrateTicks(fMax); new Handler().postDelayed(() -> updateHashrateMeter(fSpeed, fMax), 2000); } else { updateHashrateTicks(fMax); updateHashrateMeter(fSpeed, fMax); } }
395
private Query buildQueryForEntity(final Class<? extends BaseDimensionalItemObject> entity, final OrderParams orderParams, final List<String> filters, final WebOptions options){ final Schema schema = schemaService.getDynamicSchema(entity); final List<Order> orders = orderParams.getOrders(schema); final Query query = queryService.getQueryFromUrl(entity, filters, orders, getPaginationData(options), options.getRootJunction()); query.setDefaultOrder(); if (options.contains("program.id")) { final String programUid = options.get("program.id"); final List<ProgramDataElementDimensionItem> programDataElements = programService.getGeneratedProgramDataElements(programUid); query.setObjects(programDataElements); } return query; }
private Query buildQueryForEntity(final Class<? extends BaseDimensionalItemObject> entity, final OrderParams orderParams, final List<String> filters, final WebOptions options){ final Schema schema = schemaService.getDynamicSchema(entity); final List<Order> orders = orderParams.getOrders(schema); final Query query = queryService.getQueryFromUrl(entity, filters, orders, getPaginationData(options), options.getRootJunction()); query.setDefaultOrder(); addQueryFilters(options, query); return query; }
396
public void add(T value, int index){ if (index < 0 || index > size) { throw new ArrayListIndexOutOfBoundsException("Index are not exist, your index is " + index + " last index is " + size); } else if (index == size && ensureCapacity()) { arrayData[index] = value; size++; } else if (indexCapacity(index) && ensureCapacity()) { arrayCopyAdd(index); arrayData[index] = value; size++; } else { grow(); arrayCopyAdd(index); arrayData[index] = value; size++; } }
public void add(T value, int index){ if (index < 0 || index > size) { throw new ArrayListIndexOutOfBoundsException("Index are not exist, your index is " + index + " last index is " + size); } else if (index == size && ensureCapacity()) { arrayData[index] = value; size++; } else if (indexCapacity(index) && ensureCapacity()) { arrayCopyAdd(index); arrayData[index] = value; } else { grow(); arrayCopyAdd(index); arrayData[index] = value; } }
397
public List<GenomeMap> getMaps() throws Exception{ List<GenomeMap> mapList = new ArrayList<>(); Pager pager = new Pager(); while (pager.isPaging()) { Response<BrapiListResource<GenomeMap>> response = service.getMaps(null, null, null, null, null, null, null, pager.getPageSize(), pager.getPage()).execute(); if (response.isSuccessful()) { BrapiListResource<GenomeMap> maps = response.body(); mapList.addAll(maps.data()); pager.paginate(maps.getMetadata()); } else { String errorMessage = ErrorHandler.getMessage(generator, response); throw new Exception(errorMessage); } } return mapList; }
public List<Map> getMaps() throws Exception{ List<Map> mapList = new ArrayList<>(); Pager pager = new Pager(); while (pager.isPaging()) { Response<BaseResult<ArrayResult<Map>>> response = genotypeService.getMaps(null, null, null, null, null, null, null, null, pager.getPage(), pager.getPageSize()).execute(); if (response.isSuccessful()) { BaseResult<ArrayResult<Map>> maps = response.body(); mapList.addAll(maps.getResult().getData()); pager.paginate(maps.getMetadata()); } else { throw new Exception("Generic BrAPI error"); } } return mapList; }
398
public void calculateArgument44FailTest(){ StringBuilder xml_ = new StringBuilder(); xml_.append("$public $class pkg.Ex {\n"); xml_.append(" $public $static $int catching(){\n"); xml_.append(" $switch($true)label{\n"); xml_.append(" $break label;\n"); xml_.append(" }\n"); xml_.append(" $return 0i;\n"); xml_.append(" }\n"); xml_.append("}\n"); StringMap<String> files_ = new StringMap<String>(); ContextEl cont_ = ctx(); files_.put("pkg/Ex", xml_.toString()); Classes.validateAll(files_, cont_); assertTrue(!isEmptyErrors(cont_)); }
public void calculateArgument44FailTest(){ StringBuilder xml_ = new StringBuilder(); xml_.append("$public $class pkg.Ex {\n"); xml_.append(" $public $static $int catching(){\n"); xml_.append(" $switch($true)label{\n"); xml_.append(" $break label;\n"); xml_.append(" }\n"); xml_.append(" $return 0i;\n"); xml_.append(" }\n"); xml_.append("}\n"); StringMap<String> files_ = new StringMap<String>(); files_.put("pkg/Ex", xml_.toString()); assertTrue(hasErr(files_)); }
399
public List<String> getGenresOfSongBySongID(int songID, Connection connection) throws DataAccessException{ List<String> genres = new ArrayList<>(); String getGenresOfSongQuery = "SELECT genre_name FROM\n" + "(SELECT genre_name, song_id FROM genres_of_songs INNER JOIN genres\n" + "ON genres_of_songs.genre_id = genres.genre_id)\n" + "AS intermediate_table\n" + "INNER JOIN songs\n" + "ON intermediate_table.song_id = songs.song_id\n" + "WHERE songs.song_id = ?"; int songIDParameter = 1; try { PreparedStatement preparedStatement = connection.prepareStatement(getGenresOfSongQuery); preparedStatement.setInt(songIDParameter, songID); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String genre = resultSet.getString(DatabaseConstants.ColumnLabels.GenresTable.GENRE_NAME); genres.add(genre); } resultSet.close(); preparedStatement.close(); } catch (SQLException e) { logger.error(LoggingConstants.EXCEPTION_WHILE_GETTING_GENRES_OF_SONGS, e); throw new DataAccessException(); } return genres; }
public List<String> getGenresOfSongBySongID(int songID, Connection connection) throws DataAccessException{ List<String> genres = new ArrayList<>(); String getGenresOfSongQuery = "SELECT genre_name FROM\n" + "(SELECT genre_name, song_id FROM genres_of_songs INNER JOIN genres\n" + "ON genres_of_songs.genre_id = genres.genre_id)\n" + "AS intermediate_table\n" + "INNER JOIN songs\n" + "ON intermediate_table.song_id = songs.song_id\n" + "WHERE songs.song_id = ?"; int songIDParameter = 1; try (PreparedStatement preparedStatement = connection.prepareStatement(getGenresOfSongQuery)) { preparedStatement.setInt(songIDParameter, songID); try (ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { String genre = resultSet.getString(DatabaseConstants.ColumnLabels.GenresTable.GENRE_NAME); genres.add(genre); } } } catch (SQLException e) { logger.error(LoggingConstants.EXCEPTION_WHILE_GETTING_GENRES_OF_SONGS, e); throw new DataAccessException(); } return genres; }