auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int readLimit(String client) { QosClientLimitsConfig qosClientLimitsConfig = config.get().clientLimits().getOrDefault(client, ImmutableQosClientLimitsConfig.builder().build()); return Ints.saturatedCast((long) getClientLimitMultiplier(qosClientLimitsConfig.clientPriority()) * qosClientLimitsConfig.limits().readBytesPerSecond()); }

Target:
public long readLimit(String client) { QosClientLimitsConfig qosClientLimitsConfig = qosClientConfigLoader.getConfigForClient(client); return (long) (clientLimitMultiplier.getClientLimitMultiplier(qosClientLimitsConfig.clientPriority()) * qosClientLimitsConfig.limits().readBytesPerSecond()); }
Source:
public void getObs_shouldGetADateObs() throws Exception { SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd"); MockHttpServletRequest req = request(RequestMethod.GET, getURI() + "/" + getUuid()); SimpleObject result = deserialize(handle(req)); Assert.assertNotNull(result); Util.log("Obs fetched (default)", result); Assert.assertEquals(Context.getObsService().getObsByUuid(getUuid()), PropertyUtils.getProperty(result, "uuid")); Assert.assertEquals(ConversionUtil.convertToRepresentation(ymd.parse("2008-08-14"), Representation.DEFAULT), PropertyUtils.getProperty(result, "value")); }

Target:
public void getObs_shouldGetADateObs() throws Exception { String uuid = "99b92980-db62-40cd-8bca-733357c48126"; SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd"); MockHttpServletRequest req = request(RequestMethod.GET, getURI() + "/" + uuid); SimpleObject result = deserialize(handle(req)); Assert.assertNotNull(result); Util.log("Obs fetched (default)", result); Assert.assertEquals(uuid, PropertyUtils.getProperty(result, "uuid")); Assert.assertEquals(ConversionUtil.convertToRepresentation(ymd.parse("2008-08-14"), Representation.DEFAULT), PropertyUtils.getProperty(result, "value")); }
Source:
public void onResume() { Log.d(TAG, "onResume()"); hideSystemUI(); settings.reload(); vibrantColor = 0; vibrantColorDark = 0; this.locked = settings.isUIlocked; removeCallbacks(backgroundChange); background_images[background_image_active].clearAnimation(); background_images[ (background_image_active + 1) % 2].clearAnimation(); load_files(); handler.postDelayed(backgroundChange, 15000 * settings.backgroundImageDuration); setScreenOrientation(settings.screenOrientation); initSidePanel(); bottomPanelLayout.setAlarmUseLongPress(settings.stopAlarmOnLongPress); bottomPanelLayout.setAlarmUseSingleTap(settings.stopAlarmOnTap); bottomPanelLayout.setShowAlarmsPersistently(settings.showAlarmsPersistently); bottomPanelLayout.setUseAlarmSwipeGesture(settings.useAlarmSwipeGesture); bottomPanelLayout.setup(); setupScreenAnimation(); lockUI(this.locked); clockLayoutContainer.post(initClockLayout); Utility.registerEventBus(this); broadcastReceiver = registerBroadcastReceiver(); initLightSensor(); if (settings.useAmbientNoiseDetection()){ soundmeter = new SoundMeter(isDebuggable); } else { soundmeter = null; } }

Target:
public void onResume() { Log.d(TAG, "onResume()"); hideSystemUI(); settings.reload(); vibrantColor = 0; vibrantColorDark = 0; this.locked = settings.isUIlocked; removeCallbacks(backgroundChange); background_images[0].clearAnimation(); background_images[0].setImageDrawable(bgblack); background_images[1].clearAnimation(); background_images[1].setImageDrawable(bgblack); lastAnimationTime = 0L; if (settings.getBackgroundMode() == Settings.BACKGROUND_SLIDESHOW) { loadBackgroundImageFiles(); handler.postDelayed(backgroundChange, 15000 * settings.backgroundImageDuration); } setScreenOrientation(settings.screenOrientation); initSidePanel(); bottomPanelLayout.setAlarmUseLongPress(settings.stopAlarmOnLongPress); bottomPanelLayout.setAlarmUseSingleTap(settings.stopAlarmOnTap); bottomPanelLayout.setShowAlarmsPersistently(settings.showAlarmsPersistently); bottomPanelLayout.setUseAlarmSwipeGesture(settings.useAlarmSwipeGesture); bottomPanelLayout.setup(); setupScreenAnimation(); lockUI(this.locked); clockLayoutContainer.post(initClockLayout); Utility.registerEventBus(this); broadcastReceiver = registerBroadcastReceiver(); initLightSensor(); if (settings.useAmbientNoiseDetection()){ soundmeter = new SoundMeter(isDebuggable); } else { soundmeter = null; } }
Source:
public void setEntity(EntityLocal entity) { super.setEntity(entity); setEntityLoadingConfig(); if (fromHardcodedProducers == null && producer == null) producer = entity; checkState(fromHardcodedProducers != null ^ producer != null, "must specify one of %s (%s) or %s (%s)", PRODUCER.getName(), producer, FROM_HARDCODED_PRODUCERS.getName(), fromHardcodedProducers); checkState(producer != null ? (Boolean.TRUE.equals(fromMembers) || Boolean.TRUE.equals(fromChildren)) : true, "when specifying producer, must specify at least one of fromMembers (%s) or fromChildren (%s)", fromMembers, fromChildren); if (fromHardcodedProducers != null) { for (Entity producer : Iterables.filter(fromHardcodedProducers, entityFilter)) { addProducerHardcoded(producer); } } if (Boolean.TRUE.equals(fromMembers)) { setEntityBeforeSubscribingProducerMemberEvents(entity); setEntitySubscribeProducerMemberEvents(); setEntityAfterSubscribingProducerMemberEvents(); } if (Boolean.TRUE.equals(fromChildren)) { setEntityBeforeSubscribingProducerChildrenEvents(); setEntitySubscribingProducerChildrenEvents(); setEntityAfterSubscribingProducerChildrenEvents(); } onUpdated(); }

Target:
public void setEntity(EntityLocal entity) { super.setEntity(entity); setEntityLoadingConfig(); if (fromHardcodedProducers == null && producer == null) producer = entity; checkState(fromHardcodedProducers != null ^ producer != null, "must specify one of %s (%s) or %s (%s)", PRODUCER.getName(), producer, FROM_HARDCODED_PRODUCERS.getName(), fromHardcodedProducers); checkState(producer == null || Boolean.TRUE.equals(fromMembers) || Boolean.TRUE.equals(fromChildren), "when specifying producer, must specify at least one of fromMembers (%s) or fromChildren (%s)", fromMembers, fromChildren); if (fromHardcodedProducers != null) { for (Entity producer : Iterables.filter(fromHardcodedProducers, entityFilter)) { addProducerHardcoded(producer); } } if (Boolean.TRUE.equals(fromMembers)) { setEntityBeforeSubscribingProducerMemberEvents(entity); setEntitySubscribeProducerMemberEvents(); setEntityAfterSubscribingProducerMemberEvents(); } if (Boolean.TRUE.equals(fromChildren)) { setEntityBeforeSubscribingProducerChildrenEvents(); setEntitySubscribingProducerChildrenEvents(); setEntityAfterSubscribingProducerChildrenEvents(); } onUpdated(); }
Source:
protected File getFile(HandlerRequest<EmptyRequestBody, FileMessageParameters> handlerRequest) { final String logDir = logFileLocation.logFile.getParent(); if (logFileLocation.logFile == null || StringUtils.isNullOrWhitespaceOnly(logFileLocation.logFile.getParent())) { throw new CompletionException(new RestHandlerException("Can not get JobManager log dir.", HttpResponseStatus.NOT_FOUND)); } String filename = handlerRequest.getPathParameter(LogFileNamePathParameter.class); return new File(logDir, filename); }

Target:
protected File getFile(HandlerRequest<EmptyRequestBody, FileMessageParameters> handlerRequest) { if (logDir == null) { return null; } String filename = handlerRequest.getPathParameter(LogFileNamePathParameter.class); return new File(logDir.getPath(), filename); }
Source:
protected void findAndProcess(final Annotation ann, final Object message) { try { httpsession.getCreationTime(); } catch (IllegalStateException ex) { httpsession = null; } catch (NullPointerException ex2) { httpsession = null; } try { final WebModules modules = WebModules.get(context); final WsFunction func = modules.find(this, ann); if(func == null) throw new Exception(Util.info(WS_MISSING_X, ann.toString())); else if(response != null) func.process(this, message); } catch(final RuntimeException ex) { throw ex; } catch(final Exception ex) { Util.debug(ex); throw new CloseException(StatusCode.ABNORMAL, ex.getMessage()); } }

Target:
protected void findAndProcess(final Annotation ann, final Object message) { try { if(httpsession != null) httpsession.getCreationTime(); } catch (IllegalStateException ex) { httpsession = null; } try { final WebModules modules = WebModules.get(context); final WsFunction func = modules.find(this, ann); if(func == null) throw new Exception(Util.info(WS_MISSING_X, ann)); else if(response != null) func.process(this, message); } catch(final RuntimeException ex) { throw ex; } catch(final Exception ex) { Util.debug(ex); throw new CloseException(StatusCode.ABNORMAL, ex.getMessage()); } }
Source:
public PrivateChannel subscribePrivate(final String channelName, final PrivateChannelEventListener listener, final String... eventNames) { throwExceptionIfNoAuthorizerHasBeenSet(); final PrivateChannelImpl channel = factory.newPrivateChannel(connection, channelName, pusherOptions.getAuthorizer()); channelManager.subscribeTo(channel, listener, eventNames); privateChannels.add(channel); return channel; }

Target:
public PrivateChannel subscribePrivate(final String channelName, final PrivateChannelEventListener listener, final String... eventNames) { throwExceptionIfNoAuthorizerHasBeenSet(); final PrivateChannelImpl channel = factory.newPrivateChannel(connection, channelName, pusherOptions.getAuthorizer()); channelManager.subscribeTo(channel, listener, eventNames); return channel; }
Source:
public void processElement(PipelineOptions po) { long timestampDiff = System.currentTimeMillis() - START_TIME; long minutes = (timestampDiff / 1000) / 60; int timeOffsetIndex = Math.toIntExact(minutes / KEY_VIZ_WINDOW_MINUTES); ReadDataOptions options = po.as(ReadDataOptions.class); long count = 0; List<RowRange> ranges = getRangesForTimeIndex(timeOffsetIndex, getNumRows(options)); if (ranges.size() == 0) { return; } try { Filter rangeFilters = new MultiRowRangeFilter(ranges); FilterList firstKeyFilterWithRanges = new FilterList(new FirstKeyOnlyFilter(), rangeFilters); Scan scan = new Scan() .addFamily(Bytes.toBytes(COLUMN_FAMILY)) .setFilter(firstKeyFilterWithRanges); Table table = getConnection().getTable(TableName.valueOf(options.getBigtableTableId())); ResultScanner imageData = table.getScanner(scan); for (Result row : imageData) { count++; } } catch (Exception e) { System.out.println("Error reading."); e.printStackTrace(); } System.out.printf("got %d rows\n", count); }

Target:
public void processElement(PipelineOptions po) { long timestampDiff = System.currentTimeMillis() - START_TIME; long minutes = (timestampDiff / 1000) / 60; int timeOffsetIndex = Math.toIntExact(minutes / KEY_VIZ_WINDOW_MINUTES); ReadDataOptions options = po.as(ReadDataOptions.class); long count = 0; List<RowRange> ranges = getRangesForTimeIndex(timeOffsetIndex, getNumRows(options)); if (ranges.size() == 0) { return; } try { Filter rangeFilters = new MultiRowRangeFilter(ranges); FilterList firstKeyFilterWithRanges = new FilterList( rangeFilters, new FirstKeyOnlyFilter(), new KeyOnlyFilter()); Scan scan = new Scan() .addFamily(Bytes.toBytes(COLUMN_FAMILY)) .setFilter(firstKeyFilterWithRanges); Table table = getConnection().getTable(TableName.valueOf(options.getBigtableTableId())); ResultScanner imageData = table.getScanner(scan); for (Result row : imageData) { count++; } } catch (Exception e) { System.out.println("Error reading."); e.printStackTrace(); } System.out.printf("got %d rows\n", count); }
Source:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { try { List<String> vomRoles = (List<String>) attribute.getValue(); for (String vomRole : vomRoles) { Matcher matcher = pattern.matcher(vomRole); if(!matcher.matches()) { throw new WrongAttributeValueException(attribute, "Bad resource vomsRoles value. It should not contain '<>&' characters."); } } } catch (ClassCastException e) { throw new WrongAttributeValueException(attribute, "Value should be a list of Strings."); } }

Target:
public void checkAttributeValue(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException { if(attribute.getValue() == null) { return; } try { List<String> vomRoles = (List<String>) attribute.getValue(); for (String vomRole : vomRoles) { Matcher matcher = pattern.matcher(vomRole); if(!matcher.matches()) { throw new WrongAttributeValueException(attribute, "Bad resource vomsRoles value. It should not contain '<>&' characters."); } } } catch (ClassCastException e) { throw new WrongAttributeValueException(attribute, "Value should be a list of Strings."); } }
Source:
public String toString() { return "InvocationId:" + Objects.toString(address, "local") + ":" + id; }

Target:
public String toString() { return "CommandInvocation:" + Objects.toString(address, "local") + ":" + id; }
Source:
public static HBaseMetadataService newInstance(Configuration hbaseConfig, SecurityContext securityContext, Subject subject, Component hbaseMaster, Collection<ComponentProcess> hbaseMasterProcesses) throws IOException, EntityNotFoundException { if (SecurityUtil.isKerberosAuthenticated(securityContext)) { UserGroupInformation.setConfiguration(hbaseConfig); final UserGroupInformation ugiFromSubject = UserGroupInformation.getUGIFromSubject(subject); final UserGroupInformation proxyUserForImpersonation = UserGroupInformation .createProxyUser(securityContext.getUserPrincipal().getName(), ugiFromSubject); final User user = User.create(proxyUserForImpersonation); return new HBaseMetadataService(ConnectionFactory.createConnection(hbaseConfig, user) .getAdmin(), securityContext, subject, user, hbaseMaster, hbaseMasterProcesses); } else { return new HBaseMetadataService(ConnectionFactory.createConnection(hbaseConfig).getAdmin(), null, null, null, hbaseMaster, hbaseMasterProcesses); } }

Target:
public static HBaseMetadataService newInstance(Configuration hbaseConfig, SecurityContext securityContext, Subject subject, Component hbaseMaster, Collection<ComponentProcess> hbaseMasterProcesses) throws IOException, EntityNotFoundException { if (SecurityUtil.isKerberosAuthenticated(securityContext)) { UserGroupInformation.setConfiguration(hbaseConfig); final UserGroupInformation ugiFromSubject = UserGroupInformation.getUGIFromSubject(subject); final UserGroupInformation proxyUserForImpersonation = UserGroupInformation .createProxyUser(securityContext.getUserPrincipal().getName(), ugiFromSubject); final User user = User.create(proxyUserForImpersonation); return new HBaseMetadataService(ConnectionFactory.createConnection(hbaseConfig, user) .getAdmin(), securityContext, subject, user, hbaseMaster, hbaseMasterProcesses); } else { return new HBaseMetadataService(ConnectionFactory.createConnection(hbaseConfig).getAdmin(), securityContext, subject, null, hbaseMaster, hbaseMasterProcesses); } }
Source:
public DeferredItem(Rectangle bounds, RGBAColor backgroundColor, RGBAColor foregroundColor, int alpha, int lineWidth) { fBounds = bounds; fLineWidth = lineWidth; fBgColor = backgroundColor == null ? null : RGBAUtil.fromRGBAColor(backgroundColor); if (fBgColor != null) { fBgColor.alpha = alpha; } fFgColor = foregroundColor == null ? null : RGBAUtil.fromRGBAColor(foregroundColor); }

Target:
public DeferredItem(Rectangle bounds, RGBAColor backgroundColor, RGBAColor foregroundColor, int alpha, int lineWidth) { fBounds = bounds; fLineWidth = lineWidth; if (backgroundColor == null) { fBgColor = OPAQUE; } else if (backgroundColor.getAlpha() != alpha) { fBgColor = new RGBAColor(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), alpha); } else { fBgColor = backgroundColor; } fFgColor = foregroundColor; }
Source:
public boolean getFlagDown() { if (flagdown == true) { return true; } else{ return false; } }

Target:
public boolean getFlagDown() { return this.flagdown; }
Source:
public String[] getServerIDs() { ArrayList<String> serverIDs = new ArrayList<String>(); SQLiteDatabase db = mContext.openOrCreateDatabase( DatabaseUtils.getDBName("base", category), Context.MODE_PRIVATE, null); try { Cursor cursor = db.rawQuery("select serverID from words", null); while (cursor.moveToNext()) { serverIDs.add(cursor.getString(0)); } return serverIDs.toArray(new String[0]); } catch (Exception e) { return serverIDs.toArray(new String[0]); } finally { db.close(); } }

Target:
public String[] getServerIDs() { ArrayList<String> serverIDs = new ArrayList<String>(); SQLiteDatabase db = mContext.openOrCreateDatabase( DatabaseUtils.getDBName("base", category), Context.MODE_PRIVATE, null); try { Cursor cursor = db.rawQuery("select serverID from words", null); while (cursor.moveToNext()) { serverIDs.add(cursor.getString(0)); } return serverIDs.toArray(new String[0]); } finally { db.close(); } }
Source:
private void addPairs(TaggedValuePointable tvp1) throws IOException, SystemException { op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); tvp1.getValue(op); op.getKeys(tvp1); if (tvp1.getTag() == ValueTag.XS_STRING_TAG) { addPair(tvp1); } else if (tvp1.getTag() == ValueTag.SEQUENCE_TAG) { tvp1.getValue(sp1); for (int j = 0; j < sp1.getEntryCount(); ++j) { key = ppool.takeOne(TaggedValuePointable.class); sp1.getEntry(j, tvp1); addPair(tvp1); } } }

Target:
private void addPairs(TaggedValuePointable tvp1) throws IOException, SystemException { ObjectPointable op = (ObjectPointable) ObjectPointable.FACTORY.createPointable(); tvp1.getValue(op); op.getKeys(tvp1); if (tvp1.getTag() == ValueTag.XS_STRING_TAG) { addPair(tvp1, op); } else if (tvp1.getTag() == ValueTag.SEQUENCE_TAG) { tvp1.getValue(sp1); for (int j = 0; j < sp1.getEntryCount(); ++j) { sp1.getEntry(j, tvp1); addPair(tvp1, op); } } }
Source:
public boolean notifyClientRequest(boolean keepAlive) { final long now = System.currentTimeMillis(); if (!getWebApp().getConfiguration().isTimerKeepAlive()) { final int tmout = getMaxInactiveInterval(); if (tmout >= 0 && (now - _tmLastReq) / 1000 > tmout) { invalidate(); return true; } } if (keepAlive) { _tmLastReq = now; } return false; }

Target:
public boolean notifyClientRequest(boolean keepAlive) { final long now = System.currentTimeMillis(); if (!getWebApp().getConfiguration().isTimerKeepAlive() || !keepAlive) { final int tmout = getMaxInactiveInterval(); if (tmout >= 0 && (now - _tmLastReq) / 1000 > tmout) { invalidate(); return true; } } if (keepAlive) { _tmLastReq = now; } return false; }
Source:
public int compile(final OutputStream out, final OutputStream errors, final String outputPath, final String toCompile, final String classpath) { return BatchCompiler.compile(new String[] { "-classpath", classpath, "-d", outputPath, "-source", "1.7", toCompile }, new PrintWriter(out), new PrintWriter(errors), new CompilationProgress() { @Override public void begin(final int remainingWork) { } @Override public void done() { } @Override public boolean isCanceled() { return false; } @Override public void setTaskName(final String name) { } @Override public void worked(final int workIncrement, final int remainingWork) { } }) ? 0 : -1; }

Target:
public int compile(final OutputStream out, final OutputStream errors, final String outputPath, final String toCompile, final String classpath) { return BatchCompiler.compile(new String[] { "-classpath", classpath, "-d", outputPath, "-source", "1.8", toCompile }, new PrintWriter(out), new PrintWriter(errors), new CompilationProgress() { @Override public void begin(final int remainingWork) { } @Override public void done() { } @Override public boolean isCanceled() { return false; } @Override public void setTaskName(final String name) { } @Override public void worked(final int workIncrement, final int remainingWork) { } }) ? 0 : -1; }
Source:
public synchronized void reqSent(Long requestId) { Long timestamp = System.currentTimeMillis(); requestSent.put(requestId, timestamp); }

Target:
public void reqSent(Long requestId) { synchronized (FastSyncManager.this) { Long timestamp = System.currentTimeMillis(); requestSent.put(requestId, timestamp); } }
Source:
public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: " + getHostId(); }

Target:
public String getEventDescription() { String eventDescription; if (getHostId() != null) { eventDescription = String.format("Attempting to migrate VM id: %s to host Id: %s", getVirtualMachineId(), getHostId()); } else if (getStoragePoolId() != null) { eventDescription = String.format("Attempting to migrate VM id: %s to storage pool Id: %s", getVirtualMachineId(), getStoragePoolId()); } else { eventDescription = String.format("Attempting to migrate VM id: %s", getVirtualMachineId()); } return eventDescription; }
Source:
public String getAnswerString() { String listString = answers.toString(); if (answers.get(0) == -1) { listString = "Invalid response"; return listString; } return listString.substring(1, listString.length()-1); }

Target:
public String getAnswerString() { String listString = answers.toString(); return listString.substring(1, listString.length()-1); }
Source:
public final Response getTerms(@QueryParam("start_index") final String startIndex, @QueryParam("limit") final String limit) { Map<Map.Entry<BooleanOperator, String>, List<String>> fieldsToMatch = Maps.newHashMap(); fieldsToMatch.put(immutableEntry(BooleanOperator.AND, TYPE_FIELDNAME), Collections.singletonList("glossaryTerm")); ResultsWrapper<ContentDTO> c; try { Integer resultsLimit = null; Integer startIndexOfResults = null; if (null != limit) { resultsLimit = Integer.parseInt(limit); } else { resultsLimit = DEFAULT_RESULTS_LIMIT; } if (null != startIndex) { startIndexOfResults = Integer.parseInt(startIndex); } else { startIndexOfResults = 0; } c = this.contentManager.findByFieldNames(this.contentIndex, fieldsToMatch, startIndexOfResults, resultsLimit); return Response.ok(c).build(); } catch (NumberFormatException e) { return new SegueErrorResponse(Status.BAD_REQUEST, "Unable to convert one of the integer parameters provided into numbers. " + "Params provided were: limit" + DEFAULT_RESULTS_LIMIT + " and startIndex " + 0, e).toResponse(); } catch (ContentManagerException e) { return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Content acquisition error.", e).toResponse(); } }

Target:
public final Response getTerms(@QueryParam("start_index") final String startIndex, @QueryParam("limit") final String limit) { Map<Map.Entry<BooleanOperator, String>, List<String>> fieldsToMatch = Maps.newHashMap(); fieldsToMatch.put(immutableEntry(BooleanOperator.AND, TYPE_FIELDNAME), Collections.singletonList("glossaryTerm")); ResultsWrapper<ContentDTO> c; try { Integer resultsLimit = null; Integer startIndexOfResults = null; if (null != limit) { resultsLimit = Integer.parseInt(limit); } else { resultsLimit = DEFAULT_RESULTS_LIMIT; } if (null != startIndex) { startIndexOfResults = Integer.parseInt(startIndex); } else { startIndexOfResults = 0; } c = this.contentManager.findByFieldNames(this.contentIndex, fieldsToMatch, startIndexOfResults, resultsLimit); } catch (ContentManagerException e) { return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Content acquisition error.", e).toResponse(); } EntityTag etag = new EntityTag(this.contentManager.getCurrentContentSHA().hashCode() + ""); return Response.ok(c).tag(etag).build(); }
Source:
public void testWithSideRatioNotTooSmall4D() { double[] from = new double[] {0, 0, 0, 0}; double[] to = new double[] {1, 1, 1, 1}; Envelope envelope = new Envelope( from, to ).withSideRatioNotTooSmall(); double[] expectedFrom = new double[] {0, 0, 0, 0}; double[] expectedTo = new double[] {1, 1, 1, 1}; assertArrayEquals( expectedFrom, envelope.min , 0); assertArrayEquals( expectedTo, envelope.max, 0 ); to = new double[] {100, 0.1, 12, 0.01}; Envelope envelope2 = new Envelope( from, to ).withSideRatioNotTooSmall(); double[] expectedTo2 = new double[] {100, 1, 12, 1}; assertArrayEquals( expectedFrom, envelope2.min , 0); assertArrayEquals( expectedTo2, envelope2.max, 0.00001 ); }

Target:
public void testWithSideRatioNotTooSmall4D() { double[] from = new double[] {0, 0, 0, 0}; double[] to = new double[] {1, 1, 1, 1}; Envelope envelope = new Envelope( from, to ).withSideRatioNotTooSmall(); double[] expectedFrom = new double[] {0, 0, 0, 0}; double[] expectedTo = new double[] {1, 1, 1, 1}; assertArrayEquals( expectedFrom, envelope.min , 0); assertArrayEquals( expectedTo, envelope.max, 0 ); final double bigValue = 107; final double smallValue = 0.00000000000000000123; to = new double[] {bigValue, smallValue, 12, smallValue * 0.1}; Envelope envelope2 = new Envelope( from, to ).withSideRatioNotTooSmall(); double[] expectedTo2 = new double[] {bigValue, bigValue / Envelope.MAXIMAL_ENVELOPE_SIDE_RATIO, 12, bigValue / Envelope.MAXIMAL_ENVELOPE_SIDE_RATIO}; assertArrayEquals( expectedFrom, envelope2.min , 0); assertArrayEquals( expectedTo2, envelope2.max, 0.00001 ); }
Source:
public int run() throws IOException { int b = in.read(); if (b != -1) { dOut.write(b); size++; return 1; } else { dOut.close(); LongObjectId loid = LongObjectId .fromRaw(dOut.getMessageDigest().digest()); Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } } else { FileUtils.mkdirs(mediaFile.getParent().toFile(), true); FileUtils.rename(tmpFile.toFile(), mediaFile.toFile()); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); out.close(); return -1; } }

Target:
public int run() throws IOException { try { int b = in.read(); if (b != -1) { dOut.write(b); size++; return 1; } else { dOut.close(); tmpOut.close(); LongObjectId loid = LongObjectId .fromRaw(dOut.getMessageDigest().digest()); Path mediaFile = lfsUtil.getMediaFile(loid); if (Files.isRegularFile(mediaFile)) { long fsSize = Files.size(mediaFile); if (fsSize != size) { throw new CorruptMediaFile(mediaFile, size, fsSize); } } else { FileUtils.mkdirs(mediaFile.getParent().toFile(), true); FileUtils.rename(tmpFile.toFile(), mediaFile.toFile()); } LfsPointer lfsPointer = new LfsPointer(loid, size); lfsPointer.encode(out); out.close(); return -1; } } catch (IOException e) { out.close(); dOut.close(); tmpOut.close(); throw e; } }
Source:
public List<Exception> getErrors() { List<Exception> errors = new ArrayList<Exception>(); if (causes == null) { return errors; } for (Throwable cause : causes) { if (cause instanceof Exception) { errors.add((Exception) cause); } } return errors; }

Target:
public List<Exception> getErrors() { List<Exception> errors = new ArrayList<Exception>(); if (causes == null) { return errors; } for (Throwable cause : causes) { if (cause instanceof Exception) { errors.add((Exception) cause); } else { errors.add(new Exception(cause)); } } return errors; }
Source:
public void onResume() { super.onResume(); disposable = remoteBackupsDataCache.restoreBackup(backupMetadata, overwrite) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(success -> { if (success != null && success) { Toast.makeText(getActivity(), R.string.toast_import_complete, Toast.LENGTH_LONG).show(); for (final Table table : database.getTables()) { table.clearCache(); } tripTableController.get(); getActivity().finishAffinity(); } else { Toast.makeText(getActivity(), getString(R.string.IMPORT_ERROR), Toast.LENGTH_LONG).show(); } }, throwable -> { analytics.record(new ErrorEvent(ImportRemoteBackupWorkerProgressDialogFragment.this, throwable)); if (throwable.getMessage().contains("More than five missing files")) { Toast.makeText(getActivity(), getString(R.string.IMPORT_MISSING_ERROR), Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), getString(R.string.IMPORT_ERROR), Toast.LENGTH_LONG).show(); } remoteBackupsDataCache.removeCachedRestoreBackupFor(backupMetadata); dismiss(); }, () -> { remoteBackupsDataCache.removeCachedRestoreBackupFor(backupMetadata); dismiss(); }); }

Target:
public void onResume() { super.onResume(); disposable = remoteBackupsDataCache.restoreBackup(backupMetadata, overwrite) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(success -> { if (success != null && success) { Toast.makeText(getActivity(), R.string.toast_import_complete, Toast.LENGTH_LONG).show(); for (final Table table : database.getTables()) { table.clearCache(); } tripTableController.get(); getActivity().finishAffinity(); } else { Toast.makeText(getActivity(), getString(R.string.IMPORT_ERROR), Toast.LENGTH_LONG).show(); } }, throwable -> { analytics.record(new ErrorEvent(ImportRemoteBackupWorkerProgressDialogFragment.this, throwable)); if (throwable instanceof MissingFilesException) { Toast.makeText(getActivity(), getString(R.string.IMPORT_MISSING_ERROR), Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), getString(R.string.IMPORT_ERROR), Toast.LENGTH_LONG).show(); } remoteBackupsDataCache.removeCachedRestoreBackupFor(backupMetadata); dismiss(); }, () -> { remoteBackupsDataCache.removeCachedRestoreBackupFor(backupMetadata); dismiss(); }); }
Source:
private static boolean objectsEqual(String object1, String object2) { if (object1 == null && object2 == null) { return true; } return object1.equals(object2); }

Target:
private static boolean objectsEqual(String object1, String object2) { return object1 != null ? object1.equals(object2) : object2 == null; }
Source:
public PluginInfo upsert(@Nonnull PluginInfo pluginInfo) { validate(pluginInfo); try { PluginInfo currentPluginInfo = repository.findById(pluginInfo.getId()); List<PluginInfo.Release> newReleases = new ArrayList<>(pluginInfo.getReleases()); List<PluginInfo.Release> oldReleases = new ArrayList<>(currentPluginInfo.getReleases()); new ArrayList<>(newReleases) .forEach( release -> { oldReleases.removeIf( oldRelease -> oldRelease.getVersion().equals(release.getVersion())); }); List<PluginInfo.Release> allReleases = new ArrayList<>(); Stream.of(oldReleases, newReleases).forEach(allReleases::addAll); pluginInfo.setReleases(allReleases); repository.update(pluginInfo.getId(), pluginInfo); return pluginInfo; } catch (NotFoundException e) { return repository.create(pluginInfo.getId(), pluginInfo); } }

Target:
public PluginInfo upsert(@Nonnull PluginInfo pluginInfo) { validate(pluginInfo); try { PluginInfo currentPluginInfo = repository.findById(pluginInfo.getId()); List<PluginInfo.Release> newReleases = new ArrayList<>(pluginInfo.getReleases()); List<PluginInfo.Release> oldReleases = new ArrayList<>(currentPluginInfo.getReleases()); newReleases.forEach( release -> { if (oldReleases.stream() .anyMatch(oldRelease -> oldRelease.getVersion().equals(release.getVersion()))) { throw new InvalidRequestException( "Cannot update an existing release: " + release.getVersion()); } }); List<PluginInfo.Release> allReleases = new ArrayList<>(); Stream.of(oldReleases, newReleases).forEach(allReleases::addAll); pluginInfo.setReleases(allReleases); repository.update(pluginInfo.getId(), pluginInfo); return pluginInfo; } catch (NotFoundException e) { return repository.create(pluginInfo.getId(), pluginInfo); } }
Source:
public void bulkScans(Blackhole blackhole) throws IOException { String rowPrefix = getRowPrefix(jobConfig.cellsPerRow, jobConfig.cellSize); Scan scan = new Scan().setMaxVersions(1).setRowPrefixFilter(Bytes.toBytes(rowPrefix)); ResultScanner resScanner = connection.getTable(jobConfig.tableName).getScanner(scan); for (Result result = resScanner.next(); result != null; result = resScanner.next()) { for (Cell cell : result.rawCells()) { blackhole.consume(cell); } } }

Target:
public void bulkScans(Blackhole blackhole) throws IOException { Scan scan = new Scan().setMaxVersions(1).setRowPrefixFilter(Bytes.toBytes(READ_ROW_PREFIX)); ResultScanner resScanner = table.getScanner(scan); for (Result result = resScanner.next(); result != null; result = resScanner.next()) { for (Cell cell : result.rawCells()) { blackhole.consume(cell); } } }
Source:
public void testBlockingLocalPartitionReleaseDoesNotBlockTaskExecutor() throws Exception { BlockerSync sync = new BlockerSync(); ResultPartitionManager blockingResultPartitionManager = new ResultPartitionManager() { @Override public void releasePartition(ResultPartitionID partitionId, Throwable cause) { sync.blockNonInterruptible(); super.releasePartition(partitionId, cause); } }; NettyShuffleEnvironment shuffleEnvironment = new NettyShuffleEnvironmentBuilder() .setResultPartitionManager(blockingResultPartitionManager) .setIoExecutor(java.util.concurrent.Executors.newFixedThreadPool(1)) .build(); final CompletableFuture<ResultPartitionID> startTrackingFuture = new CompletableFuture<>(); final TaskExecutorPartitionTracker partitionTracker = new TaskExecutorPartitionTrackerImpl(shuffleEnvironment) { @Override public void startTrackingPartition(JobID producingJobId, TaskExecutorPartitionInfo partitionInfo) { super.startTrackingPartition(producingJobId, partitionInfo); startTrackingFuture.complete(partitionInfo.getResultPartitionId()); } }; internalTestPartitionRelease( partitionTracker, shuffleEnvironment, startTrackingFuture, (jobId, resultPartitionDeploymentDescriptor, taskExecutor, taskExecutorGateway) -> { final IntermediateDataSetID dataSetId = resultPartitionDeploymentDescriptor.getResultId(); taskExecutorGateway.releaseClusterPartitions(Collections.singleton(dataSetId), timeout); taskExecutorGateway.canBeReleased().get(5, TimeUnit.SECONDS); } ); }

Target:
public void testBlockingLocalPartitionReleaseDoesNotBlockTaskExecutor() throws Exception { BlockerSync sync = new BlockerSync(); ResultPartitionManager blockingResultPartitionManager = new ResultPartitionManager() { @Override public void releasePartition(ResultPartitionID partitionId, Throwable cause) { sync.blockNonInterruptible(); super.releasePartition(partitionId, cause); } }; NettyShuffleEnvironment shuffleEnvironment = new NettyShuffleEnvironmentBuilder() .setResultPartitionManager(blockingResultPartitionManager) .setIoExecutor(TEST_EXECUTOR_SERVICE_RESOURCE.getExecutor()) .build(); final CompletableFuture<ResultPartitionID> startTrackingFuture = new CompletableFuture<>(); final TaskExecutorPartitionTracker partitionTracker = new TaskExecutorPartitionTrackerImpl(shuffleEnvironment) { @Override public void startTrackingPartition(JobID producingJobId, TaskExecutorPartitionInfo partitionInfo) { super.startTrackingPartition(producingJobId, partitionInfo); startTrackingFuture.complete(partitionInfo.getResultPartitionId()); } }; try { internalTestPartitionRelease( partitionTracker, shuffleEnvironment, startTrackingFuture, (jobId, resultPartitionDeploymentDescriptor, taskExecutor, taskExecutorGateway) -> { final IntermediateDataSetID dataSetId = resultPartitionDeploymentDescriptor.getResultId(); taskExecutorGateway.releaseClusterPartitions(Collections.singleton(dataSetId), timeout); taskExecutorGateway.canBeReleased().get(5, TimeUnit.SECONDS); } ); } finally { sync.releaseBlocker(); } }
Source:
public void testListing() throws DDFException { List<String> files = manager.listFiles("/usr"); LOG.info("========== files =========="); for (String file: files) { LOG.info(file); } }

Target:
public void testListing() throws DDFException { List<String> files = manager.listFiles("/test_pe"); assert (files.size() > 0); }
Source:
private static boolean isSetter(ASTMethodDeclaration node, Map<String, String> fieldNames) { if (node.getFirstDescendantOfType(ASTFormalParameters.class).jjtGetNumChildren() == 0) { return false; } List<ASTStatementExpression> statementExpressions = node.getBlock().findDescendantsOfType(ASTStatementExpression.class); Set<String> namesToCheck = new HashSet<>(); for (ASTStatementExpression st : statementExpressions) { ASTName name = st.getFirstDescendantOfType(ASTName.class); if (name == null) { ASTPrimaryExpression prim = st.getFirstChildOfType(ASTPrimaryExpression.class); ASTPrimaryPrefix prefix = prim.getFirstChildOfType(ASTPrimaryPrefix.class); if (prefix.usesThisModifier() || prefix.usesSuperModifier()) { namesToCheck.add(prim.getFirstChildOfType(ASTPrimarySuffix.class).getImage()); } else { namesToCheck.add(prefix.getImage().split("\\.")[0]); } } else { namesToCheck.add(name.getImage().split("\\.")[0]); } } for (String name : namesToCheck) { if (fieldNames.containsKey(name)) { return true; } } return false; }

Target:
private static boolean isSetter(ASTMethodDeclaration node, Map<String, String> fieldNames) { if (node.getFirstDescendantOfType(ASTFormalParameters.class).jjtGetNumChildren() != 1) { return false; } List<ASTStatementExpression> statementExpressions = node.getBlock().findDescendantsOfType(ASTStatementExpression.class); Set<String> namesToCheck = new HashSet<>(); for (ASTStatementExpression st : statementExpressions) { ASTName name = st.getFirstDescendantOfType(ASTName.class); if (name == null) { ASTPrimaryExpression prim = st.getFirstChildOfType(ASTPrimaryExpression.class); ASTPrimaryPrefix prefix = prim.getFirstChildOfType(ASTPrimaryPrefix.class); if (prefix.usesThisModifier() || prefix.usesSuperModifier()) { namesToCheck.add(prim.getFirstChildOfType(ASTPrimarySuffix.class).getImage()); } else { namesToCheck.add(prefix.getImage().split("\\.")[0]); } } else { namesToCheck.add(name.getImage().split("\\.")[0]); } } for (String name : namesToCheck) { if (fieldNames.containsKey(name)) { return true; } } return false; }
Source:
public void shouldRaiseAlertWhenSensitiveInfoInReferer() throws HttpMalformedHeaderException, URIException { String testReferer = "<LINK_0>"; HttpMessage msg = createHttpMessageWithRespBody(testReferer); rule.scanHttpRequestSend(msg, -1); assertEquals(1, alertsRaised.size()); }

Target:
public void shouldRaiseAlertWhenSensitiveInfoInReferer() throws HttpMalformedHeaderException, URIException { String sensitiveParamName = "passWord"; String sensitiveValue = "whatsup"; String testReferer = "<LINK_1>"; HttpMessage msg = createHttpMessageWithRespBody(testReferer); rule.scanHttpRequestSend(msg, -1); assertEquals(1, alertsRaised.size()); assertEquals(sensitiveParamName, alertsRaised.get(0).getEvidence()); assertEquals( Constant.messages.getString( InformationDisclosureReferrerScanner.MESSAGE_PREFIX + "otherinfo.sensitiveinfo"), alertsRaised.get(0).getOtherInfo()); }
Source:
public static Pair<Integer, Integer> getPrecisionAndScale(String type) { String param = type.substring(8, type.length() - 1); String[] params = param.split(","); return new Pair<>(Integer.parseInt(params[0].trim()), Integer.parseInt(params[1].trim())); }

Target:
public static Pair<Integer, Integer> getPrecisionAndScale(String type) { type = type.trim(); String param = type.substring(8, type.length() - 1); String[] params = param.split(","); return new Pair<>(Integer.parseInt(params[0].trim()), Integer.parseInt(params[1].trim())); }
Source:
public void putObjectWithSync() throws Exception { assumeThat(Util.getBlackPearlVersion(client), greaterThan(3.0)); final String bucketName = "test_put_object"; try { Util.createBucket(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "put_object", "-b", bucketName, "-o", Utils.getFileName(Paths.get("."), Paths.get(Util.RESOURCE_BASE_NAME + "beowulf.txt")), "--sync"}); CommandResponse response = Util.command(client, args); assertThat(response.getMessage(), is("Success: Finished syncing file to ds3 appliance.")); response = Util.command(client, args); assertThat(response.getMessage(), is("Success: No need to sync src/test/resources/books/beowulf.txt")); } finally { Util.deleteBucket(client, bucketName); } }

Target:
public void putObjectWithSync() throws Exception { assumeThat(Util.getBlackPearlVersion(client), greaterThan(1.2)); final String bucketName = "test_put_object"; try { Util.createBucket(client, bucketName); final Arguments args = new Arguments(new String[]{"--http", "-c", "put_object", "-b", bucketName, "-o", Utils.getFileName(Paths.get("."), Paths.get(Util.RESOURCE_BASE_NAME + "beowulf.txt")), "--sync"}); CommandResponse response = Util.command(client, args); assertThat(response.getMessage(), is("Success: Finished syncing file to ds3 appliance.")); response = Util.command(client, args); assertThat(response.getMessage(), is("Success: No need to sync src/test/resources/books/beowulf.txt")); } finally { Util.deleteBucket(client, bucketName); } }
Source:
public void pass_headers_Test() throws Exception { respondWith(JSON_USERS); KeystoneToken token = new KeystoneToken(); Map headersMap = new HashMap(); headersMap.put("X-Project-Name","admin"); headersMap.put("X-Project-Domain-Id","default"); Config config = Config.newConfig(); token.setEndpoint(authURL("/v3")); OSClient.OSClientV3 osClient = OSFactory.clientFromToken(token, config).headers(headersMap); osClient.identity().users().list(); RecordedRequest request = server.takeRequest(); System.out.println("request.getHeader(\"X-Project-Name\"):" + request.getHeader("X-Project-Name")); assertEquals("admin1111", request.getHeader("X-Project-Name")); assertEquals("default1111", request.getHeader("X-Project-Domain-Id")); }

Target:
public void pass_headers_Test() throws Exception { respondWith(JSON_USERS); Map header = new HashMap(); String key = "X-Domain-Id"; String value = "default"; header.put(key, value); KeystoneToken token = new KeystoneToken(); token.setEndpoint(authURL("/v3")); OSClient.OSClientV3 osClient = OSFactory.clientFromToken(token).headers(header); osClient.identity().users().list(); RecordedRequest request = server.takeRequest(); assertEquals(request.getHeader(key), value); }
Source:
private void activate() { for (ExtensionEntry entry : loadedEntries.values()) { entry.enabled = EngineLocalConfig.getInstance().getBoolean( "ENGINE_EXTENSION_ENABLE_" + entry.getName(), entry.enabled ); if (entry.enabled) { try { entry.extension = (Extension) lookupService( Extension.class, entry.getConfig().getProperty(CLASS), entry.getConfig().getProperty(MODULE) ).newInstance(); entry.extension.setContext(entry.context); entry.extension.init(); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (Exception ex) { log.error( String.format( "Error in activating extension %1$s. Exception message is %2$s", entry.getName(), ex.getMessage() ) ); if (log.isDebugEnabled()) { log.error("", ex); } } } } log.info("Activated extensions list: "); for (ExtensionEntry entry: loadedEntries.values()) { if (entry.extension != null) { log.info( String.format( "Name: %1$s Author %2$s Version %3$s Home: %4$s License: %5$s", emptyIfNull(entry.extension.getContext().get(ExtensionProperties.EXTENSION_NAME)), emptyIfNull(entry.extension.getContext().get(ExtensionProperties.AUTHOR)), emptyIfNull(entry.extension.getContext().get(ExtensionProperties.VERSION)), emptyIfNull(entry.extension.getContext().get(ExtensionProperties.HOME)), emptyIfNull(entry.extension.getContext().get(ExtensionProperties.LICENSE)) ) ); } } log.info("End of activated extensions list"); }

Target:
private void activate() { EngineLocalConfig config = EngineLocalConfig.getInstance(); for (ExtensionEntry entry : loadedEntries.values()) { entry.enabled = config.getBoolean(ENGINE_EXTENSION_ENABLED + entry.getName(), entry.enabled); if (entry.enabled) { try { entry.extension = (Extension) lookupService( Extension.class, entry.getConfig().getProperty(CLASS), entry.getConfig().getProperty(MODULE) ).newInstance(); entry.extension.setContext(entry.context); entry.extension.init(); activatedEntries.put(entry.getName(), entry); MultiValueMapUtils.addToMap(entry.getProvides(), entry, providesEntries); } catch (Exception ex) { log.error( String.format( "Error in activating extension %1$s. Exception message is %2$s", entry.getName(), ex.getMessage() ) ); if (log.isDebugEnabled()) { log.error("", ex); } } } } logEnabledExtensions(); }
Source:
public static String getLogFileName() { ApexRollingFileAppender apexAppender = (ApexRollingFileAppender)LogManager.getRootLogger().getAppender( APEX_APPENDER); return apexAppender == null ? null : apexAppender.getCurrentFileName(); }

Target:
public static String getLogFileName() { Appender appender = LogManager.getRootLogger().getAppender(APEX_APPENDER); if (appender != null && appender instanceof LogLocationProvider) { LogLocationProvider apexAppender = (LogLocationProvider)appender; return apexAppender.getCurrentFileName(); } return null; }
Source:
private Logger getLogger() { return LoggerFactory.getLogger(this.getClass()); }

Target:
private Logger getLogger() { return LoggerFactory.getLogger(FrontendAnnotatedClassVisitor.class); }
Source:
public boolean isCinderDomain() { return this == CINDER || this == MANAGED_BLOCK_STORAGE; }

Target:
public boolean isCinderDomain() { return this == CINDER; }
Source:
public void forceInsert_sameRevisionTwice() throws Exception { final String sql = "SELECT docs.docid, revid from revs join docs on revs.doc_id == docs.doc_id where docs.docid = ? and revs.revid = ? "; final DocumentRevision rev = createDbObject("1-rev", bodyOne); datastore.forceInsert(rev, "1-rev"); Assert.assertThat(datastore.getDocumentCount(), is(1)); try { datastore.forceInsert(rev, "1-rev"); } finally { datastore.runOnDbQueue(new SQLQueueCallable<Void>() { @Override public Void call(SQLDatabase db) throws Exception { Cursor cursor = null; try { cursor = db.rawQuery(sql, new String[]{rev.getId(), "1-rev"}); int resultscount = 0; while (cursor.moveToNext()) { resultscount++; } Assert.assertThat(resultscount, is(1)); } finally { DatabaseUtils.closeCursorQuietly(cursor); } return null; } }).get(); } }

Target:
public void forceInsert_sameRevisionTwice() throws Exception { DocumentRevision rev = createDbObject("1-rev", bodyOne); EventSubscriber eventSubscriber = new EventSubscriber(); datastore.getEventBus().register(eventSubscriber); datastore.forceInsert(rev, "1-rev"); Assert.assertThat(datastore.getDocumentCount(), is(1)); Assert.assertThat(eventSubscriber.eventCount, is(1)); datastore.forceInsert(rev, "1-rev"); }
Source:
public Association getAssociation(AssociationKey key, AssociationContext associationContext) { String table = key.getTable(); Table tableMetadata = provider.getMetaDataCache().get( key.getTable() ); List<Column> tablePKCols = (List<Column>) tableMetadata.getPrimaryKey().getColumns(); Select select = select().all().from( quote( key.getTable() ) ); Select.Where selectWhere = select.where( eq( quote( key.getColumnNames()[0] ), QueryBuilder.bindMarker() ) ); for ( int i = 1; i < key.getColumnNames().length; i++ ) { selectWhere = selectWhere.and( eq( quote( key.getColumnNames()[i] ), QueryBuilder.bindMarker() ) ); } boolean requiredFiltering = false; for ( Column column : tablePKCols ) { String name = column.getName(); boolean foundColumn = false; for ( int i = 0; i < key.getColumnNames().length; i++ ) { if ( name.equals( key.getColumnNames()[i] ) ) { foundColumn = true; break; } } if ( !foundColumn ) { requiredFiltering = true; break; } } if ( requiredFiltering ) { select.allowFiltering(); } Object[] columnValues = key.getColumnValues(); ResultSet resultSet = bindAndExecute( columnValues, select ); if ( resultSet.isExhausted() ) { return null; } Association association = new Association( new ResultSetAssociationSnapshot( key, resultSet, provider.getMetaDataCache() .get( table ), protocolVersion ) ); return association; }

Target:
public Association getAssociation(AssociationKey key, AssociationContext associationContext) { String table = key.getTable(); Table tableMetadata = provider.getMetaDataCache().get( key.getTable() ); List<Column> tablePKCols = (List<Column>) tableMetadata.getPrimaryKey().getColumns(); Select select = select().all().from( quote( key.getTable() ) ); Select.Where selectWhere = select.where( eq( quote( key.getColumnNames()[0] ), QueryBuilder.bindMarker() ) ); for ( int i = 1; i < key.getColumnNames().length; i++ ) { selectWhere = selectWhere.and( eq( quote( key.getColumnNames()[i] ), QueryBuilder.bindMarker() ) ); } boolean requiredFiltering = false; for ( Column column : tablePKCols ) { String name = column.getName(); boolean foundColumn = false; for ( int i = 0; i < key.getColumnNames().length; i++ ) { if ( name.equals( key.getColumnNames()[i] ) ) { foundColumn = true; break; } } if ( !foundColumn ) { requiredFiltering = true; break; } } if ( requiredFiltering ) { select.allowFiltering(); } Object[] columnValues = key.getColumnValues(); ResultSet resultSet = bindAndExecute( columnValues, select ); if ( resultSet.isExhausted() ) { return null; } Association association = new Association( new ResultSetAssociationSnapshot( key, resultSet, tableMetadata, protocolVersion ) ); return association; }