auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static GuestNicConfiguration map(VmInitNetwork entity, GuestNicConfiguration template) { GuestNicConfiguration model = template != null ? template : new GuestNicConfiguration(); model.setName(entity.getName()); model.setOnBoot(entity.getStartOnBoot()); <START> model.setBootProtocol(entity.getBootProtocol() == NetworkBootProtocol.STATIC_IP ? BootProtocol.STATIC.name() : entity.getBootProtocol().name()); <END> IP ip = new IP(); model.setIp(ip); ip.setAddress(entity.getIp()); ip.setNetmask(entity.getNetmask()); ip.setGateway(entity.getGateway()); return model; }</code><technical_language>I this follows: if (entity.getBootProtocol() != null) { model.setBootProtocol(BootProtocolMapper.map(entity.getBootProtocol(), null).value()); }</technical_language>

Target:
public static GuestNicConfiguration map(VmInitNetwork entity, GuestNicConfiguration template) { GuestNicConfiguration model = template != null ? template : new GuestNicConfiguration(); model.setName(entity.getName()); model.setOnBoot(entity.getStartOnBoot()); if (entity.getBootProtocol() != null) { model.setBootProtocol(BootProtocolMapper.map(entity.getBootProtocol(), null).value()); } IP ip = new IP(); model.setIp(ip); ip.setAddress(entity.getIp()); ip.setNetmask(entity.getNetmask()); ip.setGateway(entity.getGateway()); return model; }
Source:
<code>public static void waitTillInstancesAreCreated(ColoHelper coloHelper, String entity, int bundleSeqNo, int totalMinutesToWait ) throws JAXBException, OozieClientException { int sleep = totalMinutesToWait * 60 / 20; String entityName = Util.readEntityName(entity); ENTITY_TYPE type = Util.getEntityType(entity); String bundleID = getSequenceBundleID(coloHelper,entityName,type, <START> bundleSeqNo); <END> String coordID = getDefaultCoordIDFromBundle(coloHelper, bundleID); for (int sleepCount = 0; sleepCount < sleep; sleepCount++) { CoordinatorJob coordInfo = coloHelper.getProcessHelper().getOozieClient() .getCoordJobInfo(coordID); if(coordInfo.getActions().size() > 0) break; logger.info("Coord "+ coordInfo.getId() + " still dosent have " + "instance created on oozie: " + coloHelper.getProcessHelper() .getOozieClient().getOozieUrl()); try { Thread.sleep(20000); } catch (InterruptedException e) { logger.error(e.getMessage()); } } }</code><technical_language>if bundle/coordinator job creation takes more time get null</technical_language>

Target:
public static void waitTillInstancesAreCreated(ColoHelper coloHelper, String entity, int bundleSeqNo, int totalMinutesToWait ) throws JAXBException, OozieClientException { int sleep = totalMinutesToWait * 60 / 5; String entityName = Util.readEntityName(entity); ENTITY_TYPE type = Util.getEntityType(entity); String bundleID = getSequenceBundleID(coloHelper,entityName,type, bundleSeqNo); String coordID = getDefaultCoordIDFromBundle(coloHelper, bundleID); for (int sleepCount = 0; sleepCount < sleep; sleepCount++) { CoordinatorJob coordInfo = coloHelper.getProcessHelper().getOozieClient() .getCoordJobInfo(coordID); if(coordInfo.getActions().size() > 0) break; logger.info("Coord "+ coordInfo.getId() + " still dosent have " + "instance created on oozie: " + coloHelper.getProcessHelper() .getOozieClient().getOozieUrl()); try { Thread.sleep(5000); } catch (InterruptedException e) { logger.error(e.getMessage()); } } }
Source:
<code>protected VersionedOperationResponse executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, REPLACE_IF_UNMODIFIED_REQUEST); transport.writeArray(key); transport.writeVInt(lifespan); transport.writeVInt(maxIdle); <START> codec.writeExpirationNanoTimes(transport, lifespanNanos, maxIdleNanos, internalFlags); <END> transport.writeLong(version); transport.writeArray(value); transport.flush(); return returnVersionedOperationResponse(transport, params); }</code><technical_language>I more neater write extra lifespan/maxIdle parameters, instead write write lifespan/maxIdle add possibility send a new option defines granularity of lifespan/maxIdle. current solution feels akward adding new fields existing used. IOW, add more flag flags parameter done client :)</technical_language>

Target:
protected VersionedOperationResponse executeOperation(Transport transport) { HeaderParams params = writeHeader(transport, REPLACE_IF_UNMODIFIED_REQUEST); transport.writeArray(key); codec.writeExpirationParams(transport, lifespan, maxIdle, internalFlags); transport.writeLong(version); transport.writeArray(value); transport.flush(); return returnVersionedOperationResponse(transport, params); }
Source:
<code>public static String getFileExtension(File file) { String extension; try { extension = FilenameUtils.getExtension(file.getAbsolutePath()); <START> } catch (Exception e) { <END> extension = null; } return extension.toLowerCase(); }</code><technical_language>throw Exception instead of swallowing it. write like: java public static String getFileExtension(File file) throws Exception { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); } This new method deserve some unit test in FsCrawlerUtilTest</technical_language>

Target:
public static String getFileExtension(File file) { return FilenameUtils.getExtension(file.getAbsolutePath()).toLowerCase(); }
Source:
<code>public void init(String configFilePath) throws ManageDomainsResult { try { utilityConfiguration = new ManageDomainsConfiguration(configFilePath); } catch (ConfigurationException e) { throw new ManageDomainsResult(ManageDomainsResultEnum.FAILED_READING_CONFIGURATION, <START> "Verify that postgresql service is up and check DB configurations", e.getMessage()); <END> } try { daoImpl = new ManageDomainsDAOImpl(); } catch (SQLException e) { throw new ManageDomainsResult(ManageDomainsResultEnum.DB_EXCEPTION, "Verify that postgresql service is up and check DB configurations", e.getMessage()); } }</code><technical_language>string ConfigurationProvider? create a class some constants (public static final String ... ) constants in ConfigurationProvider</technical_language>

Target:
public void init(String configFilePath) throws ManageDomainsResult { try { utilityConfiguration = new ManageDomainsConfiguration(configFilePath); } catch (ConfigurationException e) { throw new ManageDomainsResult(ManageDomainsResultEnum.FAILED_READING_CONFIGURATION, e.getMessage()); } try { daoImpl = new ManageDomainsDAOImpl(); } catch (SQLException e) { throw new ManageDomainsResult("Please verify the following:\n1. Your database credentials are valid.\n2. The database machine is accessible.\n3. The database service is running", ManageDomainsResultEnum.DB_EXCEPTION, e.getMessage()); } }
Source:
<code>@Override public TResult current() { <START> final List<Object> list = Arrays.asList(elements.clone()); <END> @SuppressWarnings("unchecked") final TOuter outer = (TOuter) list.get(0); @SuppressWarnings("unchecked") final TInner inner = (TInner) list.get(1); return this.resultSelector.apply(outer, inner); }</code><technical_language>is purpose of Arrays.asList .clone() here</technical_language>

Target:
@Override public TResult current() { final TOuter outer = (TOuter) elements[0]; final TInner inner = (TInner) elements[1]; return this.resultSelector.apply(outer, inner); }
Source:
<code>public static boolean scaleImage(File originalImage, String finalFilePath, int maxDimen) { boolean scaledImage = false; Bitmap bitmap = BitmapFactory.decodeFile(originalImage.getAbsolutePath()); int height = bitmap.getHeight(); int width = bitmap.getWidth(); int largerDimen = Math.max(height, width); int smallerDimen = Math.min(height, width); if (largerDimen > maxDimen) { double aspectRatio = ((double) smallerDimen) / largerDimen; largerDimen = maxDimen; smallerDimen = (int) Math.floor(maxDimen * aspectRatio); if (width > height) { bitmap = Bitmap.createScaledBitmap(bitmap, largerDimen, smallerDimen, false); } else { bitmap = Bitmap.createScaledBitmap(bitmap, smallerDimen, largerDimen, false); } FileOutputStream out = null; try { out = new FileOutputStream(finalFilePath); <START> bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); <END> scaledImage = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } return scaledImage; }</code><technical_language>input file a JPG. need check file's input type get here, identify write output (JPEG, PNG, etc) if throw a warning werne't able scale image of type FOO</technical_language>

Target:
public static boolean scaleImage(File originalImage, String finalFilePath, int maxDimen) { boolean scaledImage = false; String extension = getExtension(originalImage.getAbsolutePath()); ImageWidget.ImageType type = ImageWidget.ImageType.fromExtension(extension); if (type == null) { Log.i(t, "Could not scale image " + originalImage.getAbsolutePath() + " due to incompatible extension"); return false; } Bitmap bitmap = BitmapFactory.decodeFile(originalImage.getAbsolutePath()); int height = bitmap.getHeight(); int width = bitmap.getWidth(); int largerDimen = Math.max(height, width); int smallerDimen = Math.min(height, width); if (largerDimen > maxDimen) { double aspectRatio = ((double) smallerDimen) / largerDimen; largerDimen = maxDimen; smallerDimen = (int) Math.floor(maxDimen * aspectRatio); if (width > height) { bitmap = Bitmap.createScaledBitmap(bitmap, largerDimen, smallerDimen, false); } else { bitmap = Bitmap.createScaledBitmap(bitmap, smallerDimen, largerDimen, false); } FileOutputStream out = null; try { out = new FileOutputStream(finalFilePath); bitmap.compress(type.getCompressFormat(), 100, out); scaledImage = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } return scaledImage; }
Source:
<code>public synchronized void load(PackageLoader packageLoader, boolean resolve) { if (state == State.PROXY) { EPackage[] ePackages = null; ePackages = loadPackagesFromGlobalRegistry(); if (ePackages == null) { ePackages = packageLoader.loadPackages(this); } for (EPackage ePackage : ePackages) { String packageURI = ePackage.getNsURI(); InternalCDOPackageInfo packageInfo = getPackageInfo(packageURI); if (resolve) { <START> packageRegistry.registerPackageInfo(ePackage, packageInfo); <END> synchronized (ePackage) { EcoreUtil.resolveAll(ePackage); } } } setState(State.LOADED); } }</code><technical_language>commit in CDO places this line if (resolve) statement: <LINK_0> why</technical_language>

Target:
public synchronized void load(PackageLoader packageLoader, boolean resolve) { if (state == State.PROXY) { EPackage[] ePackages = null; ePackages = loadPackagesFromGlobalRegistry(); if (ePackages == null) { ePackages = packageLoader.loadPackages(this); } for (EPackage ePackage : ePackages) { String packageURI = ePackage.getNsURI(); InternalCDOPackageInfo packageInfo = getPackageInfo(packageURI); packageRegistry.registerPackageInfo(ePackage, packageInfo); if (resolve) { synchronized (ePackage) { EcoreUtil.resolveAll(ePackage); } } } setState(State.LOADED); } }
Source:
<code>public void setUrlResourceReaderRootDirs(String... rootResourceDirs) throws IOException { Set<String> newRootResourceDirs = ImmutableSet.<String>builder().add(rootResourceDirs).build(); Configuration configuration = configAdmin.getConfiguration(PID, null); <START> if (configuration == null) { <END> LOGGER.warn( "{} configuration was null, cannot update {}", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY); return; } if (configuration.getProperties() != null) { Set<String> currentRootResourceDirs = ImmutableSet.copyOf( (Collection<String>) configuration.getProperties().get(ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY)); LOGGER.debug( "{} {}, current value: {}, new value: {}", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY, currentRootResourceDirs, newRootResourceDirs); if (rootResourceDirsEqual(currentRootResourceDirs, newRootResourceDirs)) { LOGGER.debug( "{} unchanged, skipping update", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY); return; } } Dictionary<String, Object> properties = new DictionaryMap<>(); properties.put(ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY, newRootResourceDirs); configuration.update(properties); for (int i = 0; i < 5; i++) { Configuration updatedConfig = configAdmin.getConfiguration(PID, null); if (updatedConfig .getProperties() .get(ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY) .equals(newRootResourceDirs)) { break; } boolean interrupted = false; try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { interrupted = true; } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } LOGGER.debug("{} properties after update: {}", PID, configuration.getProperties()); }</code><technical_language>Is goal create config if exit? If do call listConfiguration("(service.pid=" + PID + ")")</technical_language>

Target:
public void setUrlResourceReaderRootDirs(String... rootResourceDirs) throws IOException { Collection<String> newRootResourceDirs = ImmutableSet.<String>builder().add(rootResourceDirs).build(); Configuration configuration = configAdmin.getConfiguration(PID, null); Collection<String> currentRootResourceDirs = getCurrentRootResourceDirs(configuration); if (currentRootResourceDirs != null) { LOGGER.debug( "{} {}, current value: {}, new value: {}", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY, currentRootResourceDirs, newRootResourceDirs); if (rootResourceDirsEqual(currentRootResourceDirs, newRootResourceDirs)) { LOGGER.debug( "{} unchanged, skipping update", PID, ROOT_RESOURCE_DIRECTORIES_PROPERTY_KEY); return; } } updateUrlResourceReaderRootDirs(configuration, newRootResourceDirs); }
Source:
<code>public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { LOGGER.debug( "Root path is blank. Resolving relative path to: {}", path, <START> LogSanitizer.cleanAndEncode(absolutePath.toAbsolutePath().toString())); <END> } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }</code><technical_language>question isDebugEnabled() instead of trace</technical_language>

Target:
public String getPath(String rootPath) { if (path == null) { return null; } boolean trailingSeparator = path.endsWith(File.separator); Path absolutePath = Paths.get(path); if (!absolutePath.isAbsolute()) { if (StringUtils.isNotBlank(rootPath)) { absolutePath = Paths.get(rootPath, path); } else { LOGGER.debug( "Root path is blank. Resolving relative path to: {}", path, LogSanitizer.sanitize(absolutePath.toAbsolutePath())); } } String absolutePathStr = absolutePath.toAbsolutePath().toString(); return trailingSeparator ? absolutePathStr + File.separator : absolutePathStr; }
Source:
<code><START> public void addWarning(String errorMessage, Element element) { <END> warnings.add(new ProblemImpl(errorMessage, name, element)); }</code><technical_language>well, I calls this method supply element id</technical_language>

Target:
public void addWarning(String errorMessage, Element element) { warnings.add(new ProblemImpl(errorMessage, element)); }
Source:
<code>protected void internalReceiveCommand(String itemName, Command command) { if (!isOutBound(itemName)) { logger.warn("Received command ({}) for item which is configured as 'in-bound', ignoring", command.toString(), itemName); return; } try { String xbmcInstance = getXbmcInstance(itemName); String property = getProperty(itemName); XbmcConnector connector = getXbmcConnector(xbmcInstance); if (connector == null) { logger.warn("Received command ({}) for item but no XBMC connector found for {}, ignoring", command.toString(), itemName, xbmcInstance); return; } if (!connector.isConnected()) { logger.warn("Received command ({}) for item but the connection to the XBMC instance is down, ignoring", command.toString(), itemName, xbmcInstance); return; } if (property.equals("Player.PlayPause")) connector.playerPlayPause(); if (property.equals("Player.Open")) connector.playerOpen(command.toString()); if (property.equals("Player.Stop")) connector.playerStop(); if (property.equals("GUI.ShowNotification")) connector.showNotification("openHAB", command.toString()); if (property.equals("System.Shutdown") && command == OnOffType.OFF) connector.systemShutdown(); if (property.equals("Application.Volume")) <START> connector.applicationSetVolume(command.toString()); <END> } catch (Exception e) { logger.error("Error handling command", e); } }</code><technical_language>please "else if" option valid a time</technical_language>

Target:
protected void internalReceiveCommand(String itemName, Command command) { if (!isOutBound(itemName)) { logger.warn("Received command ({}) for item which is configured as 'in-bound', ignoring", command.toString(), itemName); return; } try { String xbmcInstance = getXbmcInstance(itemName); String property = getProperty(itemName); XbmcConnector connector = getXbmcConnector(xbmcInstance); if (connector == null) { logger.warn("Received command ({}) for item but no XBMC connector found for {}, ignoring", command.toString(), itemName, xbmcInstance); return; } if (!connector.isConnected()) { logger.warn("Received command ({}) for item but the connection to the XBMC instance is down, ignoring", command.toString(), itemName, xbmcInstance); return; } if (property.equals("Player.PlayPause")) connector.playerPlayPause(); else if (property.equals("Player.Open")) connector.playerOpen(command.toString()); else if (property.equals("Player.Stop")) connector.playerStop(); else if (property.equals("GUI.ShowNotification")) connector.showNotification("openHAB", command.toString()); else if (property.equals("System.Shutdown") && command == OnOffType.OFF) connector.systemShutdown(); else if (property.equals("Application.Volume")) connector.applicationSetVolume(command.toString()); } catch (Exception e) { logger.error("Error handling command", e); } }
Source:
<code>public ReadBatch readRecords(List<Long> addresses, Optional<String> destNode, LogUnitClient client) { for (int i = 0; i < maxReadRetries; i++) { try { ReadResponse response = CFUtils .getUninterruptibly(client.readAll(ImmutableList.copyOf(addresses)), TimeoutException.class, NetworkException.class); Map<Long, ILogData> records = new HashMap<>(response.getAddresses()); ReadBatch readBatch = checkReadRecords(ImmutableList.copyOf(addresses), records, destNode); if (readBatch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + readBatch.getFailedAddresses()); } return readBatch; <START> } catch (NetworkException | TimeoutException | IllegalStateException e) { log.warn("readRecords: error occurred: {}, retry times.", e, i); } catch (RuntimeException re) { log.error("readRecords: can't retry, error:", re); break; } } <END> throw new ReadBatchException("readRecords: read retries were exhausted"); }</code><technical_language>If WrongEpochException happens, stop retrying this node, conitnue retrying a new random node, is good. WrongEpochException read/write propogated immediately outmost layer, is backoff retry invalidate layout</technical_language>

Target:
public ReadBatch readRecords(List<Long> addresses, Optional<String> destNode, LogUnitClient client) { for (int i = 0; i < maxReadRetries; i++) { try { ReadResponse response = CFUtils .getUninterruptibly(client.readAll(addresses)); Map<Long, ILogData> records = new HashMap<>(response.getAddresses()); ReadBatch readBatch = checkReadRecords(addresses, records, destNode); if (readBatch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + readBatch.getFailedAddresses()); } return readBatch; } catch (WrongEpochException e) { log.warn("readRecords: encountered a wrong epoch exception on try {}: {}.", i, e); throw e; } catch (RuntimeException e) { log.warn("readRecords: encountered an exception on try {}: {}.", i, e); Sleep.sleepUninterruptibly(readSleepDuration); } } throw new ReadBatchException("readRecords: read retries were exhausted"); }
Source:
<code>private synchronized boolean isProtocolNameInconsistent(ApiKeys key, String protocolName) { final boolean protocolNameInconsistent = protocolName != null && generation() != Generation.NO_GENERATION && !protocolName.equals(generation().protocolName); <START> if (protocolNameInconsistent) { <END> log.error("{} failed due to inconsistent Protocol Name, received but expected {}", key, protocolName, generation().protocolName); } return protocolNameInconsistent; }</code><technical_language>@dajac clarify, generation() change check error-log? If do need synchronize function, instead get a reference of returned generation() call in error-log, generation object is immutable</technical_language>

Target:
private boolean isProtocolNameInconsistent(ApiKeys key, String protocolName) { final Generation currentGeneration = generation(); final boolean protocolNameInconsistent = protocolName != null && currentGeneration != Generation.NO_GENERATION && !protocolName.equals(currentGeneration.protocolName); if (protocolNameInconsistent) { log.error("{} failed due to inconsistent Protocol Name, received but expected {}", key, protocolName, currentGeneration.protocolName); } return protocolNameInconsistent; }
Source:
<code><START> public Optional<Enrollment> enrollUser(Enrollment enrollment, boolean isSectionEnrollment) throws InvalidOauthTokenException, IOException { <END> String createdUrl = null; if (isSectionEnrollment) { createdUrl = buildCanvasUrl("sections/" + enrollment.getCourseSectionId() + "/enrollments", Collections.emptyMap()); } else { createdUrl = buildCanvasUrl("courses/" + enrollment.getCourseId() + "/enrollments", Collections.emptyMap()); } LOG.debug("create URl for course enrollments: "+ createdUrl); Response response = canvasMessenger.sendToCanvas(oauthToken, createdUrl, enrollment.toPostMap()); if (response.getErrorHappened() || response.getResponseCode() != 200) { LOG.debug("Failed to enroll in course, error message: " + response.toString()); return Optional.empty(); } return responseParser.parseToObject(Enrollment.class,response); }</code><technical_language>do making this method private public ones: enrollUserInCourse enrollUserInSection call private one, adding boolean parameter? a bit clearer users of library. public verify enrollment object required section ID passing private method do work. (Stringutils.isBlank() check IllegalArgumentException thrown if fails)</technical_language>

Target:
private Optional<Enrollment> enrollUser(Enrollment enrollment, boolean isSectionEnrollment) throws InvalidOauthTokenException, IOException { String createdUrl = null; if (isSectionEnrollment) { createdUrl = buildCanvasUrl("sections/" + enrollment.getCourseSectionId() + "/enrollments", Collections.emptyMap()); } else { createdUrl = buildCanvasUrl("courses/" + enrollment.getCourseId() + "/enrollments", Collections.emptyMap()); } LOG.debug("create URl for course enrollments: "+ createdUrl); Response response = canvasMessenger.sendToCanvas(oauthToken, createdUrl, enrollment.toPostMap()); if (response.getErrorHappened() || response.getResponseCode() != 200) { LOG.debug("Failed to enroll in course, error message: " + response.toString()); return Optional.empty(); } return responseParser.parseToObject(Enrollment.class,response); }
Source:
<code>public Map<Errors, Integer> errorCounts() { Map<Errors, Integer> errorCounts = new HashMap<>(); <START> for (AlterReplicaLogDirTopicResult x : data.results()) { for (AlterReplicaLogDirsResponseData.AlterReplicaLogDirPartitionResult y : x.partitions()) { <END> updateErrorCounts(errorCounts, Errors.forCode(y.errorCode())); } } return errorCounts; }</code><technical_language>nit: rename x y well</technical_language>

Target:
public Map<Errors, Integer> errorCounts() { Map<Errors, Integer> errorCounts = new HashMap<>(); data.results().forEach(topicResult -> topicResult.partitions().forEach(partitionResult -> updateErrorCounts(errorCounts, Errors.forCode(partitionResult.errorCode())))); return errorCounts; }
Source:
<code>public Truthiness not() { <START> if (this == TRUTHY) { <END> return FALSY; } else if (this == FALSY) { return TRUTHY; } else { return UNKNOWN; } }</code><technical_language>@pynicolas switch</technical_language>

Target:
public Truthiness not() { switch (this) { case TRUTHY: return FALSY; case FALSY: return TRUTHY; default: return UNKNOWN; } }
Source:
<code>protected Map<String, String> convertLabelsToKubernetesNames(Map<String, String> labels) { Map<String, String> names = new HashMap<>(); for (Map.Entry<String, String> entry : labels.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { continue; } if (!key.startsWith(CHE_OPENSHIFT_RESOURCES_PREFIX)) { LOG.warn("Expected CreateContainerParams label key " + entry.getKey() + " to start with " + CHE_SERVER_LABEL_PREFIX); } else if (key.contains(".") || key.contains("_") || value.contains("_")) { <START> LOG.error(String.format("Cannot convert label %s to DNS Name: contains '-' or '.'", entry.toString())); <END> continue; } key = key.replaceAll(":", ".").replaceAll("/", "_"); value = value.replaceAll("/", "_"); names.put(String.format(CHE_SERVER_LABEL_PADDING, key), String.format(CHE_SERVER_LABEL_PADDING, value)); } return names; }</code><technical_language>I more explicit in log here: "Cannot convert label .... escape characters."</technical_language>

Target:
protected Map<String, String> convertLabelsToKubernetesNames(Map<String, String> labels) { Map<String, String> names = new HashMap<>(); for (Map.Entry<String, String> entry : labels.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null) { continue; } if (!key.startsWith(CHE_SERVER_LABEL_PREFIX)) { LOG.warn("Expected CreateContainerParams label key " + entry.getKey() + " to start with " + CHE_SERVER_LABEL_PREFIX); } else if (key.contains(".") || key.contains("_") || value.contains("_")) { LOG.error(String.format("Cannot convert label %s to DNS Name: " + "'-' and '.' are used as escape characters", entry.toString())); continue; } key = key.replaceAll(":", ".").replaceAll("/", "_"); value = value.replaceAll("/", "_"); key = String.format(CHE_SERVER_LABEL_PADDING, key); value = String.format(CHE_SERVER_LABEL_PADDING, value); if (!key.matches(KUBERNETES_ANNOTATION_REGEX) || !value.matches(KUBERNETES_ANNOTATION_REGEX)) { LOG.error(String.format("Could not convert label %s into Kubernetes annotation: " + "labels must be alphanumeric with ':' and '/'", entry.toString())); continue; } names.put(key, value); } return names; }
Source:
<code>private Player() { id = new SimpleIntegerProperty(); username = new SimpleStringProperty(); <START> clan = new SimpleStringProperty(null); <END> country = new SimpleStringProperty(); avatarUrl = new SimpleStringProperty(); avatarTooltip = new SimpleStringProperty(); moderatorForChannels = new SimpleSetProperty<>(FXCollections.observableSet()); chatOnly = new SimpleBooleanProperty(true); globalRatingDeviation = new SimpleFloatProperty(); globalRatingMean = new SimpleFloatProperty(); leaderboardRatingDeviation = new SimpleFloatProperty(); leaderboardRatingMean = new SimpleFloatProperty(); status = new SimpleObjectProperty<>(PlayerStatus.IDLE); game = new SimpleObjectProperty<>(); numberOfGames = new SimpleIntegerProperty(); socialStatus = new SimpleObjectProperty<>(OTHER); idleSince = new SimpleObjectProperty<>(Instant.now()); }</code><technical_language>null is default, it</technical_language>

Target:
private Player() { id = new SimpleIntegerProperty(); username = new SimpleStringProperty(); clan = new SimpleStringProperty(); country = new SimpleStringProperty(); avatarUrl = new SimpleStringProperty(); avatarTooltip = new SimpleStringProperty(); moderatorForChannels = new SimpleSetProperty<>(FXCollections.observableSet()); chatOnly = new SimpleBooleanProperty(true); globalRatingDeviation = new SimpleFloatProperty(); globalRatingMean = new SimpleFloatProperty(); leaderboardRatingDeviation = new SimpleFloatProperty(); leaderboardRatingMean = new SimpleFloatProperty(); status = new SimpleObjectProperty<>(PlayerStatus.IDLE); game = new SimpleObjectProperty<>(); numberOfGames = new SimpleIntegerProperty(); socialStatus = new SimpleObjectProperty<>(OTHER); idleSince = new SimpleObjectProperty<>(Instant.now()); }
Source:
<code>protected Result convert(Citations source) { if (CollectionUtils.isNotEmpty(source.getCitations())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); ExtraInfo extraInfo = new ExtraInfo(); extraInfo.setValue(converter.serialize(normalize(source.getCitations()))); extraInfo.setName(EXTRA_INFO_NAME); extraInfo.setTypology(EXTRA_INFO_TYPOLOGY); extraInfo.setProvenance(this.getInferenceProvenance()); extraInfo.setTrust(StaticConfigurationProvider.ACTION_TRUST_0_9); <START> result.setExtraInfo(Arrays.asList(extraInfo)); <END> return result; } else { return null; } }</code><technical_language>IDE Collections.singletonList</technical_language>

Target:
protected Result convert(Citations source) { if (CollectionUtils.isNotEmpty(source.getCitations())) { Result result = new Result(); result.setId(source.getDocumentId().toString()); ExtraInfo extraInfo = new ExtraInfo(); extraInfo.setValue(converter.serialize(normalize(source.getCitations()))); extraInfo.setName(EXTRA_INFO_NAME); extraInfo.setTypology(EXTRA_INFO_TYPOLOGY); extraInfo.setProvenance(this.getInferenceProvenance()); extraInfo.setTrust(StaticConfigurationProvider.ACTION_TRUST_0_9); result.setExtraInfo(Collections.singletonList(extraInfo)); return result; } else { return null; } }
Source:
<code>private boolean runDelegatedTasks(boolean inUnwrap) { <START> if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE || (delegatedTaskExecutor instanceof EventExecutor <END> && ((EventExecutor) delegatedTaskExecutor).inEventLoop())) { for (;;) { Runnable task = engine.getDelegatedTask(); if (task == null) { return true; } task.run(); } } else { final Runnable task = engine.getDelegatedTask(); assert task != null; executeDelegatingTask(task, inUnwrap); return false; } }</code><technical_language>optional: I find more readable break line || visual grouping is semantic grouping</technical_language>

Target:
private boolean runDelegatedTasks(boolean inUnwrap) { if (delegatedTaskExecutor == ImmediateExecutor.INSTANCE || inEventLoop(delegatedTaskExecutor)) { for (;;) { runAllDelegatedTasks(engine); return true; } } else { executeDelegatedTasks(inUnwrap); return false; } }
Source:
<code>public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { if (httpServletRequest.getRequestURI().toString().contains(DATA_ELEMENTS_ENDPOINT)) { <START> writeResponse(httpServletResponse, "/dhis2/data-elements-response.json"); <END> } else if (httpServletRequest.getRequestURI().toString().contains(DATA_SETS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/data-sets-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(ORGANISATION_UNITS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/organisation-units-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAMS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/programs-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAM_STAGES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/program-stages-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAM_STAGE_DATA_ELEMENTS_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/program-stage-data-elements-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(TRACKED_ENTITIES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/tracked-entities-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(TRACKED_ENTITY_ATTRIBUTES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/tracked-entity-attributes-response.json"); } else if (httpServletRequest.getRequestURI().toString().contains(PROGRAM_TRACKED_ENTITY_ATTRIBUTES_ENDPOINT)) { writeResponse(httpServletResponse, "/dhis2/program-tracked-entity-attributes-response.json"); } }</code><technical_language>please constants for path file</technical_language>

Target:
public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { String requestURI = httpServletRequest.getRequestURI().toString(); if (requestURI.contains(PROGRAM_ENDPOINT)) { writeResponse(httpServletResponse, PROGRAM_RESPONSE); } else if (requestURI.contains(DATA_ELEMENTS_ENDPOINT)) { writeResponse(httpServletResponse, DATA_ELEMENTS_RESPONSE); } else if (requestURI.contains(DATA_SETS_ENDPOINT)) { writeResponse(httpServletResponse, DATA_SETS_RESPONSE); } else if (requestURI.contains(ORGANISATION_UNITS_ENDPOINT)) { writeResponse(httpServletResponse, ORGANISATION_UNITS_RESPONSE); } else if (requestURI.contains(PROGRAMS_ENDPOINT)) { writeResponse(httpServletResponse, PROGRAMS_RESPONSE); } else if (requestURI.contains(TRACKED_ENTITIES_ENDPOINT)) { writeResponse(httpServletResponse, TRACKED_ENTITIES_RESPONSE); } else if (requestURI.contains(TRACKED_ENTITY_ATTRIBUTES_ENDPOINT)) { writeResponse(httpServletResponse, TRACKED_ENTITY_ATTRIBUTES_RESPONSE); } }
Source:
<code>protected boolean isAnonymous() { <START> return getModelObject() != null && getModelObject().getReview() != null <END> && getModelObject().getReview().getRepository() != null && getModelObject().getReview().getRepository().getAccount() == null; }</code><technical_language>This implemented in framework shared places check for anonymous access</technical_language>

Target:
protected boolean isAnonymous() { return ReviewUiUtil.isAnonymous(getModelObject()); }
Source:
<code>public void tearDown() throws IOException { try { DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); <START> } catch (GoogleJsonResponseException gjre) { } <END> System.setOut(originalOut); bout.reset(); }</code><technical_language><LINK_0></technical_language>

Target:
public void tearDown() throws IOException { DeleteJobTemplate.deleteJobTemplate(PROJECT_ID, LOCATION, TEMPLATE_ID); System.setOut(originalOut); bout.reset(); }
Source:
<code>private List<IProject> findProjectsToDelete(final List<RepositoryNode> selectedNodes) { final List<IProject> projectsToDelete = new ArrayList<>(); for (RepositoryNode node : selectedNodes) { Repository repository = node.getRepository(); <START> if (repository == null) { <END> continue; } if (repository.isBare()) continue; File workDir = repository.getWorkTree(); final IPath wdPath = new Path(workDir.getAbsolutePath()); for (IProject prj : ResourcesPlugin.getWorkspace() .getRoot().getProjects()) { IPath location = prj.getLocation(); if (location != null && wdPath.isPrefixOf(location)) { projectsToDelete.add(prj); } } } return projectsToDelete; }</code><technical_language>if (repository == null || repository.isBare()) { is more concise rid of {}-less block below</technical_language>

Target:
private List<IProject> findProjectsToDelete(final List<RepositoryNode> selectedNodes) { final List<IProject> projectsToDelete = new ArrayList<>(); for (RepositoryNode node : selectedNodes) { Repository repository = node.getRepository(); if (repository == null || repository.isBare()) { continue; } File workDir = repository.getWorkTree(); final IPath wdPath = new Path(workDir.getAbsolutePath()); for (IProject prj : ResourcesPlugin.getWorkspace() .getRoot().getProjects()) { IPath location = prj.getLocation(); if (location != null && wdPath.isPrefixOf(location)) { projectsToDelete.add(prj); } } } return projectsToDelete; }
Source:
<code>public long byteSize() { <START> return cacheEntriesBytes + size()*24; <END> }</code><technical_language>code reformat</technical_language>

Target:
public long byteSize() { log.debug("the cache has entries, the object size used {}, calculated by beepSize {}", size(), CONFLICTTXSTREAM_OBJ_SIZE, cacheEntries.isEmpty() ? 0 : MetricsUtils.sizeOf.deepSizeOf(cacheEntries.peek())); return size()*(ENTRY_OVERHEAD + CONFLICTTXSTREAM_OBJ_SIZE); }
Source:
<code>private void checkFailedAccess( HttpClient httpClient, HttpMethod method, String url, String clientDesc, Class expectedException, String expectedExceptionMsg ) { int retries = 0; while (true) { try { makeRequest(httpClient, method, url, null, -1); } catch (RuntimeException re) { Throwable rootCause = Throwables.getRootCause(re); if (rootCause instanceof IOException && ("Broken pipe".equals(rootCause.getMessage()) || "Connection reset by peer".contains(rootCause.getMessage()))) { if (retries > MAX_CONNECTION_EXCEPTION_RETRIES) { Assert.fail(StringUtils.format( <START> "Broken pipe retries exhausted, test failed, did not get %s.", <END> expectedException )); } else { retries += 1; continue; } } Assert.assertTrue( expectedException.isInstance(rootCause), StringUtils.format("Expected %s but found %s instead.", expectedException, rootCause) ); Assert.assertEquals( rootCause.getMessage(), expectedExceptionMsg ); LOG.info("%s client [%s] request failed as expected when accessing [%s]", clientDesc, method, url); return; } Assert.fail(StringUtils.format("Test failed, did not get %s.", expectedException)); } }</code><technical_language>Broken pipe connection reset retries exhausted</technical_language>

Target:
private void checkFailedAccess( HttpClient httpClient, HttpMethod method, String url, String clientDesc, Class expectedException, String expectedExceptionMsg ) { int retries = 0; while (true) { try { makeRequest(httpClient, method, url, null, -1); } catch (RuntimeException re) { Throwable rootCause = Throwables.getRootCause(re); if (rootCause instanceof IOException && ("Broken pipe".equals(rootCause.getMessage()) || "Connection reset by peer".contains(rootCause.getMessage()))) { if (retries > MAX_CONNECTION_EXCEPTION_RETRIES) { Assert.fail(StringUtils.format( "Broken pipe / connection reset retries exhausted, test failed, did not get %s.", expectedException )); } else { retries += 1; continue; } } Assert.assertTrue( expectedException.isInstance(rootCause), StringUtils.format("Expected %s but found %s instead.", expectedException, rootCause) ); Assert.assertEquals( rootCause.getMessage(), expectedExceptionMsg ); LOG.info("%s client [%s] request failed as expected when accessing [%s]", clientDesc, method, url); return; } Assert.fail(StringUtils.format("Test failed, did not get %s.", expectedException)); } }
Source:
<code>private MetaConstraint<?> withGetterLocation(ConstraintLocation getterConstraintLocation, MetaConstraint<?> constraint) { ConstraintLocation converted = null; if ( !(constraint.getLocation() instanceof TypeArgumentConstraintLocation) ) { if ( requiresConversionToGetterLocation( getterConstraintLocation, constraint ) ) { converted = getterConstraintLocation; } else { converted = constraint.getLocation(); <START> } <END> } else { Deque<ConstraintLocation> locationStack = new ArrayDeque<>(); ConstraintLocation current = constraint.getLocation(); do { locationStack.addFirst( current ); if ( current instanceof TypeArgumentConstraintLocation ) { current = ( (TypeArgumentConstraintLocation) current ).getDelegate(); } else { current = null; } } while ( current != null ); for ( ConstraintLocation location : locationStack ) { if ( !(location instanceof TypeArgumentConstraintLocation) ) { converted = getterConstraintLocation; } else { converted = ConstraintLocation.forTypeArgument( converted, ( (TypeArgumentConstraintLocation) location ).getTypeParameter(), location.getTypeForValidatorResolution() ); } } } return MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraint.getDescriptor(), converted ); }</code><technical_language>OK, this is ugly hack if ends it, a no-no for me. This method is convert other type of constraint location a getter constraint location if is one, do need do anything. I simply do: if ( constraint.getLocation() instanceof GetterConstraintLocation ) { converted = constraint.getLocation(); } else { converted = getterConstraintLocation; } for other spot forgot line 293 of updated code</technical_language>

Target:
private MetaConstraint<?> withGetterLocation(ConstraintLocation getterConstraintLocation, MetaConstraint<?> constraint) { ConstraintLocation converted = null; if ( !(constraint.getLocation() instanceof TypeArgumentConstraintLocation) ) { if ( constraint.getLocation() instanceof GetterConstraintLocation ) { converted = constraint.getLocation(); } else { converted = getterConstraintLocation; } } else { Deque<ConstraintLocation> locationStack = new ArrayDeque<>(); ConstraintLocation current = constraint.getLocation(); do { locationStack.addFirst( current ); if ( current instanceof TypeArgumentConstraintLocation ) { current = ( (TypeArgumentConstraintLocation) current ).getDelegate(); } else { current = null; } } while ( current != null ); for ( ConstraintLocation location : locationStack ) { if ( !(location instanceof TypeArgumentConstraintLocation) ) { if ( location instanceof GetterConstraintLocation ) { converted = location; } else { converted = getterConstraintLocation; } } else { converted = ConstraintLocation.forTypeArgument( converted, ( (TypeArgumentConstraintLocation) location ).getTypeParameter(), location.getTypeForValidatorResolution() ); } } } return MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraint.getDescriptor(), converted ); }
Source:
<code>public static Map<String, Object> defaultHeaders(EventMessage<?> message, SerializedObject<?> serializedObject) { Assert.notNull(message, () -> "Event message cannot be null"); Assert.notNull(serializedObject, () -> "Serialized Object cannot be null"); Assert.notNull(serializedObject.getType(), () -> "SerializedObject Type cannot be null"); return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put(MESSAGE_ID, message.getIdentifier()); put(MESSAGE_TYPE, serializedObject.getType().getName()); put(MESSAGE_REVISION, serializedObject.getType().getRevision()); <START> put(MESSAGE_TIMESTAMP, message.getTimestamp()); <END> }}); }</code><technical_language>a formatInstant format timestamp ISO8601. removed</technical_language>

Target:
public static Map<String, Object> defaultHeaders(EventMessage<?> message, SerializedObject<?> serializedObject) { Assert.notNull(message, () -> "Event message cannot be null"); Assert.notNull(serializedObject, () -> "Serialized Object cannot be null"); Assert.notNull(serializedObject.getType(), () -> "SerializedObject Type cannot be null"); HashMap<String, Object> headers = new HashMap<>(); headers.put(MESSAGE_ID, message.getIdentifier()); headers.put(MESSAGE_TYPE, serializedObject.getType().getName()); headers.put(MESSAGE_REVISION, serializedObject.getType().getRevision()); headers.put(MESSAGE_TIMESTAMP, message.getTimestamp()); if (message instanceof DomainEventMessage) { headers.put(AGGREGATE_ID, ((DomainEventMessage<?>) message).getAggregateIdentifier()); headers.put(AGGREGATE_SEQ, ((DomainEventMessage<?>) message).getSequenceNumber()); headers.put(AGGREGATE_TYPE, ((DomainEventMessage<?>) message).getType()); } return Collections.unmodifiableMap(headers); }
Source:
<code>public void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .build(); <START> String filePath = System.getProperty("user.dir") + File.separator + "GOOGLE_APPLICATION_CREDENTIALS"; <END> userCredentials.save(filePath); }</code><technical_language>running tests, I want this file show in home directory I run them. Put /tmp (use Java function auto-generated a file /tmp)</technical_language>

Target:
public void saveUserCredentials_saved_throws() throws IOException { UserCredentials userCredentials = UserCredentials.newBuilder() .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) .setRefreshToken(REFRESH_TOKEN) .build(); File file = File.createTempFile("GOOGLE_APPLICATION_CREDENTIALS", null, null); file.deleteOnExit(); String filePath = file.getAbsolutePath(); userCredentials.save(filePath); }
Source:
<code>public boolean[] encode(String contents) { contents = convertToExtended(contents); int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( <START> "Requested contents should be less than 80 digits long after extended, but got " + length); <END> } int codeWidth = (contents.length() + 2 + 2) * 9 + 1; boolean[] result = new boolean[codeWidth]; int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING); for (int i = 0; i < length; i++) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]); } int check1 = computeChecksumIndex(contents, 20); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]); contents += Code93Reader.ALPHABET_STRING.charAt(check1); int check2 = computeChecksumIndex(contents, 15); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]); pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING); result[pos] = true; return result; }</code><technical_language>"... converting extended encoding, ..."</technical_language>

Target:
public boolean[] encode(String contents) { contents = convertToExtended(contents); int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long after converting to extended encoding, but got " + length); } int codeWidth = (contents.length() + 2 + 2) * 9 + 1; boolean[] result = new boolean[codeWidth]; int pos = appendPattern(result, 0, Code93Reader.ASTERISK_ENCODING); for (int i = 0; i < length; i++) { int indexInString = Code93Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[indexInString]); } int check1 = computeChecksumIndex(contents, 20); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check1]); contents += Code93Reader.ALPHABET_STRING.charAt(check1); int check2 = computeChecksumIndex(contents, 15); pos += appendPattern(result, pos, Code93Reader.CHARACTER_ENCODINGS[check2]); pos += appendPattern(result, pos, Code93Reader.ASTERISK_ENCODING); result[pos] = true; return result; }
Source:
<code>private TaskResult await(GcsClient gcs, String bucket, String object) { StorageObject metadata = pollingWaiter(state, "exists") .withWaitMessage("Object '%s/%s' does not yet exist", bucket, object) .await(pollState -> pollingRetryExecutor(pollState, "poll") <START> .run(s -> gcs.stat(bucket, object))); <END> return TaskResult.defaultBuilder(request) .resetStoreParams(ImmutableList.of(ConfigKey.of("gcs_wait", "last_object"))) .storeParams(storeParams(metadata)) .build(); }</code><technical_language>need skip retrying in case of 4xx</technical_language>

Target:
private TaskResult await(GcsClient gcs, String bucket, String object) { StorageObject metadata = pollingWaiter(state, "exists") .withWaitMessage("Object '%s/%s' does not yet exist", bucket, object) .await(pollState -> pollingRetryExecutor(pollState, "poll") .retryUnless(GoogleJsonResponseException.class, Gcp::isDeterministicException) .run(s -> gcs.stat(bucket, object))); return TaskResult.defaultBuilder(request) .resetStoreParams(ImmutableList.of(ConfigKey.of("gcs_wait", "last_object"))) .storeParams(storeParams(metadata)) .build(); }
Source:
<code>public static String removeVersionFromName(String text) { <START> Pattern pattern = Pattern.compile(VERSION_PATTERN); <END> Matcher matcher = pattern.matcher(text); if (matcher.find()) { log.info("Removed " + text.substring(matcher.start()) + " from " + text); return text.substring(0, matcher.start()); } return text; }</code><technical_language>Pattern.compile done once</technical_language>

Target:
public static String removeVersionFromName(String text) { Matcher matcher = pattern.matcher(text); if (matcher.find()) { log.debug("Removed " + text.substring(matcher.start()) + " from " + text); return text.substring(0, matcher.start()); } return text; }