auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void whenUpdateExistingEventTypeItUpdates() throws NakadiException, DuplicatedEventTypeNameException, IOException, NoSuchEventTypeException { EventType eventType = buildEventType(); repository.saveEventType(eventType); eventType.setCategory(EventCategory.UNDEFINED); repository.update(eventType); SqlRowSet rs = template.queryForRowSet("SELECT et_name, et_event_type_object FROM zn_data.event_type"); rs.next(); assertThat("Name is persisted", rs.getString(1), equalTo("event-name")); ObjectMapper mapper = (new JsonConfig()).jacksonObjectMapper(); EventType persisted = mapper.readValue(rs.getString(2), EventType.class); assertThat(persisted.getCategory(), equalTo(eventType.getCategory())); assertThat(persisted.getName(), equalTo(eventType.getName())); assertThat(persisted.getSchema().getType(), equalTo(eventType.getSchema().getType())); assertThat(persisted.getSchema().getSchema(), equalTo(eventType.getSchema().getSchema())); }

Target:
public void whenUpdateExistingEventTypeItUpdates() throws NakadiException, DuplicatedEventTypeNameException, IOException, NoSuchEventTypeException { EventType eventType = buildEventType(); repository.saveEventType(eventType); eventType.setCategory(EventCategory.BUSINESS); eventType.setOwningApplication("new-application"); repository.update(eventType); SqlRowSet rs = template.queryForRowSet("SELECT et_name, et_event_type_object FROM zn_data.event_type"); rs.next(); assertThat("Name is persisted", rs.getString(1), equalTo("event-name")); ObjectMapper mapper = (new JsonConfig()).jacksonObjectMapper(); EventType persisted = mapper.readValue(rs.getString(2), EventType.class); assertThat(persisted.getCategory(), equalTo(eventType.getCategory())); assertThat(persisted.getOwningApplication(), equalTo(eventType.getOwningApplication())); assertThat(persisted.getOrderingKeyFields(), equalTo(eventType.getOrderingKeyFields())); assertThat(persisted.getName(), equalTo(eventType.getName())); assertThat(persisted.getSchema().getType(), equalTo(eventType.getSchema().getType())); assertThat(persisted.getSchema().getSchema(), equalTo(eventType.getSchema().getSchema())); }
Source:
public Map<TaskId, Integer> getTaskOffsetSums() { final Map<TaskId, Integer> taskOffsetSums = new HashMap<>(); for (final TaskId id : tasksOnLocalStorage()) { if (isActive(id)) { taskOffsetSums.put(id, ACTIVE_TASK_SENTINEL_OFFSET); } else { taskOffsetSums.put(id, 0); } } return taskOffsetSums; }

Target:
public Map<TaskId, Long> getTaskOffsetSums() { final Map<TaskId, Long> taskOffsetSums = new HashMap<>(); for (final TaskId id : tasksOnLocalStorage()) { if (isRunning(id)) { taskOffsetSums.put(id, Task.LATEST_OFFSET); } else { taskOffsetSums.put(id, 0L); } } return taskOffsetSums; }
Source:
public void performSimpleOperationsDropSNIProxy() throws IOException, InterruptedException { final Region<String, Integer> region = getRegion(); region.put("Roy Hobbs", 9); assertThat(region.get("Roy Hobbs")).isEqualTo(9); docker.containers() .container("haproxy") .stop(); assertThatThrownBy(() -> region.get("Roy Hobbs")) .isInstanceOf(NoAvailableLocatorsException.class) .hasMessageContaining("Unable to connect to any locators in the list"); docker.containers() .container("haproxy") .start(); assertThat(region.get("Roy Hobbs")).isEqualTo(9); region.put("Bennie Rodriquez", 30); assertThat(region.get("Bennie Rodriquez")).isEqualTo(30); region.put("Jake Taylor", 7); region.put("Crash Davis", 8); region.put("Ricky Vaughn", 99); region.put("Ebbie Calvin LaLoosh", 37); }

Target:
public void performSimpleOperationsDropSNIProxy() throws IOException, InterruptedException { final Region<String, Integer> region = getRegion(); region.put("Roy Hobbs", 9); assertThat(region.get("Roy Hobbs")).isEqualTo(9); stopProxy(); assertThatThrownBy(() -> region.get("Roy Hobbs")) .isInstanceOf(NoAvailableLocatorsException.class) .hasMessageContaining("Unable to connect to any locators in the list"); restartProxy(); await().untilAsserted(() -> assertThat(region.get("Roy Hobbs")).isEqualTo(9)); region.put("Bennie Rodriquez", 30); assertThat(region.get("Bennie Rodriquez")).isEqualTo(30); region.put("Jake Taylor", 7); region.put("Crash Davis", 8); region.put("Ricky Vaughn", 99); region.put("Ebbie Calvin LaLoosh", 37); }
Source:
public String addIdentifiersFromFile(ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required=true, value="source") IdentifierSource source, @RequestParam(required=true, value="inputFile") MultipartFile inputFile) throws Exception { IdentifierPool pool = (IdentifierPool)source; List<String> ids = new ArrayList<String>(); if(inputFile!=null){ try { String jsonIdentifiers = IOUtils.toString(inputFile.getInputStream()); if(StringUtils.isNotBlank(jsonIdentifiers)){ try{ ObjectMapper mapper = new ObjectMapper(); RemoteIdentifiersMessage remoteIdentifiersMessage = mapper.readValue(jsonIdentifiers, RemoteIdentifiersMessage.class); if(remoteIdentifiersMessage!=null){ ids= remoteIdentifiersMessage.getIdentifiers(); } }catch (IOException ex){ log.error("Unexpected response: " + jsonIdentifiers, ex); throw new Exception(ex); } } }catch (Exception e){ log.error("failed to read uploaded file", e); throw new Exception(e); } } iss.addIdentifiersToPool(pool, ids); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Success: Identifiers successfully uploaded."); return "redirect:/module/idgen/viewIdentifierSource.form?source="+source.getId(); }

Target:
public String addIdentifiersFromFile(ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required=true, value="source") IdentifierSource source, @RequestParam(required=true, value="inputFile") MultipartFile inputFile) throws Exception { IdentifierPool pool = (IdentifierPool)source; List<String> ids = new ArrayList<String>(); InputStream streamReader = null; if(inputFile != null){ try { streamReader = inputFile.getInputStream(); if(streamReader != null){ try{ ObjectMapper mapper = new ObjectMapper(); RemoteIdentifiersMessage remoteIdentifiersMessage = mapper.readValue(streamReader, RemoteIdentifiersMessage.class); if(remoteIdentifiersMessage != null){ ids = remoteIdentifiersMessage.getIdentifiers(); iss.addIdentifiersToPool(pool, ids); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Success: Identifiers successfully uploaded."); } }catch (IOException ex){ log.error("Unexpected response: " , ex); throw new Exception(ex); } } }catch (Exception e){ log.error("failed to read uploaded file", e); throw new Exception(e); }finally { if(streamReader != null){ streamReader.close(); } } } return "redirect:/module/idgen/viewIdentifierSource.form?source=" + source.getId(); }
Source:
public void setStatus(VDSStatus status, VDS vds) { synchronized (this) { if (isNetworkExceptionDuringMaintenance(status)) { return; } if (vds == null) { vds = vdsDao.get(getVdsId()); } if (vds.getStatus() != status) { if (status == VDSStatus.PreparingForMaintenance) { calculateNextMaintenanceAttemptTime(); } vds.setPreviousStatus(vds.getStatus()); if (this.cachedVds != null) { this.cachedVds.setPreviousStatus(vds.getStatus()); } } vds.setStatus(status); if (this.cachedVds != null) { this.cachedVds.setStatus(status); } if (status != VDSStatus.Up) { invalidateVdsCacheData(); } switch (status) { case NonOperational: if (this.cachedVds != null) { this.cachedVds.setNonOperationalReason(vds.getNonOperationalReason()); } if (vds.getVmCount() > 0) { break; } case NonResponsive: case Down: case Maintenance: vds.setCpuSys(Double.valueOf(0)); vds.setCpuUser(Double.valueOf(0)); vds.setCpuIdle(Double.valueOf(0)); vds.setCpuLoad(Double.valueOf(0)); vds.setUsageCpuPercent(0); vds.setUsageMemPercent(0); vds.setUsageNetworkPercent(0); if (this.cachedVds != null) { this.cachedVds.setCpuSys(Double.valueOf(0)); this.cachedVds.setCpuUser(Double.valueOf(0)); this.cachedVds.setCpuIdle(Double.valueOf(0)); this.cachedVds.setCpuLoad(Double.valueOf(0)); this.cachedVds.setUsageCpuPercent(0); this.cachedVds.setUsageMemPercent(0); this.cachedVds.setUsageNetworkPercent(0); } break; case Up: vds.setInFenceFlow(false); break; default: break; } } }

Target:
public void setStatus(VDSStatus status, VDS vds) { synchronized (this) { if (isNetworkExceptionDuringMaintenance(status)) { return; } if (vds == null) { vds = vdsDao.get(getVdsId()); } if (vds.getStatus() != status) { if (status == VDSStatus.PreparingForMaintenance) { calculateNextMaintenanceAttemptTime(); } vds.setPreviousStatus(vds.getStatus()); if (this.cachedVds != null) { this.cachedVds.setPreviousStatus(vds.getStatus()); } } vds.setStatus(status); if (this.cachedVds != null) { this.cachedVds.setStatus(status); } if (status != VDSStatus.Up) { invalidateVdsCachedData(); } switch (status) { case NonOperational: if (this.cachedVds != null) { this.cachedVds.setNonOperationalReason(vds.getNonOperationalReason()); } if (vds.getVmCount() > 0) { break; } case NonResponsive: case Down: case Maintenance: vds.setCpuSys(Double.valueOf(0)); vds.setCpuUser(Double.valueOf(0)); vds.setCpuIdle(Double.valueOf(0)); vds.setCpuLoad(Double.valueOf(0)); vds.setUsageCpuPercent(0); vds.setUsageMemPercent(0); vds.setUsageNetworkPercent(0); if (this.cachedVds != null) { this.cachedVds.setCpuSys(Double.valueOf(0)); this.cachedVds.setCpuUser(Double.valueOf(0)); this.cachedVds.setCpuIdle(Double.valueOf(0)); this.cachedVds.setCpuLoad(Double.valueOf(0)); this.cachedVds.setUsageCpuPercent(0); this.cachedVds.setUsageMemPercent(0); this.cachedVds.setUsageNetworkPercent(0); } break; case Up: vds.setInFenceFlow(false); break; default: break; } } }
Source:
private void prepareResponse(final KuraResponsePayload respPayload, final List<? extends ChannelRecord> channelRecords) { requireNonNull(respPayload, message.respPayloadNonNull()); requireNonNull(channelRecords, message.assetRecordsNonNull()); for (final ChannelRecord channelRecord : channelRecords) { final TypedValue<?> assetValue = channelRecord.getValue(); final String value = (assetValue != null) ? String.valueOf(assetValue.getValue()) : "ERROR"; String errorText; final ChannelStatus channelStatus = channelRecord.getChannelStatus(); final ChannelFlag channelFlag = channelStatus.getChannelFlag(); final String prefix = channelRecord.getChannelName() + "#"; respPayload.addMetric(prefix + message.flag(), channelFlag.toString()); respPayload.addMetric(prefix + message.timestamp(), channelRecord.getTimestamp()); respPayload.addMetric(prefix + message.value(), value); if (channelFlag == ChannelFlag.FAILURE) { final String exceptionMessage = channelStatus.getExceptionMessage(); errorText = (exceptionMessage != null) ? exceptionMessage : ""; respPayload.addMetric(prefix + message.errorMessage(), errorText); } } }

Target:
private void prepareResponse(final KuraResponsePayload respPayload, final List<? extends ChannelRecord> channelRecords) { requireNonNull(respPayload, message.respPayloadNonNull()); requireNonNull(channelRecords, message.channelRecordsNonNull()); for (final ChannelRecord channelRecord : channelRecords) { final TypedValue<?> assetValue = channelRecord.getValue(); final String value = (assetValue != null) ? String.valueOf(assetValue.getValue()) : "ERROR"; String errorText; final ChannelStatus channelStatus = channelRecord.getChannelStatus(); final ChannelFlag channelFlag = channelStatus.getChannelFlag(); final String prefix = channelRecord.getChannelName() + "#"; respPayload.addMetric(prefix + message.flag(), channelFlag.toString()); respPayload.addMetric(prefix + message.timestamp(), channelRecord.getTimestamp()); respPayload.addMetric(prefix + message.value(), value); if (channelFlag == ChannelFlag.FAILURE) { final String exceptionMessage = channelStatus.getExceptionMessage(); errorText = (exceptionMessage != null) ? exceptionMessage : ""; respPayload.addMetric(prefix + message.errorMessage(), errorText); } } }
Source:
private void updateCommand(@NotNull final String wsId, @NotNull final CommandDto commandUpdate, final String commandName, @NotNull AsyncCallback<WorkspaceDto> callback) { String url = null; try { url = baseHttpUrl + '/' + wsId + "/command/" + URLEncoder.encode(commandName, "UTF-8"); } catch (UnsupportedEncodingException ignored) { } asyncRequestFactory.createRequest(PUT, url, commandUpdate, false) .header(ACCEPT, APPLICATION_JSON) .header(CONTENT_TYPE, APPLICATION_JSON) .loader(loaderFactory.newLoader("Updating command...")) .send(newCallback(callback, dtoUnmarshallerFactory.newUnmarshaller(WorkspaceDto.class))); }

Target:
private void updateCommand(@NotNull final String wsId, @NotNull final CommandDto commandUpdate, final String commandName, @NotNull AsyncCallback<WorkspaceDto> callback) { final String url = baseHttpUrl + '/' + wsId + "/command/" + URL.encodePathSegment(commandName); asyncRequestFactory.createRequest(PUT, url, commandUpdate, false) .header(ACCEPT, APPLICATION_JSON) .header(CONTENT_TYPE, APPLICATION_JSON) .loader(loaderFactory.newLoader("Updating command...")) .send(newCallback(callback, dtoUnmarshallerFactory.newUnmarshaller(WorkspaceDto.class))); }
Source:
public void setCurrentLogForLedgerAndAddToRotate(long ledgerId, BufferedLogChannel logChannel) throws IOException { acquireLock(ledgerId); try { BufferedLogChannel hasToRotateLogChannel = getCurrentLogForLedger(ledgerId); logChannel.setLedgerIdAssigned(ledgerId); ledgerIdEntryLogMap.get(ledgerId).setEntryLog(logChannel); replicaOfCurrentLogChannels.put(logChannel.getLogId(), logChannel); if (hasToRotateLogChannel != null) { replicaOfCurrentLogChannels.remove(hasToRotateLogChannel.getLogId()); rotatedLogChannels.add(hasToRotateLogChannel); } } catch (Exception e) { log.error("Received unexpected exception while fetching entry from map", e); throw new IOException("Received unexpected exception while fetching entry from map", e); } finally { releaseLock(ledgerId); } }

Target:
public void setCurrentLogForLedgerAndAddToRotate(long ledgerId, BufferedLogChannel logChannel) throws IOException { Lock lock = getLock(ledgerId); lock.lock(); try { BufferedLogChannel hasToRotateLogChannel = getCurrentLogForLedger(ledgerId); logChannel.setLedgerIdAssigned(ledgerId); BufferedLogChannelWithDirInfo logChannelWithDirInfo = new BufferedLogChannelWithDirInfo(logChannel); ledgerIdEntryLogMap.get(ledgerId).setEntryLogWithDirInfo(logChannelWithDirInfo); replicaOfCurrentLogChannels.put(logChannel.getLogId(), logChannelWithDirInfo); if (hasToRotateLogChannel != null) { replicaOfCurrentLogChannels.remove(hasToRotateLogChannel.getLogId()); rotatedLogChannels.add(hasToRotateLogChannel); } } catch (Exception e) { log.error("Received unexpected exception while fetching entry from map for ledger: " + ledgerId, e); throw new IOException("Received unexpected exception while fetching entry from map", e); } finally { lock.unlock(); } }
Source:
protected Class findClass(String name) throws ClassNotFoundException { byte[] classfile; try { if (source != null) { if (translator != null) translator.onLoad(source, name); try { classfile = source.get(name).toBytecode(); } catch (NotFoundException e) { return null; } } else { String jarname = "/" + name.replace('.', '/') + ".class"; InputStream in = this.getClass().getResourceAsStream(jarname); if (in == null) return null; classfile = ClassPoolTail.readStream(in); } } catch (Exception e) { throw new ClassNotFoundException( "caught an exception while obtaining a class file for " + name, e); } int i = name.lastIndexOf('.'); if (i != -1) { String pname = name.substring(0, i); if (getDefinedPackage(pname) == null) try { definePackage( pname, null, null, null, null, null, null, null); } catch (IllegalArgumentException e) { } } if (domain == null) return defineClass(name, classfile, 0, classfile.length); else return defineClass(name, classfile, 0, classfile.length, domain); }

Target:
protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] classfile; try { if (source != null) { if (translator != null) translator.onLoad(source, name); try { classfile = source.get(name).toBytecode(); } catch (NotFoundException e) { return null; } } else { String jarname = "/" + name.replace('.', '/') + ".class"; InputStream in = this.getClass().getResourceAsStream(jarname); if (in == null) return null; classfile = ClassPoolTail.readStream(in); } } catch (Exception e) { throw new ClassNotFoundException( "caught an exception while obtaining a class file for " + name, e); } int i = name.lastIndexOf('.'); if (i != -1) { String pname = name.substring(0, i); if (getDefinedPackage(pname) == null) try { definePackage( pname, null, null, null, null, null, null, null); } catch (IllegalArgumentException e) { } } if (domain == null) return defineClass(name, classfile, 0, classfile.length); return defineClass(name, classfile, 0, classfile.length, domain); }
Source:
protected void packColumns() { if (fPackDone) { return; } fTable.setRedraw(false); try { TableColumn tableColumns[] = fTable.getColumns(); for (int i = 1; i < tableColumns.length; i++) { final TableColumn column = tableColumns[i]; packSingleColumn(i, column); column.setData(Key.WIDTH, column.getWidth()); } } finally { fTable.setRedraw(true); } fPackDone = true; }

Target:
protected void packColumns() { if (fPackDone) { return; } fTable.setRedraw(false); try { TableColumn tableColumns[] = fTable.getColumns(); for (int i = 0; i < tableColumns.length; i++) { final TableColumn column = tableColumns[i]; packSingleColumn(i, column); } } finally { fTable.setRedraw(true); } fPackDone = true; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (activeWorkbenchWindow != null) { IWorkbenchPart activePart = activeWorkbenchWindow.getActivePage().getActivePart(); if (activePart instanceof PapyrusMultiDiagramEditor) { PapyrusMultiDiagramEditor papyrusEditor = (PapyrusMultiDiagramEditor) activePart; try { IPage nextPage = null; if (isPrevious) { nextPage = papyrusEditor.getISashWindowsContainer().getPreviousPage(); } else { nextPage = papyrusEditor.getISashWindowsContainer().getNextPage(); } papyrusEditor.getISashWindowsContainer().selectPage(nextPage); } catch (Exception e) { e.printStackTrace(); } } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (activeWorkbenchWindow != null) { IWorkbenchPart activePart = activeWorkbenchWindow.getActivePage().getActivePart(); if (activePart instanceof PapyrusMultiDiagramEditor) { PapyrusMultiDiagramEditor papyrusEditor = (PapyrusMultiDiagramEditor) activePart; try { IPage nextPage = null; if (isPrevious) { nextPage = papyrusEditor.getISashWindowsContainer().getPreviousPage(); } else { nextPage = papyrusEditor.getISashWindowsContainer().getNextPage(); } papyrusEditor.getISashWindowsContainer().selectPage(nextPage); } catch (Exception e) { Activator.log.error(e); } } } return null; }
Source:
public static boolean checkAppSuccessFromYarnRM(Job job) throws Exception { log.info("Could not retrieve job status from JobHistory server, trying YARN ResourceManager instead."); final HttpClient httpClient = new HttpClient(); final AtomicBoolean succeeded = new AtomicBoolean(false); try { httpClient.start(); RetryUtils.retry( () -> { checkAppSuccessFromYarnRMOnce(httpClient, job, succeeded); return null; }, ex -> { return !succeeded.get(); }, 5 ); return succeeded.get(); } catch (Exception e) { log.error(e, "Got exception while trying to contact YARN RM."); return false; } finally { httpClient.stop(); } }

Target:
public static boolean checkAppSuccessFromYarnRM(Job job) { final HttpClient httpClient = new HttpClient(); final AtomicBoolean succeeded = new AtomicBoolean(false); try { httpClient.start(); RetryUtils.retry( () -> { checkAppSuccessFromYarnRMOnce(httpClient, job, succeeded); return null; }, ex -> { return !succeeded.get(); }, 5 ); return succeeded.get(); } catch (Exception e) { log.error(e, "Got exception while trying to contact YARN RM."); return false; } finally { try { httpClient.stop(); } catch (Exception e) { log.error(e, "Got exception with httpClient.stop() while trying to contact YARN RM."); } } }
Source:
@Test public void requestThrowingBeforeExecuteFailsExecute() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new RuntimeException("Broken!"); } }; Call<String> call = service.postRequestBody(a); try { call.request(); } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); try { call.execute(); } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); }

Target:
@Test public void requestThrowingBeforeExecuteFailsExecute() throws IOException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new RuntimeException("Broken!"); } }; Call<String> call = service.postRequestBody(a); try { call.request(); fail(); } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); try { call.execute(); fail(); } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); }
Source:
private void initBoolean(boolean booleanValue) { typeBitfield |= 0x00000010; this.booleanValue = booleanValue; }

Target:
private void initBoolean(boolean booleanValue) { setBitfieldType(BOOLEAN_MASK); this.booleanValue = booleanValue; }
Source:
private void restoreCollectionPreferences() { try { mShowNextReviewTime = getCol().getConf().getBoolean("estTimes"); mShowRemainingCardCount = getCol().getConf().getBoolean("dueCounts"); JSONObject revOptions = new JSONObject(); if (!getCol().getDecks().isDyn(getCol().getDecks().selected())) { grevOptions = getCol().getDecks().confForDid(getCol().getDecks().selected()).getJSONObject("rev"); } mOptUseGeneralTimerSettings = revOptions.optBoolean("useGeneralTimeoutSettings", true); mOptUseTimer = revOptions.optBoolean("timeoutAnswer", false); mOptWaitAnswerSecond = revOptions.optInt("timeoutAnswerSeconds", 20); mOptWaitQuestionSecond = revOptions.optInt("timeoutQuestionSeconds", 60); } catch (JSONException e) { Timber.e(e, "Unable to restoreCollectionPreferences"); throw new RuntimeException(e); } catch (NullPointerException npe) { Intent deckPicker = new Intent(this, DeckPicker.class); deckPicker.putExtra("collectionLoadError", true); deckPicker.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivityWithAnimation(deckPicker, ActivityTransitionAnimation.LEFT); } }

Target:
private void restoreCollectionPreferences() { try { mShowNextReviewTime = getCol().getConf().getBoolean("estTimes"); mShowRemainingCardCount = getCol().getConf().getBoolean("dueCounts"); JSONObject revOptions = new JSONObject(); long selectedDid = getCol().getDecks().selected(); if (!getCol().getDecks().isDyn(selectedDid)) { revOptions = getCol().getDecks().confForDid(selectedDid).getJSONObject("rev"); } mOptUseGeneralTimerSettings = revOptions.optBoolean("useGeneralTimeoutSettings", true); mOptUseTimer = revOptions.optBoolean("timeoutAnswer", false); mOptWaitAnswerSecond = revOptions.optInt("timeoutAnswerSeconds", 20); mOptWaitQuestionSecond = revOptions.optInt("timeoutQuestionSeconds", 60); } catch (JSONException e) { Timber.e(e, "Unable to restoreCollectionPreferences"); throw new RuntimeException(e); } catch (NullPointerException npe) { Intent deckPicker = new Intent(this, DeckPicker.class); deckPicker.putExtra("collectionLoadError", true); deckPicker.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivityWithAnimation(deckPicker, ActivityTransitionAnimation.LEFT); } }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { if (disk != null) { if (disk.getVmEntityType() == VmEntityType.VM) { return Collections.singletonList(new PermissionSubject(getParameters().getStorageDomainId(), VdcObjectType.Storage, ActionGroup.CONFIGURE_VM_STORAGE)); } if (disk.getVmEntityType() == VmEntityType.TEMPLATE) { return Collections.singletonList(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VmTemplate, ActionGroup.DELETE_TEMPLATE)); } } return null; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { if (disk != null) { if (disk.getVmEntityType() == VmEntityType.VM) { return Collections.singletonList(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VM, ActionGroup.CONFIGURE_VM_STORAGE)); } if (disk.getVmEntityType() == VmEntityType.TEMPLATE) { return Collections.singletonList(new PermissionSubject(disk.getvm_guid(), VdcObjectType.VmTemplate, ActionGroup.DELETE_TEMPLATE)); } } return null; }
Source:
public void map(Double minX, Double maxX, Double minY, Double maxY) { if (mapper == null) { mapper = new Mapper(0, 180, 0, 180); } if (minX != mapper.getMinX() || maxX != mapper.getMaxX() || minY != mapper.getMinY() || maxY != mapper.getMaxY()) { mapper = new Mapper(minX, maxX, minY, maxY); broadcastState(); } }

Target:
public void map(Double minX, Double maxX, Double minY, Double maxY) { Mapper m = new Mapper(minX, maxX, minY, maxY); this.mapper = m; }
Source:
private Set<String> getCurrentFileList() throws NoSuchChangeException, OrmException, NoSuchEntityException { Set<String> result = new HashSet<String>(); getFileListBy(psIdNew, result); getFileListBy(psIdBase, result); return result; }

Target:
private Set<String> getCurrentFileList() throws NoSuchChangeException, OrmException, NoSuchEntityException { Set<String> fileList = getFileListBy(psIdNew); fileList.addAll(getFileListBy(psIdBase)); return fileList; }
Source:
protected java.util.ArrayList<StorageDomain> parseVGList(Map<String, Object>[] vgList) { java.util.ArrayList<StorageDomain> result = new java.util.ArrayList<StorageDomain>(vgList.length); for (Map<String, Object> vg : vgList) { StorageDomain sDomain = new StorageDomain(); if (vg.containsKey("name")) { try { sDomain.setId(new Guid(vg.get("name").toString())); } catch (java.lang.Exception e) { sDomain.setStorageName(vg.get("name").toString()); } } sDomain.setStorage(vg.get("vgUUID").toString()); Long size = IrsBrokerCommand.AssignLongValue(vg, "vgfree"); if (size != null) { sDomain.setAvailableDiskSize((int) (size / SizeConverter.BYTES_IN_GB)); } size = IrsBrokerCommand.AssignLongValue(vg, "vgsize"); if (size != null && sDomain.getAvailableDiskSize() != null) { sDomain.setUsedDiskSize((int) (size / SizeConverter.BYTES_IN_GB) - sDomain.getAvailableDiskSize()); } if (vg.containsKey("vgtype")) { sDomain.setStorageType(EnumUtils.valueOf(StorageType.class, vg.get("vgtype").toString(), true)); } else { sDomain.setStorageType(StorageType.UNKNOWN); } result.add(sDomain); } return result; }

Target:
protected java.util.ArrayList<StorageDomain> parseVGList(Map<String, Object>[] vgList) { java.util.ArrayList<StorageDomain> result = new java.util.ArrayList<StorageDomain>(vgList.length); for (Map<String, Object> vg : vgList) { StorageDomain sDomain = new StorageDomain(); if (vg.containsKey("name")) { try { sDomain.setId(new Guid(vg.get("name").toString())); } catch (java.lang.Exception e) { sDomain.setStorageName(vg.get("name").toString()); } } sDomain.setStorage(vg.get("vgUUID").toString()); Long size = IrsBrokerCommand.AssignLongValue(vg, "vgfree"); if (size != null) { sDomain.setAvailableDiskSize((int) (size / IrsBrokerCommand.BYTES_TO_GB)); } size = IrsBrokerCommand.AssignLongValue(vg, "vgsize"); if (size != null && sDomain.getAvailableDiskSize() != null) { sDomain.setUsedDiskSize((int) (size / IrsBrokerCommand.BYTES_TO_GB) - sDomain.getAvailableDiskSize()); } if (vg.containsKey("vgtype")) { sDomain.setStorageType(EnumUtils.valueOf(StorageType.class, vg.get("vgtype").toString(), true)); } else { sDomain.setStorageType(StorageType.UNKNOWN); } result.add(sDomain); } return result; }
Source:
public void sendPasswordResetLinkEmail(PerunSession sess, Member member, String namespace, String url, String mailAttributeUrn, String language) throws InternalErrorException, PrivilegeException, MemberNotExistsException, UserNotExistsException, AttributeNotExistsException { Utils.checkPerunSession(sess); getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, member)) { throw new PrivilegeException(sess, "sendPasswordResetLinkEmail"); } Attribute mailAttribute = null; AttributeDefinition ad = getPerunBl().getAttributesManager().getAttributeDefinition(sess, mailAttributeUrn); try { if (ad.getEntity().equals("user")) { User user = perunBl.getUsersManagerBl().getUserByMember(sess, member); mailAttribute = getPerunBl().getAttributesManager().getAttribute(sess, user, mailAttributeUrn); } if (ad.getEntity().equals("member")) { mailAttribute = getPerunBl().getAttributesManager().getAttribute(sess, member, mailAttributeUrn); } } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } if (mailAttribute != null) { String mailAddress = mailAttribute.valueAsString(); getMembersManagerBl().sendPasswordResetLinkEmail(sess, member, namespace, url, mailAddress, language); } }

Target:
public void sendPasswordResetLinkEmail(PerunSession sess, Member member, String namespace, String url, String mailAttributeUrn, String language) throws InternalErrorException, PrivilegeException, MemberNotExistsException, UserNotExistsException, AttributeNotExistsException { Utils.checkPerunSession(sess); getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, member)) { throw new PrivilegeException(sess, "sendPasswordResetLinkEmail"); } Attribute mailAttribute = null; AttributeDefinition ad = getPerunBl().getAttributesManager().getAttributeDefinition(sess, mailAttributeUrn); try { if (ad.getEntity().equals("user")) { User user = perunBl.getUsersManagerBl().getUserByMember(sess, member); mailAttribute = getPerunBl().getAttributesManager().getAttribute(sess, user, mailAttributeUrn); } if (ad.getEntity().equals("member")) { mailAttribute = getPerunBl().getAttributesManager().getAttribute(sess, member, mailAttributeUrn); } } catch (WrongAttributeAssignmentException ex) { throw new InternalErrorException(ex); } if (mailAttribute == null) { throw new InternalErrorException("MailAttribute should not be null."); } String mailAddress = mailAttribute.valueAsString(); getMembersManagerBl().sendPasswordResetLinkEmail(sess, member, namespace, url, mailAddress, language); }
Source:
public void testNoAdminPasswordCfgFile() throws Exception { MasterDaemon md = new MasterDaemon(workingDir, REST_PORT); md.start(); Client client = ClientBuilder.newClient(); Invocation.Builder invocation = client.target("http://localhost:" + REST_PORT + "/server/deployment_cfg").request(MediaType.TEXT_PLAIN_TYPE); Response response = invocation.get(); assertEquals(Status.OK.getStatusCode(), response.getStatus()); String respond = response.readEntity(String.class); assertTrue(respond.equals(Paths.get(workingDir, MyriaConstants.DEPLOYMENT_CONF_FILE).toString())); client.close(); md.stop(); }

Target:
public void testNoAdminPasswordCfgFile() throws Exception { MasterDaemon md = new MasterDaemon(workingDir, REST_PORT); md.start(); Client client = ClientBuilder.newClient(); Invocation.Builder invocation = client.target("http://localhost:" + REST_PORT + "/server/deployment_cfg").request(MediaType.TEXT_PLAIN_TYPE); Response response = invocation.get(); assertEquals(Status.OK.getStatusCode(), response.getStatus()); String respond = response.readEntity(String.class); assertEquals(Paths.get(workingDir, MyriaConstants.DEPLOYMENT_CONF_FILE).toString(), respond); client.close(); md.stop(); }
Source:
public void execute() { log.info("method executing started"); generateUICForPatientsWithout(); }

Target:
public void execute() { log.info("method executing started"); aijarService.generateAndSaveUICForPatientsWithOut(); }
Source:
protected void onStart() { final long interval = 10 * 20L; final File databaseFile = getDatabase(); if (!ConfigEntry.COREPROTECT_AUTO_WIPING_ENABLED.getBoolean() || getCoreProtect() == null) { return; } wiper = new BukkitRunnable() { @Override public void run() { final CoreProtect coreProtect = getCoreProtect(); double bytes = databaseFile.length(); double kilobytes = (bytes / 1024); double megabytes = (kilobytes / 1024); double gigabytes = (megabytes / 1024); if (gigabytes > ConfigEntry.COREPROTECT_FILE_LIMIT.getInteger()) { FLog.info("The CoreProtect log file has grown too big for the server to cope, the data will be wiped!"); PluginManager pluginManager = server.getPluginManager(); pluginManager.disablePlugin(coreProtect); FUtil.deleteFolder(databaseFile); pluginManager.enablePlugin(coreProtect); } } }.runTaskTimer(plugin, interval, interval); }

Target:
protected void onStart() { if (ConfigEntry.COREPROTECT_AUTO_WIPING_ENABLED.getBoolean() && getCoreProtect() != null) { createAutomaticWiper(); } }
Source:
private void cleanup() { OkHttpClient httpClient = getHttpClient(); try { if (httpClient.connectionPool() != null) { httpClient.connectionPool().evictAll(); } if (httpClient.dispatcher() != null && httpClient.dispatcher().executorService() != null && !httpClient.dispatcher().executorService().isShutdown()) { httpClient.dispatcher().executorService().shutdown(); } } catch (RuntimeException ex) { LOG.error(ex.getMessage()); } }

Target:
private void cleanup() { try { doCleanup(); } catch (RuntimeException ex) { LOG.error(ex.getMessage()); } }
Source:
private GraphicsInfo getGraphicsInfo() { final VM vm = vmDao.get(getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (vm == null) { throw new RuntimeException( String.format("Vm id=%s can't be obtained. Insufficient permissions?", getParameters().getVmId())); } final GraphicsInfo graphicsInfo = vm.getGraphicsInfos().get(getParameters().getGraphicsType()); if (graphicsInfo == null) { throw new RuntimeException( String.format( "Graphics console can't be obtained, vmid=%s console=%s. Is vm ready for connecting to console?", getParameters().getVmId(), getParameters().getGraphicsType())); } return graphicsInfo; }

Target:
private GraphicsInfo getGraphicsInfo() { final VM vm = vmDao.get(getParameters().getVmId(), getUserID(), getParameters().isFiltered()); if (vm == null) { throw new EngineException(EngineError.VMCantBeObtained, String.format("vmid=%s", getParameters().getVmId())); } final GraphicsInfo graphicsInfo = vm.getGraphicsInfos().get(getParameters().getGraphicsType()); if (graphicsInfo == null) { throw new EngineException(EngineError.GraphicsConsoleCantBeObtained, String.format( "vmid=%s console=%s", getParameters().getVmId(), getParameters().getGraphicsType())); } return graphicsInfo; }
Source:
void serve(final HttpServletRequest req, final HttpServletResponse rsp, final boolean sendBody) throws IOException { if (!initRangeRequest(req, rsp)) { rsp.sendError(SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } rsp.setHeader(HDR_ACCEPT_RANGES, "bytes"); rsp.setContentLength((int) (end - pos)); if (sendBody) { final OutputStream out = rsp.getOutputStream(); try { final byte[] buf = new byte[4096]; while (pos < end) { final int r = Math.min(buf.length, (int) (end - pos)); final int n = source.read(buf, 0, r); if (n < 0) { throw new EOFException("Unexpected EOF on " + path); } out.write(buf, 0, n); pos += n; } out.flush(); } finally { out.close(); } } }

Target:
void serve(final HttpServletRequest req, final HttpServletResponse rsp, final boolean sendBody) throws IOException { if (!initRangeRequest(req, rsp)) { rsp.sendError(SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } rsp.setHeader(HDR_ACCEPT_RANGES, "bytes"); rsp.setHeader(HDR_CONTENT_LENGTH, Long.toString(end - pos)); if (sendBody) { final OutputStream out = rsp.getOutputStream(); try { final byte[] buf = new byte[4096]; while (pos < end) { final int r = (int) Math.min(buf.length, end - pos); final int n = source.read(buf, 0, r); if (n < 0) { throw new EOFException("Unexpected EOF on " + path); } out.write(buf, 0, n); pos += n; } out.flush(); } finally { out.close(); } } }
Source:
private static void convertRowTypesToOutputTypes(List<DimensionSpec> dimensionSpecs, Map<String, Object> rowMap) { for (DimensionSpec dimSpec : dimensionSpecs) { Object baseVal = rowMap.get(dimSpec.getOutputName()); switch (dimSpec.getOutputType()) { case STRING: baseVal = baseVal == null ? "" : baseVal.toString(); break; case LONG: baseVal = DimensionHandlerUtils.convertObjectToLong(baseVal); baseVal = baseVal == null ? 0L : baseVal; break; case FLOAT: baseVal = DimensionHandlerUtils.convertObjectToFloat(baseVal); baseVal = baseVal == null ? 0.f : baseVal; break; default: throw new IAE("Unsupported type: " + dimSpec.getOutputType()); } rowMap.put(dimSpec.getOutputName(), baseVal); } }

Target:
private static void convertRowTypesToOutputTypes(List<DimensionSpec> dimensionSpecs, Map<String, Object> rowMap) { for (DimensionSpec dimSpec : dimensionSpecs) { final ValueType outputType = dimSpec.getOutputType(); rowMap.compute( dimSpec.getOutputName(), (dimName, baseVal) -> { switch (outputType) { case STRING: baseVal = baseVal == null ? "" : baseVal.toString(); break; case LONG: baseVal = DimensionHandlerUtils.convertObjectToLong(baseVal); baseVal = baseVal == null ? 0L : baseVal; break; case FLOAT: baseVal = DimensionHandlerUtils.convertObjectToFloat(baseVal); baseVal = baseVal == null ? 0.f : baseVal; break; default: throw new IAE("Unsupported type: " + outputType); } return baseVal; } ); } }
Source:
private void cleanup() { try { if (httpClient.connectionPool() != null) { httpClient.connectionPool().evictAll(); } if (httpClient.dispatcher() != null && httpClient.dispatcher().executorService() != null && !httpClient.dispatcher().executorService().isShutdown()) { httpClient.dispatcher().executorService().shutdown(); } } catch (RuntimeException ex) { LOG.error(ex.getMessage()); } }

Target:
private void cleanup() { try { doCleanup(); } catch (RuntimeException ex) { LOG.error(ex.getMessage()); } }
Source:
public void show() { this.atlas = new TextureAtlas("uiskin.atlas"); this.skin = new Skin(Gdx.files.internal("uiskin.json"), this.atlas); this.stage = new Stage(); Texture texture = new Texture( Gdx.files.internal("assets/data/loading.jpeg")); TextureRegion region = new TextureRegion(texture, 0, 0, 1920, 1080); Image image = new Image(region); image.setFillParent(true); this.stage.addActor(image); this.timer = new Label("Time till game start: ", this.skin); this.timer.setPosition(1200, 540); this.stage.addActor(this.timer); this.counter = new Label("Connected: ", this.skin); this.counter.setPosition(1200, 500); this.stage.addActor(this.counter); this.startTimer(5); }

Target:
public void show() { this.atlas = new TextureAtlas("assets/uiskin.atlas"); this.skin = new Skin(Gdx.files.internal("assets/uiskin.json"), this.atlas); this.stage = new Stage(); Texture texture = new Texture( Gdx.files.internal("assets/data/loading.jpeg")); TextureRegion region = new TextureRegion(texture, 0, 0, (int) DesktopLauncher.WIDTH, (int) DesktopLauncher.HEIGHT); Image image = new Image(region); image.setFillParent(true); this.stage.addActor(image); this.createTimerLabel(); this.createCounterLabel(); this.startTimer(2); }
Source:
public void test() { connect(); jq(".z-listbox-body").scrollTop(10000); waitResponse(); Assert.assertTrue(jq("@listcell:contains(199)").exists()); }

Target:
public void test() { connect(); waitResponse(); jq(".z-listbox-body").scrollTop(10000); waitResponse(); Assert.assertTrue(jq("@listcell:contains(199)").exists()); }
Source:
public void downloadTransformation(HttpServletResponse response) throws IOException { InputStream inputStream = new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8)); response.setContentLength(result.length()); response.setHeader("Content-Disposition", String.format("attachment; filename=" + "TransformationResult")); FileCopyUtils.copy(inputStream, response.getOutputStream()); }

Target:
public String downloadTransformation(HttpServletResponse response) throws IOException { if (result == null) { return "auth/transformation/failureTransformation"; } InputStream inputStream = new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8)); response.setContentLength(result.length()); response.setHeader("Content-Disposition", String.format("attachment; filename=" + "TransformationResult.graphml")); FileCopyUtils.copy(inputStream, response.getOutputStream()); return null; }
Source:
public void addCluster(String clusterName, boolean overwritePrevious, CloudConfig cloudConfig) throws HelixException { _admin.addCluster(clusterName, overwritePrevious); for (BuiltInStateModelDefinitions def : BuiltInStateModelDefinitions.values()) { addStateModelDef(clusterName, def.getStateModelDefinition().getId(), def.getStateModelDefinition(), overwritePrevious); } if (cloudConfig != null) { _admin.addCloudConfig(clusterName, cloudConfig); if (cloudConfig.isCloudEnabled() && cloudConfig.getCloudProvider().equals(CloudProvider.AZURE.name())) { ConfigAccessor configAccessor = new ConfigAccessor(_zkServerAddress); ClusterConfig clusterConfig = new ClusterConfig(clusterName); clusterConfig.setTopology("/helixZoneId/host"); clusterConfig.setTopologyAwareEnabled(true); clusterConfig.setFaultZoneType("helixZoneId"); configAccessor.updateClusterConfig(clusterName, clusterConfig); } } }

Target:
public void addCluster(String clusterName, boolean overwritePrevious, CloudConfig cloudConfig) throws HelixException { _admin.addCluster(clusterName, overwritePrevious); for (BuiltInStateModelDefinitions def : BuiltInStateModelDefinitions.values()) { addStateModelDef(clusterName, def.getStateModelDefinition().getId(), def.getStateModelDefinition(), overwritePrevious); } if (cloudConfig != null) { _admin.addCloudConfig(clusterName, cloudConfig); if (cloudConfig.isCloudEnabled() && cloudConfig.getCloudProvider().equals(CloudProvider.AZURE.name())) { ConfigAccessor configAccessor = new ConfigAccessor(_zkServerAddress); ClusterConfig clusterConfig = new ClusterConfig(clusterName); clusterConfig.setTopology(AzureConstants.AZURE_TOPOLOGY); clusterConfig.setTopologyAwareEnabled(true); clusterConfig.setFaultZoneType(AzureConstants.AZURE_FAULT_ZONE_TYPE); configAccessor.updateClusterConfig(clusterName, clusterConfig); } } }
Source:
private byte[] encrypt(final byte[] bytes) throws IOException { try { final Cipher cipher = Cipher.getInstance(ALGORITHM); final AlgorithmParameterSpec spec = new IvParameterSpec(this.ivbytes); cipher.init(Cipher.ENCRYPT_MODE, this.secret, spec); return cipher.doFinal(bytes); } catch (final InvalidKeyException ike) { throw new IOException(ike); } catch (final NoSuchAlgorithmException nse) { throw new IOException(nse); } catch (final NoSuchPaddingException nspe) { throw new IOException(nspe); } catch (final InvalidAlgorithmParameterException iape) { throw new IOException(iape); } catch (final IllegalBlockSizeException ibse) { throw new IOException(ibse); } catch (final BadPaddingException bpe) { throw new IOException(bpe); } }

Target:
private byte[] encrypt(final byte[] bytes) throws IOException { try { return this.enc.doFinal(bytes); } catch (final GeneralSecurityException gse) { throw new IOException(gse); } }
Source:
public List<HostAddress> getAddresses() { return ImmutableList.of(); }

Target:
public List<HostAddress> getAddresses() { return ImmutableList.of(address); }
Source:
public Set<AccountGroup.Id> getEffectiveGroups() { if (effectiveGroups == null) { Set<AccountGroup.Id> seedGroups = new HashSet<AccountGroup.Id> (); if (authConfig.isIdentityTrustable(state().getExternalIds())) { seedGroups = realm.groups(state()); } else { seedGroups = authConfig.getRegisteredGroups(); } effectiveGroups = getIncludedGroups(seedGroups); } return effectiveGroups; }

Target:
public Set<AccountGroup.Id> getEffectiveGroups() { if (effectiveGroups == null) { Set<AccountGroup.Id> seedGroups; if (authConfig.isIdentityTrustable(state().getExternalIds())) { seedGroups = realm.groups(state()); } else { seedGroups = authConfig.getRegisteredGroups(); } effectiveGroups = getIncludedGroups(seedGroups); } return effectiveGroups; }
Source:
private void validateDepDefinitionUniqueness(final List<TriggerDependencyBean> dependencies) { final Set<String> seen = new HashSet<>(); for (final TriggerDependencyBean dep : dependencies) { final Map<String, String> props = dep.getParams(); Preconditions.checkArgument(seen.add(dep.getType() + ":" + props.toString()), String.format ("duplicate " + "dependency" + "config %s found, dependency config should be unique", dep.getName())); } }

Target:
private void validateDepDefinitionUniqueness(final List<TriggerDependencyBean> dependencies) { for (int i = 0; i < dependencies.size(); i++) { for (int j = i + 1; j < dependencies.size(); j++) { final boolean duplicateDepDefFound = dependencies.get(i).getType().equals(dependencies.get(j) .getType()) && dependencies.get(i).getParams() .equals(dependencies.get(j).getParams()); Preconditions.checkArgument(!duplicateDepDefFound, String.format("duplicate dependency" + "config %s found, dependency config should be unique", dependencies.get(i).getName())); } } }
Source:
public void testNameStrategyOnExistingFolders() throws Exception{ jenkins.setProjectNamingStrategy(new ProjectNamingStrategy.PatternProjectNamingStrategy("DUMMY.*", true)); try { Folder folder = jenkins.createProject(Folder.class, "DUMMY_folder"); assertNotNull("No folder created", folder); try { jenkins.createProject(Folder.class, "project"); fail("Should not get here, the folder name is not allowed, therefore the creation must fail!"); } catch (Failure failure) { } try { folder.renameTo("project"); folder.setDisplayName("project"); folder.save(); System.out.println(folder.getDisplayName()); fail("Should not be allowed to rename existing folder to invalid folder."); } catch (Failure failure) { } } finally { jenkins.setProjectNamingStrategy(ProjectNamingStrategy.DEFAULT_NAMING_STRATEGY); } }

Target:
public void testNameStrategyOnExistingFolders() throws Exception{ jenkins.setProjectNamingStrategy(new ProjectNamingStrategy.PatternProjectNamingStrategy("DUMMY.*", true)); Folder folder = jenkins.createProject(Folder.class, "DUMMY_folder"); assertNotNull("No folder created", folder); try { jenkins.createProject(Folder.class, "project"); fail("Should not get here, the folder name is not allowed, therefore the creation must fail!"); } catch (Failure failure) { } try { folder.renameTo("project"); folder.setDisplayName("project"); folder.save(); System.out.println(folder.getDisplayName()); fail("Should not be allowed to rename existing folder to invalid folder."); } catch (Failure failure) { } }