auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void setNameAndPresetDefaults(String presetSubtypeName) { String faction = entity.getFaction(); String nameTag = "entity.ancientwarfarenpc." + faction + "." + presetSubtypeName + "." + "name"; entity.setCustomNameTag(I18n.translateToLocal(nameTag)); String[] spells = (NpcDefaultsRegistry.getFactionNpcDefault(entity.getFaction(), presetSubtypeName).getSpells()).split(","); for (String spell : spells) { try { Spell spellObj = Spell.get(spell); addSpell(spellObj); } catch (NullPointerException n) { AncientWarfareNPC.LOG.warn("Couldn't assign spell " + spell + " in preset of " + nameTag); } } int basehealth = (int) NpcDefaultsRegistry.getFactionNpcDefault(entity.getFaction(), presetSubtypeName).getBaseHealth(); System.out.println("basehealth: " + basehealth); maxHealth = (int) (basehealth); skinSettings.setSkinType(NpcSkinSettings.SkinType.NPC_TYPE); skinSettings.setRandom(true); skinSettings.setNpcTypeName(faction + "." + presetSubtypeName); }

Target:
public void setNameAndPresetDefaults(String presetSubtypeName) { String faction = entity.getFaction(); String nameTag = "entity.ancientwarfarenpc." + faction + "." + presetSubtypeName + "." + "name"; entity.setCustomNameTag(I18n.translateToLocal(nameTag)); String[] spells = (NpcDefaultsRegistry.getFactionNpcDefault(entity.getFaction(), presetSubtypeName).getSpells()).split(","); for (String spell : spells) { Spell spellObj = Spell.get(spell); addSpell(spellObj); } int basehealth = (int) NpcDefaultsRegistry.getFactionNpcDefault(entity.getFaction(), presetSubtypeName).getBaseHealth(); maxHealth = (int) (basehealth); skinSettings.setSkinType(NpcSkinSettings.SkinType.NPC_TYPE); skinSettings.setRandom(true); skinSettings.setNpcTypeName(faction + "." + presetSubtypeName); }
Source:
public void validate(Element element, ElementValidation validation) { injectHelper.validate(FragmentArg.class, element, validation); validatorHelper.isNotPrivate(element, validation); Element param = element; if (element instanceof ExecutableElement) { param = ((ExecutableElement) element).getParameters().get(0); } validatorHelper.canBePutInABundle(param, validation); }

Target:
public void validate(Element element, ElementValidation validation) { injectHelper.validate(FragmentArg.class, element, validation); validatorHelper.isNotPrivate(element, validation); Element param = injectHelper.getParam(element); validatorHelper.canBePutInABundle(param, validation); }
Source:
public int run() throws IOException { mMetricsMap = mMetricsMasterClient.getMetrics(); SortedSet<String> names = new TreeSet<>(mMetricsMap.keySet()); for (String name : names) { if (!isAlluxioMetric(name)) { continue; } MetricValue metricValue = mMetricsMap.get(name); String strValue; if (metricValue.hasStringValue()) { strValue = metricValue.getStringValue(); } else { double doubleValue = metricValue.getDoubleValue(); if (name.contains(BYTES_METRIC_IDENTIFIER)) { strValue = FormatUtils.getSizeFromBytes((long) doubleValue); if (name.contains(THROUGHPUT_METRIC_IDENTIFIER)) { strValue = strValue + "/SEC"; } } else if (DoubleMath.isMathematicalInteger(doubleValue)) { strValue = DECIMAL_FORMAT.format((long) doubleValue); } else { strValue = String.valueOf(doubleValue); } } mPrintStream.printf(INFO_FORMAT, name, metricValue.getMetricType(), strValue); } return 0; }

Target:
public int run() throws IOException { mMetricsMap = mMetricsMasterClient.getMetrics(); SortedSet<String> names = new TreeSet<>(mMetricsMap.keySet()); for (String name : names) { if (!isAlluxioMetric(name)) { continue; } MetricValue metricValue = mMetricsMap.get(name); String strValue; if (metricValue.hasStringValue()) { strValue = metricValue.getStringValue(); } else { double doubleValue = metricValue.getDoubleValue(); if (name.contains(BYTES_METRIC_IDENTIFIER)) { strValue = FormatUtils.getSizeFromBytes((long) doubleValue); if (name.contains(THROUGHPUT_METRIC_IDENTIFIER)) { strValue = strValue + "/MIN"; } } else if (DoubleMath.isMathematicalInteger(doubleValue)) { strValue = DECIMAL_FORMAT.format((long) doubleValue); } else { strValue = String.valueOf(doubleValue); } } mPrintStream.printf(INFO_FORMAT, name, metricValue.getMetricType(), strValue); } return 0; }
Source:
public static File[] getExtensionFilesToLoad(ExtensionsConfig config) { File[] extensionsToLoad; final File rootExtensionsDir = new File(config.getExtensionsDir()); final List<String> toLoad = config.getToLoad(); if (toLoad == null) { extensionsToLoad = rootExtensionsDir.exists() ? rootExtensionsDir.listFiles() : new File[]{}; } else { int i = 0; extensionsToLoad = new File[toLoad.size()]; for (final String extensionName : toLoad) { final File extensionDir = new File(rootExtensionsDir, extensionName); if (!extensionDir.exists()) { throw new RuntimeException( String.format( "Extension [%s] specified in \"druid.extensions.toLoad\" didn't exist!?", extensionDir.getAbsolutePath() ) ); } extensionsToLoad[i++] = extensionDir; } } return extensionsToLoad; }

Target:
public static File[] getExtensionFilesToLoad(ExtensionsConfig config) { final File rootExtensionsDir = new File(config.getDirectory()); if (rootExtensionsDir.exists() && !rootExtensionsDir.isDirectory()) { throw new ISE("Root extensions directory [%s] is not a directory!?", rootExtensionsDir); } File[] extensionsToLoad; final List<String> toLoad = config.getLoadList(); if (toLoad == null) { extensionsToLoad = rootExtensionsDir.listFiles(); } else { int i = 0; extensionsToLoad = new File[toLoad.size()]; for (final String extensionName : toLoad) { final File extensionDir = new File(rootExtensionsDir, extensionName); if (!extensionDir.isDirectory()) { throw new ISE( String.format( "Extension [%s] specified in \"druid.extensions.loadList\" didn't exist!?", extensionDir.getAbsolutePath() ) ); } extensionsToLoad[i++] = extensionDir; } } return extensionsToLoad == null ? new File[]{} : extensionsToLoad; }
Source:
public void payloadLimitingClientThrowsOnRequestThatIsTooLarge() { TestResource client = AtlasDbHttpClients.createProxy(new MetricRegistry(), NO_SSL, getUriForPort(availablePort), TestResource.class, true); assertThat(client.postRequest(new byte[AtlasDbInterceptors.MAX_PAYLOAD_SIZE / 2])).isTrue(); assertThatThrownBy(() -> client.postRequest(new byte[AtlasDbInterceptors.MAX_PAYLOAD_SIZE])) .isInstanceOf(IllegalArgumentException.class); }

Target:
public void payloadLimitingClientThrowsOnRequestThatIsTooLarge() { TestResource client = AtlasDbHttpClients.createProxy(new MetricRegistry(), NO_SSL, getUriForPort(availablePort), TestResource.class, true); assertThat(client.postRequest(new byte[AtlasDbInterceptors.MAX_PAYLOAD_SIZE / 2])) .as("Request with payload size below limit succeeds") .isTrue(); assertThatThrownBy(() -> client.postRequest(new byte[AtlasDbInterceptors.MAX_PAYLOAD_SIZE])) .as("Request with payload size exceeding limit throws") .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Request too large"); }
Source:
protected int run(List<String> nonFlagArgs) throws Exception { mKiji = Kiji.Factory.open(mURI); try { mTable = mKiji.getSchemaTable(); if (mCreateFlag != null && !mCreateFlag.isEmpty()) { File file = new File(mCreateFlag); Schema schema = new Schema.Parser().parse(file); long id = mTable.getOrCreateSchemaId(schema); if (isInteractive()) { getPrintStream().println("Schema table schema ID for the given schema is: \n"); } getPrintStream().println(id); return SUCCESS; } else { Schema schema = mTable.getSchema(mGetFlag); Preconditions.checkArgument(schema != null, "No schema definition with ID: %s", mGetFlag); try { File file = new File(mOutputFlag); boolean fileCreated = file.createNewFile(); if (fileCreated) { FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); try { bw.write(schema.toString()); } finally { bw.close(); } } else { if (mayProceed("File: %s already exists, do you wish to overwrite the file?", mOutputFlag)) { FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); try { bw.write(schema.toString()); } finally { bw.close(); } } else { return ABORTED; } } if (isInteractive()) { getPrintStream().println( String.format("Schema definition written to: %s", mOutputFlag)); } return SUCCESS; } catch (IOException ioe) { LOG.error(String.format("Error writing to file: %s", mOutputFlag)); throw ioe; } } } finally { mKiji.release(); } }

Target:
protected int run(List<String> nonFlagArgs) throws Exception { mKiji = Kiji.Factory.open(mURI); try { final KijiSchemaTable table = mKiji.getSchemaTable(); if (mRegisterFlag != null && !mRegisterFlag.isEmpty()) { final File file = new File(mRegisterFlag); final Schema schema = new Schema.Parser().parse(file); final long id = table.getOrCreateSchemaId(schema); if (isInteractive()) { getPrintStream().println("Schema table schema ID for the given schema is: \n"); } getPrintStream().println(id); return SUCCESS; } else { final Schema schema = table.getSchema(mGetFlag); Preconditions.checkArgument(schema != null, "No schema definition with ID: %s", mGetFlag); try { final File file = new File(mOutputFlag); final boolean fileCreated = file.createNewFile(); if (fileCreated) { final FileOutputStream fop = new FileOutputStream(file.getAbsoluteFile()); try { fop.write(schema.toString().getBytes("utf-8")); fop.flush(); } finally { fop.close(); } } else { if (mayProceed("File: %s already exists, do you wish to overwrite the file?", mOutputFlag)) { final FileOutputStream fop = new FileOutputStream(file.getAbsoluteFile()); try { fop.write(schema.toString().getBytes("utf-8")); } finally { fop.flush(); fop.close(); } } else { return FAILURE; } } if (isInteractive()) { getPrintStream().printf("Schema definition written to: %s", mOutputFlag); } return SUCCESS; } catch (IOException ioe) { LOG.error("Error writing to file: {}", mOutputFlag); throw ioe; } } } finally { mKiji.release(); } }
Source:
private int getDnsProbeTimeout() { return getIntSetting(mContext, R.integer.config_captive_portal_dns_probe_timeout, CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT, R.integer.default_captive_portal_dns_probe_timeout); }

Target:
private int getDnsProbeTimeout() { final Context targetContext = getContextByMccIfNoSimCardOrDefault(); return getIntSetting(targetContext, R.integer.config_captive_portal_dns_probe_timeout, CONFIG_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT, R.integer.default_captive_portal_dns_probe_timeout); }
Source:
protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.network_setting); mPhone = PhoneFactory.getDefaultPhone(); mHandler = new MyHandler(); PreferenceScreen prefSet = getPreferenceScreen(); mButtonDataRoam = (CheckBoxPreference) prefSet.findPreference(BUTTON_ROAMING_KEY); mButtonPreferredNetworkMode = (ListPreference) prefSet.findPreference( BUTTON_PREFERED_NETWORK_MODE); if (getResources().getBoolean(R.bool.world_phone) == true) { mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this); int settingsNetworkMode = android.provider.Settings.Secure.getInt(mPhone.getContext(). getContentResolver(),android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, preferredNetworkMode); mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode)); mCdmaOptions = new CdmaOptions(this, prefSet); mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet); } else { prefSet.removePreference(mButtonPreferredNetworkMode); prefSet.removePreference(prefSet.findPreference(BUTTON_GSM_UMTS_OPTIONS)); prefSet.removePreference(prefSet.findPreference(BUTTON_CDMA_OPTIONS)); int phoneType = mPhone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { mButtonCdmaSystemSelect = (CdmaSystemSelectListPreference) prefSet .findPreference(BUTTON_CDMA_SYSTEM_SELECT_KEY); mCdmaOptions = new CdmaOptions(this, prefSet); } else if (phoneType == Phone.PHONE_TYPE_GSM) { mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } }

Target:
protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.network_setting); mPhone = PhoneFactory.getDefaultPhone(); mHandler = new MyHandler(); PreferenceScreen prefSet = getPreferenceScreen(); mButtonDataRoam = (CheckBoxPreference) prefSet.findPreference(BUTTON_ROAMING_KEY); mButtonPreferredNetworkMode = (ListPreference) prefSet.findPreference( BUTTON_PREFERED_NETWORK_MODE); if (getResources().getBoolean(R.bool.world_phone) == true) { mButtonPreferredNetworkMode.setOnPreferenceChangeListener(this); int settingsNetworkMode = android.provider.Settings.Secure.getInt(mPhone.getContext(). getContentResolver(),android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, preferredNetworkMode); mButtonPreferredNetworkMode.setValue(Integer.toString(settingsNetworkMode)); mCdmaOptions = new CdmaOptions(this, prefSet); mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet); } else { prefSet.removePreference(mButtonPreferredNetworkMode); int phoneType = mPhone.getPhoneType(); if (phoneType == Phone.PHONE_TYPE_CDMA) { mButtonCdmaSystemSelect = (CdmaSystemSelectListPreference) prefSet .findPreference(BUTTON_CDMA_SYSTEM_SELECT_KEY); mCdmaOptions = new CdmaOptions(this, prefSet); } else if (phoneType == Phone.PHONE_TYPE_GSM) { mGsmUmtsOptions = new GsmUmtsOptions(this, prefSet); } else { throw new IllegalStateException("Unexpected phone type: " + phoneType); } } }
Source:
public void onError(Throwable e) { if (!done) { done = true; actual.onError(e); } }

Target:
public void onError(Throwable e) { if (!done) { done = true; actual.onError(e); } else { RxJavaHooks.onError(e); } }
Source:
public long getEstimatedKeyCount() throws IOException { try { return db.getLongProperty(handle, "rocksdb.estimate-num-keys"); } catch (RocksDBException e) { throw new IOException( "Failed to get estimated key count of table."); } }

Target:
public long getEstimatedKeyCount() throws IOException { try { return db.getLongProperty(handle, "rocksdb.estimate-num-keys"); } catch (RocksDBException e) { throw toIOException( "Failed to get estimated key count of table " + getName(), e); } }
Source:
public CompletableFuture<?> getAllBarriersReceivedFuture(long checkpointId) { if (checkpointId < currentCheckpointId) { return CompletableFuture.completedFuture(null); } if (checkpointId > currentCheckpointId) { throw new IllegalStateException("Checkpoint " + checkpointId + " has not been started at all"); } return allBarriersReceivedFuture; }

Target:
public CompletableFuture<Void> getAllBarriersReceivedFuture(long checkpointId) { return threadSafeUnaligner.getAllBarriersReceivedFuture(checkpointId); }
Source:
private synchronized void updateReview(TaskTask task) { String summary = task.getSummary(); boolean ourQuery = task.getParentContainers().contains(fCurrentQuery); if (ourQuery && summary != null && !summary.equals("")) { try { TaskData taskData = fConnector.getTaskData(getTaskRepository(), task.getTaskId(), new NullProgressMonitor()); GerritTask gtask = new GerritTask(taskData); if (gtask.getAttribute(GerritTask.DATE_COMPLETION) == null) { fReviewTable.updateReviewItem(gtask); } } catch (CoreException e) { StatusHandler.log(new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, NLS.bind( "Unable to update the table ''{0}'' ", e))); } } }

Target:
private synchronized void updateReview(TaskTask task) { String summary = task.getSummary(); boolean ourQuery = task.getParentContainers().contains(fCurrentQuery); if (ourQuery && summary != null && !summary.equals("")) { try { TaskData taskData = fConnector.getTaskData(getTaskRepository(), task.getTaskId(), new NullProgressMonitor()); GerritTask gtask = new GerritTask(taskData); if (gtask.getAttribute(GerritTask.DATE_COMPLETION) == null) { fReviewTable.updateReviewItem(gtask); } } catch (CoreException e) { StatusHandler.log(new Status(IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, NLS.bind( "Unable to update the table ''{0}'' ", e.getMessage()))); } } }
Source:
public boolean tryReserveMemory(String allocationTag, long delta, boolean enforceBroadcastMemoryLimit) { if (enforceBroadcastMemoryLimit && !tryUpdateBroadcastMemoryFunction.test(delta)) { return false; } return tryReserveMemoryFunction.test(allocationTag, delta); }

Target:
public boolean tryReserveMemory(String allocationTag, long delta, boolean enforceBroadcastMemoryLimit) { if (!tryReserveMemoryFunction.test(allocationTag, delta)) { return false; } return !enforceBroadcastMemoryLimit || tryUpdateBroadcastMemoryFunction.test(delta); }
Source:
private void drawVertexLane(final SequenceSegment segment) { for (int index = 0; index <= lanes.size(); index++) { if (index >= lanes.size() || lanes.get(index) <= segment.getStart() && segmentFree(index, segment)) { segmentInsert(index, segment); String text = segment.getContent().toString(); drawVertex(text, segment.getStart(), index, segment .getContent().getLength(), segment.getSources().size(), sequenceColor(segment.getMutation())); break; } } }

Target:
private void drawVertexLane(final SequenceSegment segment) { String text = segment.getContent().toString(); long start = segment.getStart(); long width = segment.getContent().getLength(); long height = segment.getSources().size(); Color color = sequenceColor(segment.getMutation()); for (int index = 0; index < lanes.size(); index++) { if (lanes.get(index) <= segment.getStart() && segmentFree(index, segment)) { drawVertex(text, start, index, width, height, color); segmentInsert(index, segment); return; } } drawVertex(text, start, lanes.size(), width, height, color); segmentInsert(lanes.size(), segment); }
Source:
public static String getMetricsJMXDomain(Map reporterConf) { return Utils.getString(reporterConf.get(Config.STORM_DAEMON_METRICS_REPORTER_PLUGIN_DOMAIN), null); }

Target:
public static String getMetricsJMXDomain(Map reporterConf) { return Utils.getString(reporterConf.get(JMX_DOMAIN), null); }
Source:
private void initAllContentViews() { mLoginToMyAccountView = getLayoutInflater().inflate(R.layout.my_account, null); mUsername = mLoginToMyAccountView.findViewById(R.id.username); mPassword = mLoginToMyAccountView.findViewById(R.id.password); mPassword.setOnKeyListener((v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: login(); return true; default: break; } } return false; }); Button loginButton = mLoginToMyAccountView.findViewById(R.id.login_button); loginButton.setOnClickListener(v -> login()); Button resetPWButton = mLoginToMyAccountView.findViewById(R.id.reset_password_button); resetPWButton.setOnClickListener(v -> resetPassword()); Button signUpButton = mLoginToMyAccountView.findViewById(R.id.sign_up_button); Uri url = Uri.parse(getResources().getString(R.string.register_url)); signUpButton.setOnClickListener(v -> openUrl(url)); mLoggedIntoMyAccountView = getLayoutInflater().inflate(R.layout.my_account_logged_in, null); mUsernameLoggedIn = mLoggedIntoMyAccountView.findViewById(R.id.username_logged_in); Button logoutButton = mLoggedIntoMyAccountView.findViewById(R.id.logout_button); logoutButton.setOnClickListener(v -> logout()); }

Target:
private void initAllContentViews() { mLoginToMyAccountView = getLayoutInflater().inflate(R.layout.my_account, null); mUsername = mLoginToMyAccountView.findViewById(R.id.username); mPassword = mLoginToMyAccountView.findViewById(R.id.password); mPassword.setOnKeyListener((v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_NUMPAD_ENTER: login(); return true; default: break; } } return false; }); Button loginButton = mLoginToMyAccountView.findViewById(R.id.login_button); loginButton.setOnClickListener(v -> login()); Button resetPWButton = mLoginToMyAccountView.findViewById(R.id.reset_password_button); resetPWButton.setOnClickListener(v -> resetPassword()); Button signUpButton = mLoginToMyAccountView.findViewById(R.id.sign_up_button); Uri url = Uri.parse(getResources().getString(R.string.register_url)); signUpButton.setOnClickListener(v -> openUrl(url)); mLoggedIntoMyAccountView = getLayoutInflater().inflate(R.layout.my_account_logged_in, null); mUsernameLoggedIn = mLoggedIntoMyAccountView.findViewById(R.id.username_logged_in); Button logoutButton = mLoggedIntoMyAccountView.findViewById(R.id.logout_button); logoutButton.setOnClickListener(v -> logout()); }
Source:
public String makeValidTableName(String requestedName) { if ( StringHelper.isEmpty( requestedName ) ) { throw new org.hibernate.AssertionFailure( "qualifiedName is not expected to be null at this point" ); } else if ( requestedName.startsWith( "system." ) ) { throw log.collectionNameHasInvalidSystemPrefix( requestedName ); } else if ( requestedName.contains( "\u0000" ) ) { throw log.collectionNameContainsNULCharacter( requestedName ); } else if ( requestedName.contains( "$" ) ) { throw log.collectionNameContainsDollarCharacter( requestedName ); } return requestedName; }

Target:
public String makeValidTableName(String requestedName) { Contracts.assertStringParameterNotEmpty( requestedName, "requestedName" ); if ( requestedName.startsWith( "system." ) ) { throw log.collectionNameHasInvalidSystemPrefix( requestedName ); } else if ( requestedName.contains( "\u0000" ) ) { throw log.collectionNameContainsNULCharacter( requestedName ); } else if ( requestedName.contains( "$" ) ) { throw log.collectionNameContainsDollarCharacter( requestedName ); } return requestedName; }
Source:
public List<VDSGroup> getAllWithQuery(String query) { List<VDSGroup> groups = jdbcTemplate.query(query, VdsGroupRowMapper.instance); try { return getHostsAndVmsForClusters(groups); } catch (Exception e) { log.error("Can't load host and vm count for vds group for query " + query, e); } return groups; }

Target:
public List<VDSGroup> getAllWithQuery(String query) { List<VDSGroup> groups = jdbcTemplate.query(query, VdsGroupRowMapper.instance); try { return getHostsAndVmsForClusters(groups); } catch (Exception e) { log.error("Can't load host and vm count for cluster. Query is " + query, e); } return groups; }
Source:
public void testFileReadingAndWriting() throws IOException { String randomizedTestString = TEST_STRING + System.currentTimeMillis(); for (String ext : TEST_FILE_EXTENSIONS) { File f = File.createTempFile(TEST_FILE_PREFIX, ext); IOUtil.assertFileIsReadable(f); CodeUtil.applyIfNotNull(f,IOUtil::assertFileIsReadable); f.deleteOnExit(); OutputStream os = IOUtil.openFileForWriting(f); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write(randomizedTestString); writer.close(); InputStream is = IOUtil.openFileForReading(f); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = reader.readLine(); Assert.assertEquals(randomizedTestString, line); } }

Target:
public void testFileReadingAndWriting() throws IOException { String randomizedTestString = TEST_STRING + System.currentTimeMillis(); for (String ext : TEST_FILE_EXTENSIONS) { File f = File.createTempFile(TEST_FILE_PREFIX, ext); f.deleteOnExit(); OutputStream os = IOUtil.openFileForWriting(f); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write(randomizedTestString); writer.close(); InputStream is = IOUtil.openFileForReading(f); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = reader.readLine(); Assert.assertEquals(randomizedTestString, line); } }
Source:
public void close() { synchronized (lock) { if (!running) { return; } running = false; LOG.info("Closing {}.", this); leaderElectorRunFuture.complete(null); kubernetesWatch.close(); } }

Target:
public void close() { if (!running) { return; } running = false; LOG.info("Closing {}.", this); leaderElector.stop(); kubernetesWatch.close(); }
Source:
private ProcessOvfUpdateForStorageDomainCommandParameters createProcessOvfUpdateForDomainParams() { ProcessOvfUpdateForStorageDomainCommandParameters params = new ProcessOvfUpdateForStorageDomainCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId()); params.setSkipDomainChecks(getParameters().isSkipDomainChecks()); params.setParentCommand(getParameters().getParentCommand()); params.setSkipDomainChecks(getParameters().isSkipDomainChecks()); params.setParentParameters(getParameters().getParentParameters()); return params; }

Target:
private ProcessOvfUpdateForStorageDomainCommandParameters createProcessOvfUpdateForDomainParams() { ProcessOvfUpdateForStorageDomainCommandParameters params = new ProcessOvfUpdateForStorageDomainCommandParameters(getParameters().getStoragePoolId(), getParameters().getStorageDomainId()); params.setSkipDomainChecks(getParameters().isSkipDomainChecks()); params.setParentCommand(getParameters().getParentCommand()); params.setParentParameters(getParameters().getParentParameters()); return params; }
Source:
public void clear() throws CacheAccessException { try { map.clear(); currentUsageinBytes.set(0l); } catch (RuntimeException re) { handleRuntimeException(re); } }

Target:
public void clear() throws CacheAccessException { try { long current = currentUsageinBytes.get(); map.clear(); current = currentUsageinBytes.addAndGet(-current); if(current < 0L) { currentUsageinBytes.addAndGet(current); } } catch (RuntimeException re) { handleRuntimeException(re); } }
Source:
private void addBaseGroup(TargetEnvironment env) throws WdbaGlueException { SPSkyObject so = env.getPrimaryTargetFromAsterism(); if (so instanceof SPTarget) { final SPTarget spt = (SPTarget) so; if (isEmpty(spt.getName())) spt.setName(TccNames.BASE); add(new TargetConfig(spt, TccNames.BASE)); } if (so instanceof SPCoordinates) { add(new TargetConfig((SPCoordinates)so, TccNames.BASE)); } int pos = 1; for (UserTarget user : env.getUserTargets()) { final SPTarget t = user.target; if (isEmpty(t.getName())) { t.setName(TargetConfig.formatName("User", pos)); } ++pos; add(new TargetConfig(t, user.type.displayName)); } add(TargetGroupConfig.createBaseGroup(env)); }

Target:
private void addBaseGroup(TargetEnvironment env) throws WdbaGlueException { final SPSkyObject so = env.getSlewPositionObjectFromAsterism(); if (so instanceof SPTarget) { final SPTarget spt = (SPTarget) so; if (isEmpty(spt.getName())) spt.setName(TccNames.BASE); add(new TargetConfig(spt, TccNames.BASE)); } else if (so instanceof SPCoordinates) { add(new TargetConfig((SPCoordinates)so, TccNames.BASE)); } int pos = 1; for (UserTarget user : env.getUserTargets()) { final SPTarget t = user.target; if (isEmpty(t.getName())) { t.setName(TargetConfig.formatName("User", pos)); } ++pos; add(new TargetConfig(t, user.type.displayName)); } add(TargetGroupConfig.createBaseGroup(env)); }
Source:
public void visitNode(Tree tree) { if (tree.is(Tree.Kind.TRY_STATEMENT)) { withinTry.push((TryStatementTree) tree); } else if (withinStandardTry() && ((NewClassTree) tree).symbolType().isSubtypeOf("java.lang.AutoCloseable") && !reported.contains(withinTry.peek())) { reported.add(withinTry.peek()); reportIssue(withinTry.peek().tryKeyword(), "Change this \"try\" to a try-with-resources." + context.getJavaVersion().java7CompatibilityMessage()); } }

Target:
public void visitNode(Tree tree) { if (tree.is(Tree.Kind.TRY_STATEMENT)) { withinTry.push((TryStatementTree) tree); toReport.push(new ArrayList<Tree>()); } else if (withinStandardTryWithFinally() && ((NewClassTree) tree).symbolType().isSubtypeOf("java.lang.AutoCloseable")) { toReport.peek().add(tree); } }
Source:
public Expr toExpr() { return new DoubleExpr(value == null ? null : (value).doubleValue()); }

Target:
public Expr toExpr() { return new DoubleExpr(value == null ? null : value.doubleValue()); }
Source:
public Response findStaffMemberAddress(@PathParam("STAFFMEMBERID") Long staffMemberId, @PathParam("ID") Long id) { StaffMember staffMember = userController.findStaffMemberById(staffMemberId); if (staffMember == null) { return Response.status(Status.NOT_FOUND).build(); } if (staffMember.getArchived()) { return Response.status(Status.NOT_FOUND).build(); } if (!restSecurity.hasPermission(new String[] { UserPermissions.LIST_STAFFMEMBERADDRESES }, staffMember ) && !restSecurity.hasPermission(new String[] { PersonPermissions.PERSON_OWNER }, staffMember.getPerson() )) { return Response.status(Status.FORBIDDEN).build(); } Address address = commonController.findAddressById(id); if (address == null) { return Response.status(Status.NOT_FOUND).build(); } if (!address.getContactInfo().getId().equals(staffMember.getContactInfo().getId())) { return Response.status(Status.NOT_FOUND).build(); } return Response.ok(objectFactory.createModel(address)).build(); }

Target:
public Response findStaffMemberAddress(@PathParam("STAFFMEMBERID") Long staffMemberId, @PathParam("ID") Long id) { StaffMember staffMember = userController.findStaffMemberById(staffMemberId); if (staffMember == null) { return Response.status(Status.NOT_FOUND).build(); } if (staffMember.getArchived()) { return Response.status(Status.NOT_FOUND).build(); } if (!restSecurity.hasPermission(new String[] { UserPermissions.FIND_STAFFMEMBERADDRESS }, staffMember ) && !restSecurity.hasPermission(new String[] { PersonPermissions.PERSON_OWNER }, staffMember.getPerson() )) { return Response.status(Status.FORBIDDEN).build(); } Address address = commonController.findAddressById(id); if (address == null) { return Response.status(Status.NOT_FOUND).build(); } if (!address.getContactInfo().getId().equals(staffMember.getContactInfo().getId())) { return Response.status(Status.NOT_FOUND).build(); } return Response.ok(objectFactory.createModel(address)).build(); }
Source:
public void addChild(Group parent, Group child, boolean broadcast) throws Exception { if (log.isTraceEnabled()) { Tools.logMethodIn( log, LogLevel.TRACE, "addChild", new Object[]{ "parent", parent, "child", child, "broadcast", broadcast } ); } org.picketlink.idm.api.Group parentGroup = null; String childPLGroupName = getPLIDMGroupName(child.getGroupName()); if (parent != null) { String parentPLGroupName = getPLIDMGroupName(parent.getGroupName()); try { parentGroup = getIdentitySession().getPersistenceManager(). findGroup(parentPLGroupName, orgService.getConfiguration().getGroupType(parent.getParentId())); } catch (Exception e) { log.info("Cannot obtain group: " + parentPLGroupName, e); orgService.recoverFromIDMError(); } ((ExtGroup)child).setId(parent.getId() + "/" + child.getGroupName()); } else { ((ExtGroup)child).setId("/" + child.getGroupName()); } if (broadcast) { preSave(child, true); } if (parentGroup != null) { ((ExtGroup)child).setParentId(parent.getId()); } org.picketlink.idm.api.Group childGroup = persistGroup(child); try { if (parentGroup != null) { getIdentitySession().getRelationshipManager().associateGroups(parentGroup, childGroup); } else { getIdentitySession().getRelationshipManager().associateGroups(getRootGroup(), childGroup); } } catch (Exception e) { log.info("Cannot associate groups: ", e); orgService.recoverFromIDMError(); } if (broadcast) { postSave(child, true); } }

Target:
public void addChild(Group parent, Group child, boolean broadcast) throws Exception { if (log.isTraceEnabled()) { Tools.logMethodIn( log, LogLevel.TRACE, "addChild", new Object[]{ "parent", parent, "child", child, "broadcast", broadcast } ); } org.picketlink.idm.api.Group parentGroup = null; String childPLGroupName = getPLIDMGroupName(child.getGroupName()); if (parent != null) { String parentPLGroupName = getPLIDMGroupName(parent.getGroupName()); try { parentGroup = getIdentitySession().getPersistenceManager(). findGroup(parentPLGroupName, orgService.getConfiguration().getGroupType(parent.getParentId())); } catch (Exception e) { log.info("Cannot obtain group: " + parentPLGroupName, e); orgService.recoverFromIDMError(e); } ((ExtGroup)child).setId(parent.getId() + "/" + child.getGroupName()); } else { ((ExtGroup)child).setId("/" + child.getGroupName()); } if (broadcast) { preSave(child, true); } if (parentGroup != null) { ((ExtGroup)child).setParentId(parent.getId()); } org.picketlink.idm.api.Group childGroup = persistGroup(child); try { if (parentGroup != null) { getIdentitySession().getRelationshipManager().associateGroups(parentGroup, childGroup); } else { getIdentitySession().getRelationshipManager().associateGroups(getRootGroup(), childGroup); } } catch (Exception e) { log.info("Cannot associate groups: ", e); orgService.recoverFromIDMError(e); } if (broadcast) { postSave(child, true); } }
Source:
private void updateAnnotationModelForRemoves(IAnnotationModel annotationModel) { if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null); } else { for (Annotation fOccurrenceAnnotation : fOccurrenceAnnotations) { annotationModel.removeAnnotation(fOccurrenceAnnotation); } } fOccurrenceAnnotations = null; }

Target:
private void updateAnnotationModelForRemoves(IAnnotationModel annotationModel) { if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension) annotationModel).replaceAnnotations(fOccurrenceAnnotations, null); } else { for (Annotation annotation : fOccurrenceAnnotations) { annotationModel.removeAnnotation(annotation); } } fOccurrenceAnnotations = null; }
Source:
protected void runPipeline(final JavaSparkContext ctx) { if (! new HDF5Library().load(null)){ throw new UserException.HardwareFeatureException("Cannot load the required HDF5 library"); } final ReadCountCollection analysisReadCounts = composeAnalysisReadCounts(); final List<String> targetNames = analysisReadCounts.targets().stream().map(Target::getName).collect(Collectors.toList()); final List<String> sampleNames = analysisReadCounts.columnNames(); final double[][] counts = analysisReadCounts.counts().getData(); final PCA pca = PCA.createPCA(targetNames, sampleNames, new Array2DRowRealMatrix(counts), SVDFactory::createSVD); try (final HDF5File output = new HDF5File(outputFile, HDF5File.OpenMode.CREATE)) { PCA.writeHDF5(pca, output); } catch (final GATKException ex) { throw new UserException.CouldNotCreateOutputFile(outputFile, ex); } }

Target:
protected void runPipeline(final JavaSparkContext ctx) { if (! new HDF5Library().load(null)){ throw new UserException.HardwareFeatureException("Cannot load the required HDF5 library. " + "HDF5 is currently supported on x86-64 architecture and Linux or OSX systems."); } final ReadCountCollection analysisReadCounts = composeAnalysisReadCounts(); final List<String> targetNames = analysisReadCounts.targets().stream().map(Target::getName).collect(Collectors.toList()); final List<String> sampleNames = analysisReadCounts.columnNames(); final double[][] counts = analysisReadCounts.counts().getData(); final PCA pca = PCA.createPCA(targetNames, sampleNames, new Array2DRowRealMatrix(counts), SVDFactory::createSVD); try (final HDF5File output = new HDF5File(outputFile, HDF5File.OpenMode.CREATE)) { PCA.writeHDF5(pca, output); } catch (final GATKException ex) { throw new UserException.CouldNotCreateOutputFile(outputFile, ex); } }
Source:
private List<ColumnMetadata> loadColumns(ElasticsearchTableDescription table) { if (table.getColumns().isPresent()) { return buildMetadata(table.getColumns().get()); } List<ElasticsearchColumn> columns = buildColumns(table); return buildMetadata(columns); }

Target:
private List<ColumnMetadata> loadColumns(ElasticsearchTableDescription table) { if (table.getColumns().isPresent()) { return buildMetadata(table.getColumns().get()); } return buildMetadata(buildColumns(table)); }
Source:
public void channelRead( ChannelHandlerContext ctx, Object msg ) { ByteBuf buf = (ByteBuf) msg; try { assertEncryptedIfRequired(); handshakeBuffer.writeBytes( buf, Math.min( buf.readableBytes(), handshakeBuffer.writableBytes() ) ); if ( handshakeBuffer.writableBytes() == 0 ) { if ( verifyBoltPreamble() ) { if ( performHandshake() ) { ctx.writeAndFlush( ctx.alloc().buffer( 4 ).writeInt( (int)protocol.version() ) ); protocol.install(); ctx.pipeline().remove( this ); if ( buf.readableBytes() > 0 ) { ctx.fireChannelRead( buf.readRetainedSlice( buf.readableBytes() ) ); } } else { ctx.writeAndFlush( Unpooled.wrappedBuffer( new byte[]{0, 0, 0, 0} ) ).addListener( ChannelFutureListener.CLOSE ); } } else { ctx.close(); } } } finally { buf.release(); } }

Target:
public void channelRead( ChannelHandlerContext ctx, Object msg ) { ByteBuf buf = (ByteBuf) msg; try { assertEncryptedIfRequired(); handshakeBuffer.writeBytes( buf, Math.min( buf.readableBytes(), handshakeBuffer.writableBytes() ) ); if ( handshakeBuffer.writableBytes() == 0 ) { if ( verifyBoltPreamble() ) { if ( performHandshake() ) { ctx.writeAndFlush( ctx.alloc().buffer( 4 ).writeInt( (int)protocol.version() ) ); protocol.install(); ctx.pipeline().remove( this ); if ( buf.readableBytes() > 0 ) { ctx.fireChannelRead( buf.readRetainedSlice( buf.readableBytes() ) ); } } else { ctx.writeAndFlush( ctx.alloc().buffer().writeBytes( new byte[]{0, 0, 0, 0} ) ).addListener( ChannelFutureListener.CLOSE ); } } else { ctx.close(); } } } finally { buf.release(); } }
Source:
public void success(PageCombo pageCombo, Response response) { L.v(response.getUrl()); if (pageCombo.hasError()) { onError(); return; } final Page page = pageCombo.toPage(title); new SavePageTask(WikipediaApp.getInstance(), page.getTitle(), page).execute(); L.d("Downloaded page " + title.getDisplayText()); onComplete(); }

Target:
public void success(PageCombo pageCombo, Response response) { L.v(response.getUrl()); if (pageCombo.hasError()) { onError(); return; } final Page page = pageCombo.toPage(title); new SavePageTask(WikipediaApp.getInstance(), page.getTitle(), page) { @Override public void onFinish(Boolean result) { L.d("Downloaded page " + title.getDisplayText()); onComplete(); } }.execute(); }
Source:
public StructApi getPlatformStruct() { return new FakeStructApi( new ImmutableMap.Builder<String, Object>() .put("ios_device", "ios_device") .put("ios_simulator", "ios_simulator") .put("tvos_device", "tvos_device") .put("tvos_simulator", "tvos_simulator") .put("watchos_device", "watchos_device") .put("watchos_simulator", "watchos_simulator") .build()); }

Target:
public StructApi getPlatformStruct() { return new FakeStructApi( new ImmutableMap.Builder<String, Object>() .put("ios_device", "ios_device") .put("ios_simulator", "ios_simulator") .put("macos", "macos") .put("tvos_device", "tvos_device") .put("tvos_simulator", "tvos_simulator") .put("watchos_device", "watchos_device") .put("watchos_simulator", "watchos_simulator") .build()); }
Source:
private List<DiskImage> getAllDiskImagesInSrcAndDstToValidate() { List<DiskImage> allDiskImages = new ArrayList<>(); List<DiskImage> sourceImages = getSourceImages(); sourceImages.stream().map(DiskImage::getImageId).forEach(d -> allDiskImages.addAll(diskImageDao.getAllSnapshotsForParent(d))); allDiskImages.addAll(sourceImages); return allDiskImages; }

Target:
private List<DiskImage> getAllDiskImagesInSrcAndDstToValidate() { List<Guid> parentsIds = getSourceImages().stream().map(DiskImage::getImageId).collect(Collectors.toList()); List<DiskImage> allDiskImages = new ArrayList<>(diskImageDao.getAllSnapshotsForParents(parentsIds)); allDiskImages.addAll(getSourceImages()); return allDiskImages; }
Source:
public void builderShouldThrowsExceptionIfFileDoesntExists() throws Exception { thrown.expect(FileNotFoundException.class); thrown.expectMessage("File exists doesn't exists"); DownloadBuilder.of(new File("/path/that/doesnt/exists")).build(); }

Target:
public void builderShouldThrowsExceptionIfFileDoesntExists() throws Exception { thrown.expect(FileNotFoundException.class); thrown.expectMessage("File picture.jpg doesn't exists"); DownloadBuilder.of(new File("/path/that/doesnt/exists/picture.jpg")).build(); }
Source:
protected TaskResult run(TaskExecutionContext ctx, BqClient bq, String projectId) { List<BqOperation> operations = Stream.of( params.getListOrEmpty("delete_datasets", JsonNode.class).stream().map(this::deleteDataset), params.getListOrEmpty("empty_datasets", JsonNode.class).stream().map(this::emptyDataset), params.getListOrEmpty("create_datasets", JsonNode.class).stream().map(this::createDataset), params.getListOrEmpty("delete_tables", JsonNode.class).stream().map(this::deleteTable), params.getListOrEmpty("empty_tables", JsonNode.class).stream().map(this::emptyTable), params.getListOrEmpty("create_tables", JsonNode.class).stream().map(this::createTable)) .flatMap(s -> s) .collect(Collectors.toList()); int operation = state.params().get("operation", int.class, 0); for (int i = operation; i < operations.size(); i++) { state.params().set("operation", i); BqOperation o = operations.get(i); pollingRetryExecutor(state, "retry") .retryUnless(GoogleJsonResponseException.class, BqDdlOperatorFactory::isDeterministicException) .withErrorMessage("BiqQuery DDL operation failed") .runAction(s -> o.perform(bq, projectId)); } return TaskResult.empty(request); }

Target:
protected TaskResult run(TaskExecutionContext ctx, BqClient bq, String projectId) { List<BqOperation> operations = Stream.of( params.getListOrEmpty("delete_datasets", JsonNode.class).stream().map(this::deleteDataset), params.getListOrEmpty("empty_datasets", JsonNode.class).stream().map(this::emptyDataset), params.getListOrEmpty("create_datasets", JsonNode.class).stream().map(this::createDataset), params.getListOrEmpty("delete_tables", JsonNode.class).stream().map(this::deleteTable), params.getListOrEmpty("empty_tables", JsonNode.class).stream().map(this::emptyTable), params.getListOrEmpty("create_tables", JsonNode.class).stream().map(this::createTable)) .flatMap(s -> s) .collect(Collectors.toList()); int operation = state.params().get("operation", int.class, 0); for (int i = operation; i < operations.size(); i++) { state.params().set("operation", i); BqOperation o = operations.get(i); pollingRetryExecutor(state, "request") .retryUnless(GoogleJsonResponseException.class, BqDdlOperatorFactory::isDeterministicException) .withErrorMessage("BiqQuery DDL operation failed") .runAction(s -> o.perform(bq, projectId)); } return TaskResult.empty(request); }
Source:
public GeneMongoBean mapLine(String line, int lineNumber) throws Exception { String[] lineSplit = line.split("\t"); String[] attributesSplit = lineSplit[8].split(";"); Map<String, String> attributes = new TreeMap<>(); for (String attribute : attributesSplit) { String[] keyValue = attribute.split(" "); String value = keyValue[keyValue.length - 1]; String valueWithoutQuotes = value.substring(1, value.length() - 1); attributes.put(keyValue[keyValue.length - 2], valueWithoutQuotes); } return new GeneMongoBean(attributes.get("gene_id"), attributes.get("gene_name"), lineSplit[2], lineSplit[0], Integer.parseInt(lineSplit[3]), Integer.parseInt(lineSplit[4])); }

Target:
public FeatureCoordinates mapLine(String line, int lineNumber) throws Exception { String[] lineSplit = line.split("\t"); String[] attributesSplit = lineSplit[8].split(";"); Map<String, String> attributes = new TreeMap<>(); for (String attribute : attributesSplit) { String[] keyValue = attribute.split(" "); int valueLength = keyValue[keyValue.length - 1].length(); attributes.put(keyValue[keyValue.length - 2], keyValue[keyValue.length - 1].substring(1, valueLength - 1)); } String feature = lineSplit[2]; return new FeatureCoordinates(attributes.get(feature + "_id"), attributes.get(feature + "_name"), feature, lineSplit[0], Integer.parseInt(lineSplit[3]), Integer.parseInt(lineSplit[4])); }
Source:
public void start(final ServiceProvider serviceProvider) { final ManagementRegistryService managementRegistry = serviceProvider.getService(ManagementRegistryService.class); final EhcacheManager ehcacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); final Context cmContext = managementRegistry.getConfiguration().getContext(); ehcacheManager.registerListener(new CacheManagerListener() { @Override public void cacheAdded(String alias, Cache<?, ?> cache) { } @Override public void cacheRemoved(String alias, Cache<?, ?> cache) { } @Override @SuppressFBWarnings("SF_SWITCH_NO_DEFAULT") public void stateTransition(Status from, Status to) { switch (to) { case AVAILABLE: delegates.put(cmContext, managementRegistry); break; case UNINITIALIZED: delegates.remove(cmContext); ehcacheManager.deregisterListener(this); break; } } }); }

Target:
public void start(final ServiceProvider serviceProvider) { final ManagementRegistryService managementRegistry = serviceProvider.getService(ManagementRegistryService.class); final Context cmContext = managementRegistry.getConfiguration().getContext(); final EhcacheManager ehcacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); ehcacheManager.registerListener(new CacheManagerListener() { @Override public void cacheAdded(String alias, Cache<?, ?> cache) { } @Override public void cacheRemoved(String alias, Cache<?, ?> cache) { } @Override public void stateTransition(Status from, Status to) { switch (to) { case AVAILABLE: delegates.put(cmContext, managementRegistry); break; case UNINITIALIZED: delegates.remove(cmContext); ehcacheManager.deregisterListener(this); break; case MAINTENANCE: break; default: throw new AssertionError(to); } } }); }
Source:
private String copyProject(Long targetId, Long folderId) { SurveyGroup projectSource = surveyGroupDao.getByKey(targetId); SurveyGroup projectCopy = new SurveyGroup(); projectCopy.setCode(projectSource.getCode() + " copy"); projectCopy.setName(projectSource.getName() + " copy"); projectCopy.setMonitoringGroup(projectSource.getMonitoringGroup()); projectCopy.setParentId(folderId); SurveyGroup savedProjectCopy = surveyGroupDao.save(projectCopy); List<Survey> surveys = surveyDao.listSurveysByGroup(targetId); for (Survey survey : surveys) { SurveyDto surveyDto = new SurveyDto(); surveyDto.setCode(survey.getCode()); surveyDto.setName(survey.getName()); surveyDto.setSurveyGroupId(savedProjectCopy.getKey().getId()); Survey surveyCopy = SurveyUtils.copySurvey(survey, surveyDto); surveyCopy.setSurveyGroupId(savedProjectCopy.getKey().getId()); surveyDao.save(surveyCopy); } return "success"; }

Target:
private String copyProject(Long targetId, Long folderId) { SurveyGroup projectSource = surveyGroupDao.getByKey(targetId); if (projectSource == null) { logger.log(Level.WARNING, String.format("Failed to copy project %s to folder %s", targetId, folderId)); return "failed"; } SurveyGroup projectCopy = new SurveyGroup(); projectCopy.setCode(projectSource.getCode() + " copy"); projectCopy.setName(projectSource.getName() + " copy"); projectCopy.setMonitoringGroup(projectSource.getMonitoringGroup()); projectCopy.setParentId(folderId); SurveyGroup savedProjectCopy = surveyGroupDao.save(projectCopy); List<Survey> surveys = surveyDao.listSurveysByGroup(targetId); for (Survey survey : surveys) { SurveyDto surveyDto = new SurveyDto(); surveyDto.setCode(survey.getCode()); surveyDto.setName(survey.getName()); surveyDto.setSurveyGroupId(savedProjectCopy.getKey().getId()); Survey surveyCopy = SurveyUtils.copySurvey(survey, surveyDto); surveyCopy.setSurveyGroupId(savedProjectCopy.getKey().getId()); surveyDao.save(surveyCopy); } return "success"; }