auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public synchronized void close() { try { switch (state.type) { case ZERO: break; case NORMAL: if (log.isDebugEnabled()) { log.debug( "Closing connection pool: {}", UnsafeArg.of("connConfig", connConfig), new SafeRuntimeException("Closing connection pool")); } state.dataSourcePool.close(); break; case CLOSED: break; } } finally { state = new State(StateType.CLOSED, null, null, new Throwable("Hikari pool closed here")); } }

Target:
public synchronized void close() { try { switch (state.type) { case ZERO: break; case NORMAL: if (log.isDebugEnabled()) { log.debug( "Closing connection pool", UnsafeArg.of("connConfig", connConfig), new SafeRuntimeException("Closing connection pool")); } state.dataSourcePool.close(); break; case CLOSED: break; } } finally { state = new State(StateType.CLOSED, null, null, new Throwable("Hikari pool closed here")); } }
Source:
public void compactBuffer() { if (this.readPos >= BUFFER_COMPACT_THRESHOLD_KB * 1024) { try { this.bufferWriteMutex.acquire(); } catch(Exception e){} int remainingBytesInBuffer = this.readBufferLen.get() - this.readPos; this.readBufferLen.set(remainingBytesInBuffer); System.arraycopy(this.readBuffer,this.readPos,this.readBuffer,0,remainingBytesInBuffer); if (this.markPos >= 0) { this.markPos -= this.readPos; } this.readPos = 0; this.bufferWriteMutex.release(); } }

Target:
private void compactBuffer() { if (this.readPos >= this.bufferCompactThresholdKB * 1024) { try { this.bufferWriteMutex.acquire(); } catch(Exception e){} int remainingBytesInBuffer = this.readBufferLen.get() - this.readPos; this.readBufferLen.set(remainingBytesInBuffer); System.arraycopy(this.readBuffer,this.readPos,this.readBuffer,0,remainingBytesInBuffer); if (this.markPos >= 0) { this.markPos -= this.readPos; } this.readPos = 0; this.bufferWriteMutex.release(); } }
Source:
protected void setupChatRoom(ChatRoom mucRoom) { if (mucRoom instanceof ChatRoomJabberImpl) { if (this.displayName != null) { ((ChatRoomJabberImpl)mucRoom).addPresencePacketExtensions( new Nick(this.displayName)); } else { logger.error(this.callContext + " No display name to use..."); } String region = JigasiBundleActivator.getConfigurationService() .getString(LOCAL_REGION_PNAME); if(!StringUtils.isNullOrEmpty(region)) { RegionPacketExtension rpe = new RegionPacketExtension(); rpe.setRegionId(region); ((ChatRoomJabberImpl)mucRoom) .addPresencePacketExtensions(rpe); } ((ChatRoomJabberImpl)mucRoom) .addPresencePacketExtensions( new ColibriStatsExtension.Stat( ColibriStatsExtension.VERSION, CurrentVersionImpl.VERSION.getApplicationName() + " " + CurrentVersionImpl.VERSION)); AbstractPacketExtension initiator = new AbstractPacketExtension( SIP_GATEWAY_FEATURE_NAME, "initiator"){}; callContext.getExtraHeaders().forEach( (key, value) -> { HeaderExtension he = new HeaderExtension(); he.setName(key); he.setValue(value); initiator.addChildExtension(he); }); if (initiator.getChildExtensions().size() > 0) { ((ChatRoomJabberImpl)mucRoom) .addPresencePacketExtensions(initiator); } } }

Target:
void setupChatRoom(ChatRoom mucRoom) { if (mucRoom instanceof ChatRoomJabberImpl) { String displayName = this.sipGatewaySession.getMucDisplayName(); if (displayName != null) { ((ChatRoomJabberImpl)mucRoom).addPresencePacketExtensions( new Nick(displayName)); } else { logger.error(this.callContext + " No display name to use..."); } } }
Source:
private void testDeleteCommentsActionAfterEditingComments() throws IOException { ______TS("delete comments on responses and verify edited comments action"); submitPage = loginToInstructorEditStudentFeedbackPage( "IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.waitForPageToLoad(); submitPage.deleteFeedbackResponseComment("-3-0"); submitPage.verifyRowDeletedSuccess("-0-3-0"); }

Target:
private void testDeleteCommentsActionAfterEditingComments() { submitPage = loginToInstructorEditStudentFeedbackPage( "IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.waitForPageToLoad(); submitPage.deleteFeedbackResponseComment("-3-0"); submitPage.verifyCommentRowMissing("-0-3-0"); }
Source:
private Single<JsonObject> getDepictions(String filename) { return mediaClient.getCaptionAndDepictions(filename) .map(mediaResponse -> { return mediaResponse; }).doOnError(throwable -> { Timber.e(throwable+"eror while fetching captions"); }); }

Target:
private Single<JsonObject> getDepictions(String filename) { return mediaClient.getCaptionAndDepictions(filename) .map(mediaResponse -> { return mediaResponse; }).doOnError(throwable -> { Timber.e(throwable+ "error while fetching depictions"); }); }
Source:
public void non_looper_thread_commit_realmobject_async() { final Realm realm = looperThread.realm; realm.beginTransaction(); realm.createObject(Dog.class).setAge(0); realm.commitTransaction(); Dog dog = realm.where(Dog.class).findFirstAsync(); looperThread.keepStrongReference.add(dog); dog.addChangeListener(new RealmChangeListener<Dog>() { @Override public void onChange(Dog object) { typebasedCommitInvocations.incrementAndGet(); switch (typebasedCommitInvocations.get()) { case 1: assertEquals(0, object.getAge()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.where(Dog.class).findFirst().setAge(17); } }); break; case 2: assertEquals(17, object.getAge()); looperThread.testComplete(); break; default: fail(); } } }); }

Target:
public void non_looper_thread_commit_realmobject_async() { final Realm realm = looperThread.realm; realm.beginTransaction(); realm.createObject(Dog.class).setAge(1); realm.commitTransaction(); Dog dog = realm.where(Dog.class).findFirstAsync(); looperThread.keepStrongReference.add(dog); dog.addChangeListener(new RealmChangeListener<Dog>() { @Override public void onChange(Dog object) { switch (typebasedCommitInvocations.incrementAndGet()) { case 1: assertEquals(1, object.getAge()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.where(Dog.class).findFirst().setAge(17); } }); break; case 2: assertEquals(17, object.getAge()); looperThread.testComplete(); break; default: fail(); } } }); }
Source:
public Mono<AccessToken> getToken(TokenRequestContext request) { return Mono.fromSupplier(() -> { if (configuration.contains(Configuration.PROPERTY_AZURE_CLIENT_ID) && configuration.contains(Configuration.PROPERTY_AZURE_CLIENT_SECRET) && configuration.contains(Configuration.PROPERTY_AZURE_TENANT_ID)) { return new ClientSecretCredential(configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID), configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID), configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET), identityClientOptions); } else if (configuration.contains(Configuration.PROPERTY_AZURE_CLIENT_ID) && configuration.contains(Configuration.PROPERTY_AZURE_TENANT_ID) && configuration.contains(Configuration.PROPERTY_AZURE_CLIENT_CERTIFICATE_PATH)) { return new ClientCertificateCredential(configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID), configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID), configuration.get(Configuration.PROPERTY_AZURE_CLIENT_CERTIFICATE_PATH), null, identityClientOptions); } else if (configuration.contains(Configuration.PROPERTY_AZURE_USERNAME) && configuration.contains(Configuration.PROPERTY_AZURE_CLIENT_ID) && configuration.contains(Configuration.PROPERTY_AZURE_PASSWORD)) { return new UsernamePasswordCredential(configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID), configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID), configuration.get(Configuration.PROPERTY_AZURE_USERNAME), configuration.get(Configuration.PROPERTY_AZURE_PASSWORD), identityClientOptions); } throw logger.logExceptionAsError(new ClientAuthenticationException( "Cannot create any credentials with the current environment variables", null)); }).flatMap(cred -> cred.getToken(request)); }

Target:
public Mono<AccessToken> getToken(TokenRequestContext request) { String clientId = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID); String tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); String clientSecret = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_SECRET); String certPath = configuration.get(Configuration.PROPERTY_AZURE_CLIENT_CERTIFICATE_PATH); String username = configuration.get(Configuration.PROPERTY_AZURE_USERNAME); String password = configuration.get(Configuration.PROPERTY_AZURE_PASSWORD); return Mono.fromSupplier(() -> { if (verifyNotNull(clientId)) { if (verifyNotNull(tenantId, clientSecret)) { return new ClientSecretCredential(tenantId, clientId, clientSecret, identityClientOptions); } else if (verifyNotNull(tenantId, certPath)) { return new ClientCertificateCredential(tenantId, clientId, certPath, null, identityClientOptions); } else if (verifyNotNull(username, password)) { return new UsernamePasswordCredential(clientId, tenantId, username, password, identityClientOptions); } } throw logger.logExceptionAsError(new ClientAuthenticationException( "Cannot create any credentials with the current environment variables", null)); }).flatMap(cred -> cred.getToken(request)); }
Source:
public Change munge(String entityId, Collection<Statement> statements) { munge(entityId, statements, emptySet(), emptySet(), null, null); }

Target:
public Change munge(String entityId, Collection<Statement> statements) { return munge(entityId, statements, emptySet(), emptySet(), null, null); }
Source:
public void initializeEditorFragment() { if (mEditorFragment instanceof AztecEditorFragment) { AztecEditorFragment aztecEditorFragment = (AztecEditorFragment)mEditorFragment; aztecEditorFragment.setEditorImageSettingsListener(EditPostActivity.this); aztecEditorFragment.setMediaToolbarButtonClickListener(EditPostActivity.this); Drawable loadingImagePlaceholder = EditorMediaUtils.getAztecPlaceholderDrawableFromResID( this, org.wordpress.android.editor.R.drawable.ic_gridicons_image, aztecEditorFragment.getMaxMediaSize() ); aztecEditorFragment.setAztecImageLoader(new AztecImageLoader(getBaseContext(), loadingImagePlaceholder)); aztecEditorFragment.setLoadingImagePlaceholder(loadingImagePlaceholder); Drawable loadingVideoPlaceholder = EditorMediaUtils.getAztecPlaceholderDrawableFromResID( this, org.wordpress.android.editor.R.drawable.ic_gridicons_video_camera, aztecEditorFragment.getMaxMediaSize() ); aztecEditorFragment.setAztecVideoLoader(new AztecVideoLoader(getBaseContext(), loadingVideoPlaceholder)); aztecEditorFragment.setLoadingVideoPlaceholder(loadingVideoPlaceholder); if (getSite() != null && getSite().isWPCom() && !getSite().isPrivate()) { aztecEditorFragment.enableContentLogOnCrashes( new AztecExceptionHandler.ExceptionHandlerHelper() { @Override public boolean shouldLog(Throwable throwable) { return getPost() != null && TextUtils.isEmpty(getPost().getPassword()) && !"private".equals(getPost().getStatus()); } } ); } } }

Target:
public void initializeEditorFragment() { if (mEditorFragment instanceof AztecEditorFragment) { AztecEditorFragment aztecEditorFragment = (AztecEditorFragment)mEditorFragment; aztecEditorFragment.setEditorImageSettingsListener(EditPostActivity.this); aztecEditorFragment.setMediaToolbarButtonClickListener(EditPostActivity.this); Drawable loadingImagePlaceholder = EditorMediaUtils.getAztecPlaceholderDrawableFromResID( this, org.wordpress.android.editor.R.drawable.ic_gridicons_image, aztecEditorFragment.getMaxMediaSize() ); aztecEditorFragment.setAztecImageLoader(new AztecImageLoader(getBaseContext(), loadingImagePlaceholder)); aztecEditorFragment.setLoadingImagePlaceholder(loadingImagePlaceholder); Drawable loadingVideoPlaceholder = EditorMediaUtils.getAztecPlaceholderDrawableFromResID( this, org.wordpress.android.editor.R.drawable.ic_gridicons_video_camera, aztecEditorFragment.getMaxMediaSize() ); aztecEditorFragment.setAztecVideoLoader(new AztecVideoLoader(getBaseContext(), loadingVideoPlaceholder)); aztecEditorFragment.setLoadingVideoPlaceholder(loadingVideoPlaceholder); if (getSite() != null && getSite().isWPCom() && !getSite().isPrivate()) { aztecEditorFragment.enableContentLogOnCrashes( new AztecExceptionHandler.ExceptionHandlerHelper() { @Override public boolean shouldLog(Throwable throwable) { return getPost() != null && TextUtils.isEmpty(getPost().getPassword()) && !PostStatus.PRIVATE.toString().equals(getPost().getStatus()); } } ); } } }
Source:
public static ITmfStateValue queryRangeMax(ITmfStateSystem ss, long t1, long t2, int quark) throws AttributeNotFoundException, TimeRangeException { ITmfStateValue max = TmfStateValue.nullValue(); try { List<ITmfStateInterval> intervals = queryAttributeRange(ss, t1, t2, quark, AbstractTmfMipmapStateProvider.MAX_STRING); if (intervals.size() == 0) { return TmfStateValue.nullValue(); } for (ITmfStateInterval si : intervals) { ITmfStateValue value = si.getStateValue(); switch (value.getType()) { case DOUBLE: if (max.isNull() || si.getStateValue().unboxDouble() > max.unboxDouble()) { max = si.getStateValue(); } break; case INTEGER: case LONG: if (max.isNull() || si.getStateValue().unboxLong() > max.unboxLong()) { max = si.getStateValue(); } break; case NULL: case STRING: default: Activator.logError(unsupOperationMsg(value, "Max")); break; } } } catch (StateValueTypeException e) { throw new IllegalStateException(); } return max; }

Target:
public static ITmfStateValue queryRangeMax(ITmfStateSystem ss, long t1, long t2, int quark) throws AttributeNotFoundException, TimeRangeException, StateValueTypeException { ITmfStateValue max = TmfStateValue.nullValue(); List<ITmfStateInterval> intervals = queryAttributeRange(ss, t1, t2, quark, AbstractTmfMipmapStateProvider.MAX_STRING); if (intervals.size() == 0) { return TmfStateValue.nullValue(); } for (ITmfStateInterval si : intervals) { ITmfStateValue value = si.getStateValue(); switch (value.getType()) { case DOUBLE: if (max.isNull() || si.getStateValue().unboxDouble() > max.unboxDouble()) { max = si.getStateValue(); } break; case INTEGER: case LONG: if (max.isNull() || si.getStateValue().unboxLong() > max.unboxLong()) { max = si.getStateValue(); } break; case NULL: case STRING: default: throw new StateValueTypeException(); } } return max; }
Source:
public ApplicationModule() { final AsyncCallback<List<String>> callback = new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable caught) { Layout.getInstance().setWarningMessage("Unable to load applet gatelab classes:<br />" + caught.getMessage()); } @Override public void onSuccess(List<String> result) { reservedGateClasses=result; } }; ApplicationService.Util.getInstance().getAppletGateLabClasses(callback); final AsyncCallback<List<String>> callbackTest = new AsyncCallback<List<String>>() { @Override public void onFailure(Throwable caught) { Layout.getInstance().setWarningMessage("Unable to load applet gatelab classes:<br />" + caught.getMessage()); } @Override public void onSuccess(List<String> result) { reservedTestClasses=result; } }; ApplicationService.Util.getInstance().getAppletGateLabTestClasses(callbackTest); }

Target:
public ApplicationModule() { final AsyncCallback<HashMap<String, Integer>> callback = new AsyncCallback<HashMap<String, Integer>>() { @Override public void onFailure(Throwable caught) { Layout.getInstance().setWarningMessage("Unable to load applet gatelab classes:<br />" + caught.getMessage()); } @Override public void onSuccess(HashMap<String, Integer> result) { reservedClasses=result; } }; ApplicationService.Util.getInstance().getReservedClasses(callback); }
Source:
private ObjectId bumpTerm(Repository git, ObjectInserter inserter) throws IOException { long newTerm; CommitBuilder b = new CommitBuilder(); if (!ObjectId.zeroId().equals(acceptedOld)) { try (RevWalk rw = new RevWalk(git)) { RevCommit c = rw.parseCommit(acceptedOld); b.setTreeId(c.getTree()); b.setParentId(acceptedOld); newTerm = parseTerm(c.getFooterLines(TERM)) + 1; } } else { newTerm = 1; b.setTreeId(inserter.insert(new TreeFormatter())); } StringBuilder msg = new StringBuilder(); msg.append(KetchConstants.TERM.getName()) .append(": ") .append(newTerm); String tag = leader.getSystem().newLeaderTag(); if (tag != null && !tag.isEmpty()) { msg.append(' ').append(tag); } b.setAuthor(leader.getSystem().newCommitter()); b.setCommitter(b.getAuthor()); b.setMessage(msg.toString()); if (log.isDebugEnabled()) { log.debug("Trying to elect myself " + b.getMessage()); } term = newTerm; return inserter.insert(b); }

Target:
private ObjectId bumpTerm(Repository git, ObjectInserter inserter) throws IOException { CommitBuilder b = new CommitBuilder(); if (!ObjectId.zeroId().equals(acceptedOldIndex)) { try (RevWalk rw = new RevWalk(git)) { RevCommit c = rw.parseCommit(acceptedOldIndex); b.setTreeId(c.getTree()); b.setParentId(acceptedOldIndex); term = parseTerm(c.getFooterLines(TERM)) + 1; } } else { term = 1; b.setTreeId(inserter.insert(new TreeFormatter())); } StringBuilder msg = new StringBuilder(); msg.append(KetchConstants.TERM.getName()) .append(": ") .append(term); String tag = leader.getSystem().newLeaderTag(); if (tag != null && !tag.isEmpty()) { msg.append(' ').append(tag); } b.setAuthor(leader.getSystem().newCommitter()); b.setCommitter(b.getAuthor()); b.setMessage(msg.toString()); if (log.isDebugEnabled()) { log.debug("Trying to elect myself " + b.getMessage()); } return inserter.insert(b); }
Source:
public Sequence<T> run( final Query<T> query, final Map<String, Object> responseContext ) { QueryMetrics<? super Query<T>> queryMetrics = queryToolChest.makeMetrics(query); Query<T> queryWithMetrics = query.withQueryMetrics(queryMetrics); final Sequence<T> baseSequence = delegate.run(queryWithMetrics, responseContext); return Sequences.wrap( baseSequence, new SequenceWrapper() { @Override public <RetType> RetType wrap(Supplier<RetType> sequenceProcessing) { final long start = VMUtils.getCurrentThreadCpuTime(); try { return sequenceProcessing.get(); } finally { cpuTimeAccumulator.addAndGet(VMUtils.getCurrentThreadCpuTime() - start); } } @Override public void after(boolean isDone, Throwable thrown) throws Exception { if (report) { final long cpuTimeNs = cpuTimeAccumulator.get(); if (cpuTimeNs > 0) { queryMetrics.reportCpuTime(cpuTimeNs).emit(emitter); } } } } ); }

Target:
public Sequence<T> run(final Query<T> query, final Map<String, Object> responseContext) { final Sequence<T> baseSequence = delegate.run(query, responseContext); return Sequences.wrap( baseSequence, new SequenceWrapper() { @Override public <RetType> RetType wrap(Supplier<RetType> sequenceProcessing) { final long start = VMUtils.getCurrentThreadCpuTime(); try { return sequenceProcessing.get(); } finally { cpuTimeAccumulator.addAndGet(VMUtils.getCurrentThreadCpuTime() - start); } } @Override public void after(boolean isDone, Throwable thrown) throws Exception { if (report) { final long cpuTimeNs = cpuTimeAccumulator.get(); if (cpuTimeNs > 0) { queryToolChest.makeMetrics(query).reportCpuTime(cpuTimeNs).emit(emitter); } } } } ); }
Source:
public void testProcessInstanceResume_noParams() throws Exception { try{ bundles[0].setProcessPeriodicity(5, TimeUnit.minutes); bundles[0].setOutputFeedPeriodicity(5, TimeUnit.minutes); bundles[0].setProcessConcurrency(6); bundles[0].submitAndScheduleBundle(prism); Thread.sleep(15000); ProcessInstancesResult r = prism.getProcessHelper().getProcessInstanceResume( Util.readEntityName(bundles[0].getProcessData()), ""); InstanceUtil.validateSuccessWithStatusCode(r, ResponseKeys.UNPARSEABLE_DATE); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Expected BEGIN_OBJECT but was STRING at line 1 column")); } }

Target:
public void testProcessInstanceResume_noParams() throws Exception { bundles[0].setProcessPeriodicity(5, TimeUnit.minutes); bundles[0].setOutputFeedPeriodicity(5, TimeUnit.minutes); bundles[0].setProcessConcurrency(6); bundles[0].submitAndScheduleBundle(prism); Thread.sleep(15000); ProcessInstancesResult r = prism.getProcessHelper().getProcessInstanceResume( Util.readEntityName(bundles[0].getProcessData()), null); InstanceUtil.validateSuccessWithStatusCode(r, ResponseKeys.UNPARSEABLE_DATE); }
Source:
public Translation getTranslation() { return translation; }

Target:
public Translation getTranslation() { if (this.translation == null) { String args = new ItemStack((Item) getItemType()).getDisplayName(); int end = "stat.".length() + this.statId.substring("stat.".length()).indexOf('.'); this.translation = new SpongeTranslation(this.statId.substring(0, end), args); } return this.translation; }
Source:
public int read(byte[] b, int off, int len) throws IOException { validateParameters(b, off, len); if (len == 0) { return 0; } if (!subscribed) { blockForData(); } if (this.buffer == null) { if (this.lastError != null) { throw lastError; } if (this.fluxComplete) { return -1; } this.buffer = new ByteArrayInputStream(new byte[0]); } if (this.buffer.available() == 0) { if (this.fluxComplete) { return -1; } if (!waitingForData) { blockForData(); } } if (this.buffer.available() > 0) { return this.buffer.read(b, off, len); } if (this.fluxComplete) { return -1; } return 0; }

Target:
public int read(byte[] b, int off, int len) throws IOException { validateParameters(b, off, len); if (len == 0) { return 0; } if (!subscribed) { blockForData(); } if (this.buffer == null) { if (this.lastError != null) { throw lastError; } if (this.fluxComplete) { return -1; } this.buffer = new ByteArrayInputStream(new byte[0]); } if (this.buffer.available() == 0) { if (this.fluxComplete) { return -1; } blockForData(); } if (this.buffer.available() > 0) { return this.buffer.read(b, off, len); } if (this.fluxComplete) { return -1; } else { throw new IllegalStateException("An unexpected error occurred. No data was read from the stream but the " + "stream did not indicate completion."); } }
Source:
public String toString() { return "AggregateCount{" + "name='" + name + '\'' + ", interval=" + interval + ", counts=" + Arrays.toString(counts) + ", resolution=" + resolution + '}'; }

Target:
public String toString() { return "AggregateCount{" + "name='" + name + "', interval=" + interval + ", counts=" + Arrays.toString(counts) + ", resolution=" + resolution + '}'; }
Source:
public <T> T execute(SessionCallback<F, T> callback) { Session<F> session = null; try { session = this.sessionFactory.getSession(); Assert.notNull(session, "failed to acquire a Session"); return callback.doInSession(session); } catch (Exception e) { if (session instanceof CachedSession) { ((CachedSession) session).dirty(); } throw new MessagingException("Failed to execute on session", e); } finally { if (session != null) { try { session.close(); } catch (Exception ignored) { if (logger.isDebugEnabled()) { logger.debug("failed to close Session", ignored); } } } } }

Target:
public <T> T execute(SessionCallback<F, T> callback) { Session<F> session = null; try { session = this.sessionFactory.getSession(); Assert.notNull(session, "failed to acquire a Session"); return callback.doInSession(session); } catch (Exception e) { if (session instanceof CachingSessionFactory<?>.CachedSession) { ((CachingSessionFactory<?>.CachedSession) session).dirty(); } if (e instanceof MessagingException) { throw (MessagingException) e; } throw new MessagingException("Failed to execute on session", e); } finally { if (session != null) { try { session.close(); } catch (Exception ignored) { if (logger.isDebugEnabled()) { logger.debug("failed to close Session", ignored); } } } } }
Source:
private void changeValue(boolean newState) { if (fIsSelected != newState) { fIsSelected= newState; if (fAttachedDialogFields != null) { boolean focusSet= false; for (DialogField fAttachedDialogField : fAttachedDialogFields) { fAttachedDialogField.setEnabled(fIsSelected); if (fIsSelected && !focusSet) { focusSet= fAttachedDialogField.setFocus(); } } } dialogFieldChanged(); } else if (fButtonStyle == SWT.PUSH) { dialogFieldChanged(); } }

Target:
private void changeValue(boolean newState) { if (fIsSelected != newState) { fIsSelected= newState; if (fAttachedDialogFields != null) { boolean focusSet= false; for (DialogField dialogField : fAttachedDialogFields) { dialogField.setEnabled(fIsSelected); if (fIsSelected && !focusSet) { focusSet= dialogField.setFocus(); } } } dialogFieldChanged(); } else if (fButtonStyle == SWT.PUSH) { dialogFieldChanged(); } }
Source:
private void initializeEnvironment() throws MojoExecutionException { if (server != null) { Server serverObject = this.settings.getServer(server); if (serverObject == null) { getLog().error("Server [" + server + "] not found in settings file."); throw new MojoExecutionException("Server [" + server + "] not found in settings file."); } if (StringUtils.isNotEmpty(username) || StringUtils.isNotEmpty(password)) { getLog().warn("Both server and credentials are configured. Using settings.xml server configuration."); } username = serverObject.getUsername(); password = serverObject.getPassword(); } }

Target:
private void initializeEnvironment() throws MojoExecutionException { if (server != null) { Server serverObject = this.settings.getServer(server); if (serverObject == null) { getLog().error("Server [" + server + "] not found in settings file."); throw new MojoExecutionException("Server [" + server + "] not found in settings file."); } serverObject = decrypter.decrypt(new DefaultSettingsDecryptionRequest(serverObject)).getServer(); if (StringUtils.isNotEmpty(username) || StringUtils.isNotEmpty(password)) { getLog().warn("Both server and credentials are configured. Using plugin configuration credentials."); } else { username = serverObject.getUsername(); password = serverObject.getPassword(); } } }
Source:
public void matchShouldReturnAddressesWhenSpecifiedExceptionHasOccurred() throws MessagingException { mockedMail.setAttribute(Mail.MAILET_ERROR_ATTRIBUTE_NAME, new javax.mail.internet.AddressException()); FakeMatcherConfig mci = FakeMatcherConfig.builder() .matcherName("HasException") .condition("javax.mail.internet.AddressException") .build(); matcher.init(mci); assertThat(matcher.match(mockedMail)).containsAll(mockedMail.getRecipients()); }

Target:
public void matchShouldReturnAddressesWhenSpecifiedExceptionHasOccurred() throws MessagingException { mockedMail.setAttribute(Mail.MAILET_ERROR_ATTRIBUTE_NAME, new javax.mail.internet.AddressException()); FakeMatcherConfig matcherConfig = FakeMatcherConfig.builder() .matcherName("HasException") .condition("javax.mail.internet.AddressException") .build(); testee.init(matcherConfig); assertThat(testee.match(mockedMail)).containsExactlyElementsOf(mockedMail.getRecipients()); }
Source:
public void notify(TranscriptionResult result) { if(!result.isInterim()) { ArrayList<TranslationResult> translations = getTranslations(result); for (TranslationResultListener listener : listeners) { for (TranslationResult translation : translations) listener.notify(translation); } } }

Target:
public void notify(TranscriptionResult result) { if(!result.isInterim()) { List<TranslationResult> translations = getTranslations(result); Iterable<TranslationResultListener> translationResultListeners; synchronized (listeners) { translationResultListeners = new ArrayList<>(listeners); } translationResultListeners.forEach( listener -> translations.forEach(listener::notify)); } }
Source:
private List<StorageServerConnections> getConnections() { List<StorageServerConnections> connectionsList = new ArrayList<>(); for (int i = 0; i == NUMBER_OF_EXISTING_CONNECTIONS; i++) { StorageServerConnections conn = new StorageServerConnections(); conn.setId(Guid.newGuid().toString()); connectionsList.add(conn); } return connectionsList; }

Target:
private List<StorageServerConnections> getConnections() { List<StorageServerConnections> connectionsList = new ArrayList<>(); for (int i = 0; i <= NUMBER_OF_EXISTING_CONNECTIONS; i++) { StorageServerConnections conn = new StorageServerConnections(); conn.setId(Guid.newGuid().toString()); connectionsList.add(conn); } return connectionsList; }
Source:
public static SemanticVersion parseParquetVersion(String createdBy) { if (Strings.isNullOrEmpty(createdBy)) { warnIfNeed("Ignoring statistics because created_by is null or empty! See PARQUET-251 and PARQUET-297"); return null; } else { try { VersionParser.ParsedVersion version = VersionParser.parse(createdBy); if (!"parquet-mr".equals(version.application)) { return null; } else if (Strings.isNullOrEmpty(version.version)) { warnIfNeed("Ignoring statistics because created_by did not contain a semver (see PARQUET-251): " + createdBy); return null; } return SemanticVersion.parse(version.version); } catch (RuntimeException | SemanticVersion.SemanticVersionParseException | VersionParser.VersionParseException ex) { warnParseErrorOnce(createdBy, ex); return null; } } }

Target:
private static Optional<SemanticVersion> parseParquetVersion(String createdBy) { if (Strings.isNullOrEmpty(createdBy)) { return Optional.empty(); } try { VersionParser.ParsedVersion version = VersionParser.parse(createdBy); if (!"parquet-mr".equals(version.application)) { return Optional.empty(); } if (Strings.isNullOrEmpty(version.version)) { return Optional.empty(); } return Optional.of(SemanticVersion.parse(version.version)); } catch (SemanticVersion.SemanticVersionParseException | VersionParser.VersionParseException ex) { return Optional.empty(); } }
Source:
public static void main(String[] args) { System.out.println(">>> Starting cluster."); try (Ignite ignite = Ignition.start("examples/config/encryption/example-encrypted-store.xml")) { ignite.active(true); CacheConfiguration<Long, BankAccount> ccfg = new CacheConfiguration<>("encrypted-cache"); ccfg.setEncryptionEnabled(true); System.out.println(">>> Creating encrypted cache."); IgniteCache<Long, BankAccount> cache = ignite.createCache(ccfg); System.out.println(">>> Populating cache with data."); cache.put(1L, new BankAccount("Rich account", 1_000_000L)); cache.put(2L, new BankAccount("Middle account", 1_000L)); cache.put(3L, new BankAccount("One dollar account", 1L)); } System.out.println(">>> Starting cluster again."); try (Ignite ignite = Ignition.start("examples/config/encryption/example-encrypted-store.xml")) { ignite.active(true); IgniteCache<Long, BankAccount> cache = ignite.getOrCreateCache("encrypted-cache"); QueryCursor<Cache.Entry<Long, BankAccount>> cursor = cache.query(new ScanQuery<>()); System.out.println(">>> Saved data:"); for (Cache.Entry<Long, BankAccount> entry : cursor) { System.out.println(">>> ID = " + entry.getKey() + ", AccountName = " + entry.getValue().accountName + ", Balance = " + entry.getValue().balance); } } }

Target:
public static void main(String[] args) { System.out.println(">>> Starting cluster."); try (Ignite ignite = Ignition.start("examples/config/encryption/example-encrypted-store.xml")) { ignite.cluster().active(true); CacheConfiguration<Long, BankAccount> ccfg = new CacheConfiguration<>("encrypted-cache"); ccfg.setEncryptionEnabled(true); System.out.println(">>> Creating encrypted cache."); IgniteCache<Long, BankAccount> cache = ignite.createCache(ccfg); System.out.println(">>> Populating cache with data."); cache.put(1L, new BankAccount("Rich account", 1_000_000L)); cache.put(2L, new BankAccount("Middle account", 1_000L)); cache.put(3L, new BankAccount("One dollar account", 1L)); } System.out.println(">>> Starting cluster again."); try (Ignite ignite = Ignition.start("examples/config/encryption/example-encrypted-store.xml")) { ignite.cluster().active(true); IgniteCache<Long, BankAccount> cache = ignite.getOrCreateCache("encrypted-cache"); QueryCursor<Cache.Entry<Long, BankAccount>> cursor = cache.query(new ScanQuery<>()); System.out.println(">>> Saved data:"); for (Cache.Entry<Long, BankAccount> entry : cursor) { System.out.println(">>> ID = " + entry.getKey() + ", AccountName = " + entry.getValue().accountName + ", Balance = " + entry.getValue().balance); } } }
Source:
protected boolean validateSpaceRequirements() { int numOfVms = getParameters().getVmsCount(); List<DiskImage> disksList = new ArrayList<>(); for (int i = 0; i < numOfVms; ++i) { disksList.addAll(diskInfoDestinationMap.values()); } for (DiskImage diskImage : disksList) { diskImage.setVolumeType(VolumeType.Sparse); if (getDiskStorageDomain(diskImage).getStorageType().isBlockDomain()) { diskImage.setvolumeFormat(VolumeFormat.COW); } else { diskImage.setvolumeFormat(VolumeFormat.RAW); } } Guid spId = getVmTemplate().getStoragePoolId(); Set<Guid> sdIds = destStorages.keySet(); MultipleStorageDomainsValidator storageDomainsValidator = getStorageDomainsValidator(spId, sdIds); return validate(storageDomainsValidator.allDomainsWithinThresholds()) && validate(storageDomainsValidator.allDomainsHaveSpaceForNewDisks(disksList)); }

Target:
protected boolean validateSpaceRequirements() { int numOfVms = getParameters().getVmsCount(); List<DiskImage> disksList = getDiskList(); for (int i = 0; i < numOfVms; ++i) { disksList.addAll(diskInfoDestinationMap.values()); } Guid spId = getVmTemplate().getStoragePoolId(); Set<Guid> sdIds = destStorages.keySet(); MultipleStorageDomainsValidator storageDomainsValidator = getStorageDomainsValidator(spId, sdIds); return validate(storageDomainsValidator.allDomainsWithinThresholds()) && validate(storageDomainsValidator.allDomainsHaveSpaceForNewDisks(disksList)); }
Source:
public static void share(Context ctx, News news) { ctx.startActivity(Intent.createChooser(getPumpkinShareIntent(ctx, news), ctx.getResources().getString(R.string.share))); }

Target:
public static void share(Context ctx, News news) { ctx.startActivity(Intent.createChooser(getPumpkinShareIntent(news), ctx.getResources().getString(R.string.share))); }
Source:
public long getGlobalClassLoaderId() { return (long) ClassLoaderIdentifier.GLOBAL_ID; }

Target:
public long getGlobalClassLoaderId() { return ClassLoaderIdentifier.GLOBAL_ID; }
Source:
public MobileArticlePageObject openTOCPage(String wikiURL){ getUrl(wikiURL+wikiTOC); waitForElementByElement(tocWrapper); PageObjectLogging.log("openTOC", "TOC page was opened", true, driver); return new MobileArticlePageObject(driver); }

Target:
public MobileArticlePageObject openTOCPage(String wikiURL){ getUrl(wikiURL + wikiTOC); waitForElementByElement(tocWrapper); PageObjectLogging.log("openTOCPage", "TOC page was opened", true, driver); return new MobileArticlePageObject(driver); }
Source:
void initTableOverhead() { disksViewRadioGroup = new DisksViewRadioGroup(); disksViewRadioGroup.setClickHandler(clickHandler); disksContentTypeRadioGroup = new DisksContentTypeRadioGroup(); disksContentTypeRadioGroup.setClickHandler(event -> { if (((RadioButton) event.getSource()).getValue()) { getMainModel().getDiskContentType().setEntity(disksContentTypeRadioGroup.getDiskContentType()); } }); HorizontalPanel overheadPanel = new HorizontalPanel(); overheadPanel.add(disksViewRadioGroup); overheadPanel.add(disksContentTypeRadioGroup); getTable().setTableOverhead(overheadPanel); }

Target:
void initTableOverhead() { disksViewRadioGroup = new DisksViewRadioGroup(); disksViewRadioGroup.addChangeHandler(diskViewTypeChange); disksContentTypeRadioGroup = new DisksContentTypeRadioGroup(); disksContentTypeRadioGroup.addChangeHandler(diskContentViewTypeChange); FlowPanel overheadPanel = new FlowPanel(); overheadPanel.add(disksViewRadioGroup); overheadPanel.add(disksContentTypeRadioGroup); getTable().setTableOverhead(overheadPanel); }
Source:
public GuiWrongMinecraft(WrongMinecraftVersionException wrongMC) { super(); this.wrongMC = wrongMC; }

Target:
public GuiWrongMinecraft(WrongMinecraftVersionException wrongMC) { this.wrongMC = wrongMC; }
Source:
public void put(final int numAlleles, final int ploidy, final int numLikelihoods) { if(numAlleles < N_ALLELES && ploidy < PLOIDY) { staticCache[numAlleles][ploidy] = numLikelihoods; } else{ final HashMap<Integer, Integer> cache = dynamicCache.containsKey(ploidy) ? dynamicCache.get(ploidy) : new HashMap<>(); if(cache.isEmpty()){ dynamicCache.put(ploidy, cache); } cache.put(numAlleles, numLikelihoods); } }

Target:
private synchronized void put(final int numAlleles, final int ploidy, final int numLikelihoods) { dynamicCache.put(new CacheKey(numAlleles, ploidy), numLikelihoods); }
Source:
public Guid getVdsForConnectStorage() { vdsId = getParameters().getVdsId(); if (vdsId == null) { List<VDS> hosts = getDbFacade().getVdsDao().getAllForStoragePoolAndStatus(getParameters().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { vdsId = hosts.get(new Random().nextInt(hosts.size())).getId(); log.info("vds id '{}' was chosen to fetch the Storage domain info", vdsId); } else { log.warn("There is no available vds in UP state to fetch the Storage domain info from VDSM"); } } return vdsId; }

Target:
private Guid getVdsForConnectStorage() { vdsId = getParameters().getVdsId(); if (vdsId == null) { List<VDS> hosts = getDbFacade().getVdsDao().getAllForStoragePoolAndStatus(getParameters().getId(), VDSStatus.Up); if (!hosts.isEmpty()) { vdsId = hosts.get(new Random().nextInt(hosts.size())).getId(); log.info("vds id '{}' was chosen to fetch the Storage domain info", vdsId); } else { log.warn("There is no available vds in UP state to fetch the Storage domain info from VDSM"); } } return vdsId; }
Source:
public String getBindingType() { return "upb"; }

Target:
public String getBindingType() { return "UPB"; }
Source:
public void applyCSSProperty(Control control, String property, CSSValue value, String pseudo, CSSEngine engine) throws Exception { if (!isMruControlledByCSS()) { return; } boolean isMruVisible = (Boolean)engine.convert(value, Boolean.class, null); if (control instanceof CTabFolder) { CTabFolder folder = (CTabFolder) control; folder.setMRUVisible(isMruVisible); } }

Target:
public void applyCSSProperty(Control control, String property, CSSValue value, String pseudo, CSSEngine engine) throws Exception { if (!isMRUControlledByCSS()) { return; } boolean isMruVisible = (Boolean)engine.convert(value, Boolean.class, null); if (control instanceof CTabFolder) { CTabFolder folder = (CTabFolder) control; folder.setMRUVisible(isMruVisible); } }
Source:
private LongRunningOperationStatus toLongRunningOperationStatus(String operationStatus) { switch (operationStatus) { case "InProgress": return LongRunningOperationStatus.IN_PROGRESS; case "Success": return LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; case "Failed": return LongRunningOperationStatus.FAILED; default: return LongRunningOperationStatus.fromString("POLLING_FAILED", true); } }

Target:
private static LongRunningOperationStatus toLongRunningOperationStatus(String operationStatus) { switch (operationStatus) { case "inprogress": return LongRunningOperationStatus.IN_PROGRESS; case "succeeded": return LongRunningOperationStatus.SUCCESSFULLY_COMPLETED; case "failed": return LongRunningOperationStatus.FAILED; default: return LongRunningOperationStatus.fromString("POLLING_FAILED", true); } }
Source:
private void processPage() { chooserLogic = new ToolChooserLogic(serviceManager); xLinkMock = new XLinkMock(serviceUtils, authenticationContext); requestParameters = getRequestParametersAsAMap(); HttpServletRequest req = (HttpServletRequest) getRequest().getContainerRequest(); HttpServletResponse resp = (HttpServletResponse) getResponse().getContainerResponse(); setContextFromId(); try { checkIfXLinkIsValid(req); } catch (OpenXLinkException ex) { handleErrorResponse(ex.getMessage()); } if (checkForLocalSwitchingParameters()) { ModelDescription destinationModelClass = chooserLogic.getModelClassOfView(hostId, connectorId, viewId); triggerXLinkProcessing(destinationModelClass, connectorId, viewId); handleSuccessResponse(resp); return; } buildToolChooserPage(resp); }

Target:
private void processPage() { requestParameters = getRequestParametersAsAMap(); HttpServletRequest req = (HttpServletRequest) getRequest().getContainerRequest(); HttpServletResponse resp = (HttpServletResponse) getResponse().getContainerResponse(); setContextFromId(); try { checkIfXLinkIsValid(req); } catch (OpenXLinkException ex) { handleErrorResponse(ex.getMessage()); } if (checkForLocalSwitchingParameters()) { ModelDescription destinationModelClass = toolChooserLogic.getModelClassOfView(hostId, connectorId, viewId); triggerXLinkProcessing(destinationModelClass, connectorId, viewId); handleSuccessResponse(resp); return; } buildToolChooserPage(resp); }
Source:
private Operation<PromiseError> handleError(final String nameSpace) { return new Operation<PromiseError>() { @Override public void apply(PromiseError promiseError) throws OperationException { loader.hide(); notificationManager.showError(locale.deleteProjectFailed(nameSpace) + " " + promiseError.getMessage()); } }; }

Target:
private Operation<PromiseError> handleError(final String nameSpace) { return new Operation<PromiseError>() { @Override public void apply(PromiseError promiseError) throws OperationException { notificationManager.showError(locale.deleteProjectFailed(nameSpace) + " " + promiseError.getMessage()); } }; }
Source:
public Object doWork() { final ReadCountCollection inputCounts; try { inputCounts = ReadCountCollectionUtils.parse(inputFile); } catch (final IOException e) { throw new UserException.CouldNotReadInputFile(inputFile, "cannot reach or read the input target coverage file"); } final RealMatrix counts = inputCounts.counts(); final List<Target> targets = inputCounts.targets().stream() .map(t -> new Target(t.getName(), t.getInterval())).collect(Collectors.toList()); final List<String> columnNames = new ArrayList<>(inputCounts.columnNames()); final int[] targetSizes; if (weightByTargetSize) { try { targetSizes = targets.stream().mapToInt(t -> length(t)).toArray(); } catch (final IllegalStateException e) { throw new UserException.BadInput("Weighting by target size requested but input read counts lack target intervals."); } } else { targetSizes = new int[targets.size()]; Arrays.fill(targetSizes, 1); } final int totalTargetSize = Arrays.stream(targetSizes).sum(); final double[] sampleWeightedAverages = new double[counts.getColumnDimension()]; counts.walkInOptimizedOrder(new DefaultRealMatrixPreservingVisitor() { @Override public void visit(final int target, final int sample, final double coverage) { sampleWeightedAverages[sample] += targetSizes[target] * coverage / totalTargetSize; } }); counts.walkInOptimizedOrder(new DefaultRealMatrixChangingVisitor() { @Override public double visit(final int target, final int sample, final double coverage) { return coverage / sampleWeightedAverages[sample]; } }); final ReadCountCollection normalizedCounts = new ReadCountCollection(SetUniqueList.setUniqueList(targets), SetUniqueList.setUniqueList(columnNames), counts); try { ReadCountCollectionUtils.write(outputFile, normalizedCounts); } catch (final IOException e) { throw new UserException.CouldNotCreateOutputFile(outputFile, "cannot write to the given output file"); } return "SUCCESS"; }

Target:
public Object doWork() { final ReadCountCollection inputCounts; try { inputCounts = ReadCountCollectionUtils.parse(inputFile); } catch (final IOException e) { throw new UserException.CouldNotReadInputFile(inputFile, "cannot reach or read the input target coverage file"); } final ReadCountCollection normalizedCounts; try { normalizedCounts = inputCounts.normalizeByColumnAverages(weightByTargetSize); } catch (final IllegalArgumentException e) { throw new UserException.BadInput("Weighting by target size requested but input read normalizedCounts lack target intervals."); } try { ReadCountCollectionUtils.write(outputFile, normalizedCounts); } catch (final IOException e) { throw new UserException.CouldNotCreateOutputFile(outputFile, "cannot write to the given output file"); } return "SUCCESS"; }
Source:
public void getClustersTest() throws Exception { String lzfile = System.getProperty("lztestfile"); if(lzfile != null) { DFUFileDetailWrapper fileWrapper = wsdfuclient.getFileDetails(lzfile, null); assertTrue(fileWrapper.getClusters().size() >= 1); } }

Target:
public void getClustersTest() throws Exception { DFUFileDetailWrapper fileWrapper = wsdfuclient.getFileDetails(logicalfilename, null); Set<String> clusters = fileWrapper.getClusters(); assertTrue(clusters != null && !clusters.isEmpty()); assertTrue(clusters.stream().findFirst().isPresent()); }
Source:
private List<GridCacheSqlQuery> prepareMapQueryForSinglePartition(GridCacheTwoStepQuery qry, Object[] params) { boolean hasSubQries = false; for (GridCacheSqlQuery mapQry : qry.mapQueries()) hasSubQries |= mapQry.hasSubQueries(); GridCacheSqlQuery originalQry = new GridCacheSqlQuery(qry.originalSql()); if (!F.isEmpty(params)) { int[] paramIdxs = new int[params.length]; for (int i = 0; i < params.length; i++) paramIdxs[i] = i; originalQry.parameterIndexes(paramIdxs); } originalQry.partitioned(true); originalQry.hasSubQueries(hasSubQries); return Collections.singletonList(originalQry); }

Target:
private List<GridCacheSqlQuery> prepareMapQueryForSinglePartition(GridCacheTwoStepQuery qry, Object[] params) { boolean hasSubQries = false; for (GridCacheSqlQuery mapQry : qry.mapQueries()) { if (mapQry.hasSubQueries()) { hasSubQries = true; break; } } GridCacheSqlQuery originalQry = new GridCacheSqlQuery(qry.originalSql()); if (!F.isEmpty(params)) { int[] paramIdxs = new int[params.length]; for (int i = 0; i < params.length; i++) paramIdxs[i] = i; originalQry.parameterIndexes(paramIdxs); } originalQry.partitioned(true); originalQry.hasSubQueries(hasSubQries); return Collections.singletonList(originalQry); }
Source:
protected boolean doSend(Message<?> message, long timeout) { Assert.notNull(message, "'message' must not be null"); try { if (this.queue instanceof BlockingQueue) { BlockingQueue<Message<?>> blockingQueue = (BlockingQueue<Message<?>>) this.queue; if (timeout > 0) { return blockingQueue.offer(message, timeout, TimeUnit.MILLISECONDS); } if (timeout == 0) { return blockingQueue.offer(message); } blockingQueue.put(message); return true; } else { return this.queue.add(message); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } }

Target:
protected boolean doSend(Message<?> message, long timeout) { Assert.notNull(message, "'message' must not be null"); try { if (this.queue instanceof BlockingQueue) { BlockingQueue<Message<?>> blockingQueue = (BlockingQueue<Message<?>>) this.queue; if (timeout > 0) { return blockingQueue.offer(message, timeout, TimeUnit.MILLISECONDS); } if (timeout == 0) { return blockingQueue.offer(message); } blockingQueue.put(message); return true; } else { try { return this.queue.offer(message); } finally { this.queueSemaphore.release(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } }
Source:
public Response iscsiLogin(Action action) { validateParameters(action, "iscsi.address", "iscsi.target"); StorageServerConnections cnx = new StorageServerConnections(); IscsiDetails iscsiDetails = action.getIscsi(); cnx.setConnection(iscsiDetails.getAddress()); cnx.setIqn(iscsiDetails.getTarget()); cnx.setStorageType(StorageType.ISCSI); if (iscsiDetails.isSetPort()) { cnx.setPort(iscsiDetails.getPort().toString()); } else { cnx.setPort(DEFAULT_ISCSI_PORT); } if (iscsiDetails.isSetPortal()) { cnx.setPortal(iscsiDetails.getPortal().toString()); } if (iscsiDetails.isSetUsername()) { cnx.setUserName(iscsiDetails.getUsername()); } if (iscsiDetails.isSetPassword()) { cnx.setPassword(iscsiDetails.getPassword()); } StorageServerConnectionParametersBase connectionParms = new StorageServerConnectionParametersBase(cnx, guid, false); return doAction(ActionType.ConnectStorageToVds, connectionParms, action); }

Target:
public Response iscsiLogin(Action action) { validateParameters(action, "iscsi.address", "iscsi.target"); StorageServerConnections cnx = new StorageServerConnections(); IscsiDetails iscsiDetails = action.getIscsi(); cnx.setConnection(iscsiDetails.getAddress()); cnx.setIqn(iscsiDetails.getTarget()); cnx.setStorageType(StorageType.ISCSI); if (iscsiDetails.isSetPort()) { cnx.setPort(iscsiDetails.getPort().toString()); } else { cnx.setPort(DEFAULT_ISCSI_PORT); } if (iscsiDetails.isSetPortal()) { cnx.setPortal(iscsiDetails.getPortal()); } if (iscsiDetails.isSetUsername()) { cnx.setUserName(iscsiDetails.getUsername()); } if (iscsiDetails.isSetPassword()) { cnx.setPassword(iscsiDetails.getPassword()); } StorageServerConnectionParametersBase connectionParms = new StorageServerConnectionParametersBase(cnx, guid, false); return doAction(ActionType.ConnectStorageToVds, connectionParms, action); }