private boolean parseAuditLogForm( AuditLogForm auditLogForm, JEventCategory eventCategory, Model uiModel, Integer page, Integer size) { boolean hasParseErrors = false; String sDate = auditLogForm.getStartDateAsString(); String eDate = auditLogForm.getEndDateAsString(); try { if (!StringUtils.isEmpty(sDate)) { Date startDate = JUtils.DATE_FORMAT.parse(StringUtils.trim(sDate)); auditLogForm.setStartDate(startDate); } // Include endDate if (!StringUtils.isEmpty(eDate)) { Date endDate = JUtils.DATE_FORMAT.parse(StringUtils.trim(eDate)); if (endDate != null) { DateTime dateTime = new DateTime(endDate); dateTime = dateTime.plusDays(1); auditLogForm.setEndDate(dateTime.toDate()); } } } catch (ParseException e) { logger.error(">>> Failed parsing date.", e); uiModel.addAttribute("error_msg", "Saisie invalide. Le format de date est incorrect."); populateAuditLog(new AuditLogForm(), eventCategory, uiModel, "auditconnections", page, size); hasParseErrors = true; } return hasParseErrors; }
public void setModelPath(Map<String, String> modelPath) { if (null == modelPath || modelPath.size() < 1) return; String[] login_success; for (String model : modelPath.keySet()) { String path = modelPath.get(model); login_success = StringUtils.split(path, ";"); if (null != login_success && login_success.length == 2) { this.modelPath.put(StringUtils.trim(model) + LOGIN, StringUtils.trim(login_success[0])); this.modelPath.put(StringUtils.trim(model) + SUCCESS, StringUtils.trim(login_success[1])); } } }
@Override @Transactional public String updateFunction(Function function, String updatedBy) throws Exception { Function functionUpdate = findFunction(function.getId()); functionUpdate.setCd(StringUtils.trim(function.getCd())); functionUpdate.setName(StringUtils.trim(function.getName())); functionUpdate.setDescription(StringUtils.trim(function.getDescription())); functionUpdate.setUpdatedBy(updatedBy); functionUpdate.setDateUpdated(new Date()); getCurrentSession().update(functionUpdate); return functionUpdate.getId(); }
private boolean basicAuth(HttpServerRequest request, String encodedAuth) { byte[] authBytes = Base64.decodeBase64(encodedAuth); String decodedString = new String(authBytes); String[] splitAuth = StringUtils.split(StringUtils.trim(decodedString), ":"); // $NON-NLS-1$ if (splitAuth.length != 2) return false; if (fileBasicAuthData.containsKey(splitAuth[0])) { String storedHash = new String(Base64.decodeBase64(fileBasicAuthData.get(splitAuth[0]))); MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-256"); // $NON-NLS-1$ digest.update(splitAuth[1].getBytes()); String receivedHash = new String(digest.digest()); if (storedHash.equals(receivedHash)) { return true; } } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage(), e.getCause()); } } request .response() .headers() .add( "WWW-Authenticate", "Basic realm=\"" + config.getRealm() + "\""); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return false; }
/** * 由于Excel当中的单元格Cell存在类型,若获取类型错误就会产生异常, 所以通过此方法将Cell内容全部转换为String类型 * * @param cell * @return */ public static String getCellValue(Cell cell) { String str = null; if (cell != null) { switch (cell.getCellType()) { case Cell.CELL_TYPE_BLANK: str = ""; break; case Cell.CELL_TYPE_BOOLEAN: str = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: str = String.valueOf(cell.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) { str = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(cell.getDateCellValue()); } else { str = String.valueOf((long) cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_STRING: str = String.valueOf(cell.getStringCellValue()); break; default: str = null; break; } } return StringUtils.trim(str); }
/** * * * <li><b>Trim/Strip</b> - removes leading and trailing whitespace Strip-->Strips any of a set of * characters from the start and end of a String */ @Test public void testTrimStripStringUtils() { System.out.println(strOne + ":" + strOne.length()); System.out.println(StringUtils.trim(" " + strOne + " ").length()); System.out.println(StringUtils.strip(" " + strOne + " ").length()); System.out.println(StringUtils.strip("zabcyx", "xyz")); }
/** Returns the names and locations defined in this {@link Document}. */ public static Map<String, String> getSchemaLocations(Document doc) { Set<String> namespaces = new HashSet<String>(); namespaces.addAll(LocationAwareXmlReader.getNamespaces(doc)); String schemaLocation; try { schemaLocation = XmlUtil.xpathExtract(doc, "//@xsi:schemaLocation", objs); } catch (MarshallingException e) { throw new RuntimeException("Exception extracting xpath.", e); } Map<String, String> result = new HashMap<String, String>(); if (StringUtils.isNotBlank(schemaLocation)) { schemaLocation = StringUtils.trim(schemaLocation); String[] locations = schemaLocation.split("\\s+"); for (int i = 0, j = locations.length - 1; i < j; i++) { if (namespaces.contains(locations[i])) { result.put(locations[i], locations[i + 1]); } } } for (String r : result.keySet()) { namespaces.remove(r); } // if there are namespaces without namespace locations, load here. if (namespaces.size() > 0) { for (String namespace : namespaces) { result.put(namespace, null); } } return result; }
/** * Tries to parse the cell content as a number. * * @param cell the {@link TableCellBlock}. * @return cell content parsed as a {@link Number}. * @throws MacroExecutionException if the cell does not represent a number. */ private Number cellContentAsNumber(TableCellBlock cell) throws MacroExecutionException { String stringContent = cellContentAsString(cell); try { return NumberUtils.createNumber(StringUtils.trim(stringContent)); } catch (NumberFormatException ex) { throw new MacroExecutionException(String.format("Invalid number: [%s].", stringContent)); } }
/** * Utility method for extracting the Proxy Headers for a request. * * <p>The configuration option '{key}.proxyHeaders' is used to specify a multi-valued list of HTTP * headers to add to the outbound request to '{key}.uri'. * * <p>Example: * * <pre> * someservice.proxyHeaders=On-Behalf-Of: {wiscedupvi},Some-Other-Header: staticvalue * </pre> * * Implementers can specify either static values ('Some-Other-Header: staticvalue') or use * placeholders to relay {@link HttpServletRequest#getAttribute(String)} values ('On-Behalf-Of: * {wiscedupvi}') * * @param env * @param resourceKey * @param request * @return a potentially empty, but never null, {@link Multimap} of HTTP headers to add to the * outbound HTTP request. */ public static Multimap<String, String> getProxyHeaders( Environment env, String resourceKey, final HttpServletRequest request) { Multimap<String, String> headers = ArrayListMultimap.create(); String proxyHeadersValue = env.getProperty(resourceKey + ".proxyHeaders"); if (proxyHeadersValue != null) { String[] proxyHeaders = StringUtils.split(proxyHeadersValue, ","); for (String proxyHeader : proxyHeaders) { String[] tokens = StringUtils.trim(proxyHeader).split(":"); if (tokens.length == 2) { PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(START_PLACEHOLDER, END_PLACEHOLDER); String value = helper.replacePlaceholders( tokens[1], new PropertyPlaceholderHelper.PlaceholderResolver() { @Override public String resolvePlaceholder(String placeholderName) { Object attribute = request.getAttribute(placeholderName); if (attribute != null && attribute instanceof String) { return (String) attribute; } logger.warn( "configuration error: could not resolve placeholder for attribute {} as it's not a String, it's a {}", placeholderName, attribute != null ? attribute.getClass() : null); return null; } }); value = StringUtils.trim(value); if (value != null && !value.startsWith(START_PLACEHOLDER) && !value.endsWith(END_PLACEHOLDER)) { headers.put(tokens[0], value); } } else { logger.warn("configuration error: can't split {} on ':', ignoring", proxyHeader); } } } return headers; }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Profile profile = (Profile) request.getSession().getAttribute(Profile.TAG); if (profile == null) { System.out.println("Nie jesteś zalogowany."); response.sendRedirect("./changepass.jsp"); return; } String oldPassword = request.getParameter("oldPassword"); String newPassword = request.getParameter("newPassword"); if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) { System.out.println("oldPass lub newPass blank"); response.sendRedirect("./changepass.jsp"); return; } oldPassword = StringUtils.trim(oldPassword); newPassword = StringUtils.trim(newPassword); HttpSession session = request.getSession(); OpResult result = profileTools.changePassword(session, profile, oldPassword, newPassword); if (result.status == OpStatus.ERROR) { session.setAttribute(Profile.TAG, profile); response.sendRedirect("./changepass.jsp"); } else if (result.status == OpStatus.LOCK_LOGOUT) { response.sendRedirect("../index.jsp"); } else { response.sendRedirect("../index.jsp"); } }
@Override protected void beforeShowFeedInformation(Feed feed, Map<String, String> alternateFeedUrls) { super.beforeShowFeedInformation(feed, alternateFeedUrls); // remove HTML tags from descriptions if (BuildConfig.DEBUG) Log.d(TAG, "Removing HTML from shownotes"); if (feed.getItems() != null) { HtmlToPlainText formatter = new HtmlToPlainText(); for (FeedItem item : feed.getItems()) { if (item.getDescription() != null) { Document description = Jsoup.parse(item.getDescription()); item.setDescription(StringUtils.trim(formatter.getPlainText(description))); } } } }
@NonNull public static IConnector getConnector(final String geocodeInput) { // this may come from user input final String geocode = StringUtils.trim(geocodeInput); if (geocode == null) { return UNKNOWN_CONNECTOR; } if (isInvalidGeocode(geocode)) { return UNKNOWN_CONNECTOR; } for (final IConnector connector : CONNECTORS) { if (connector.canHandle(geocode)) { return connector; } } // in case of errors, take UNKNOWN to avoid null checks everywhere return UNKNOWN_CONNECTOR; }
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public User createUser(@NotNull User user, String password) { if (user.getId() != null) { throw new HiveException(Messages.ID_NOT_ALLOWED, BAD_REQUEST.getStatusCode()); } user.setLogin(StringUtils.trim(user.getLogin())); User existing = userDAO.findByLogin(user.getLogin()); if (existing != null) { throw new HiveException(Messages.DUPLICATE_LOGIN, FORBIDDEN.getStatusCode()); } if (StringUtils.isEmpty(password)) { throw new HiveException(Messages.PASSWORD_REQUIRED, BAD_REQUEST.getStatusCode()); } String salt = passwordService.generateSalt(); String hash = passwordService.hashPassword(password, salt); user.setPasswordSalt(salt); user.setPasswordHash(hash); user.setLoginAttempts(Constants.INITIAL_LOGIN_ATTEMPTS); hiveValidator.validate(user); return userDAO.create(user); }
private void populatePatientDetails(PatientVO patient, UserVO user) { setUsername(user.getUserName()); setFirstname(user.getFirstName()); setLastname(user.getLastName()); setUserStatus(user.getUserStatus().toString()); setMembershipType(patient.getMembershipType().toString()); setEmploymentType(patient.getEmploymentType().toString()); setEnrollmentMode(patient.getEnrollmentMode().toString()); setRelationshipType(patient.getRelationshipType().toString()); setLastLoginDate(user.getStrLastLoginDate()); setMembershipExpirationDate(patient.getStrMembershipExpirationDate()); String policyNo = patient.getPolicyNumber(); if (StringUtils.isNotEmpty(policyNo)) setPolicyNumber(patient.getPolicyNumber()); String priInsured = patient.getPrimaryInsured(); if (StringUtils.isNotEmpty(priInsured)) setPrimaryInsured(patient.getPrimaryInsured()); setInsuranceExpirationDate(patient.getStrInsuranceExpirationDate()); setDateOfBirth(patient.getStrDateOfBirth()); setIssuedBy(patient.getIssuedBy()); String fnote = patient.getNote(); if (StringUtils.isNotEmpty(fnote)) { setNote(StringUtils.trim(fnote.replaceAll("\\s*[\\r\\n]+\\s*", " "))); } setWebUrl(patient.getWebURL()); setSumAssured(String.valueOf(patient.getSumAssured())); setNote(patient.getNote()); setEnrollmentReferredBy(patient.getEnrollmentReferredBy()); setCompanyName(patient.getCompanyName()); setAge(calculateAge(new Date())); setPasswordExpirationDays(user.getPasswordExpirationDays() + " days"); setGender(user.getGender()); setImgFileName(patient.getImageFileName()); }
/** * Given the location of data, returns the feed. * * @param type type of the entity, is valid only for feeds. * @param instancePath location of the data * @return Feed Name, type of the data and cluster name. */ public FeedLookupResult reverseLookup(String type, String instancePath) { try { EntityType entityType = EntityType.getEnum(type); if (entityType != EntityType.FEED) { LOG.error("Reverse Lookup is not supported for entitytype: {}", type); throw new IllegalArgumentException("Reverse lookup is not supported for " + type); } instancePath = StringUtils.trim(instancePath); String instancePathWithoutSlash = instancePath.endsWith("/") ? StringUtils.removeEnd(instancePath, "/") : instancePath; // treat strings with and without trailing slash as same for purpose of searching e.g. // /data/cas and /data/cas/ should be treated as same. String instancePathWithSlash = instancePathWithoutSlash + "/"; FeedLocationStore store = FeedLocationStore.get(); Collection<FeedLookupResult.FeedProperties> feeds = new ArrayList<>(); Collection<FeedLookupResult.FeedProperties> res = store.reverseLookup(instancePathWithoutSlash); if (res != null) { feeds.addAll(res); } res = store.reverseLookup(instancePathWithSlash); if (res != null) { feeds.addAll(res); } FeedLookupResult result = new FeedLookupResult(APIResult.Status.SUCCEEDED, "SUCCESS"); FeedLookupResult.FeedProperties[] props = feeds.toArray(new FeedLookupResult.FeedProperties[0]); result.setElements(props); return result; } catch (IllegalArgumentException e) { throw FalconWebException.newException(e, Response.Status.BAD_REQUEST); } catch (Throwable throwable) { LOG.error("reverse look up failed", throwable); throw FalconWebException.newException(throwable, Response.Status.INTERNAL_SERVER_ERROR); } }
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public User updateUser(@NotNull Long id, UserUpdate userToUpdate) { User existing = userDAO.findById(id); if (existing == null) { throw new HiveException( String.format(Messages.USER_NOT_FOUND, id), NOT_FOUND.getStatusCode()); } if (userToUpdate == null) { return existing; } if (userToUpdate.getLogin() != null) { String newLogin = StringUtils.trim(userToUpdate.getLogin().getValue()); User withSuchLogin = userDAO.findByLogin(newLogin); if (withSuchLogin != null && !withSuchLogin.getId().equals(id)) { throw new HiveException(Messages.DUPLICATE_LOGIN, FORBIDDEN.getStatusCode()); } existing.setLogin(newLogin); } if (userToUpdate.getPassword() != null) { if (StringUtils.isEmpty(userToUpdate.getPassword().getValue())) { throw new HiveException(Messages.PASSWORD_REQUIRED, BAD_REQUEST.getStatusCode()); } String salt = passwordService.generateSalt(); String hash = passwordService.hashPassword(userToUpdate.getPassword().getValue(), salt); existing.setPasswordSalt(salt); existing.setPasswordHash(hash); } if (userToUpdate.getRole() != null) { existing.setRole(userToUpdate.getRoleEnum()); } if (userToUpdate.getStatus() != null) { existing.setStatus(userToUpdate.getStatusEnum()); } hiveValidator.validate(existing); return userDAO.update(existing); }
public static String formatTableData(String text, int col) { if ((col <= 1)) { String[] value = StringUtils.split(StringUtils.trim(text), ','); for (int i = 0; i < value.length; i++) { value[i] = value[i].trim(); } String result = ""; if (value.length == 0) { result = "0 , 0 , 0"; } else if (value.length == 1) { result = value[0] + " , 0 , 0"; } else if (value.length == 2) { result = value[0] + " , " + value[1] + " , 0"; } else { result = value[0] + " , " + value[1] + " , " + value[2]; } return "( " + result + " )"; } else if (col == 2) { return text + "ms"; } else { return text; } }
public static UnidadeSessao createUnidadeSessao(String logUnidadeSessao) throws ParseException { UnidadeSessao unidade; String[] linhas = logUnidadeSessao.split(ParserConstantes.caracterQuebraAtributo); String dataRegistro = obterValor(linhas, IndiceLogRadius.DATA_REGISTRO); String tipoUnidade = obterValor(linhas, IndiceLogRadius.TIPO_REGISTRO); if (ParserConstantes.INICIO_SESSAO.equalsIgnoreCase(StringUtils.trim(tipoUnidade))) { String codigoSessao = obterValor(linhas, IndiceLogRadius.COD_SESSAO_START); String usuario = obterValor(linhas, IndiceLogRadius.NOME_USUARIO_START); unidade = new UnidadeSessaoInicio( dataRegistro, parseLogValue(codigoSessao), parseLogValue(usuario)); } else { String codigoSessao = obterValor(linhas, IndiceLogRadius.COD_SESSAO_STOP); String usuario = obterValor(linhas, IndiceLogRadius.NOME_USUARIO_STOP); String duracao = obterValor(linhas, IndiceLogRadius.DURACAO); String bytesIn = obterValor(linhas, IndiceLogRadius.BYTES_IN); String bytesOut = obterValor(linhas, IndiceLogRadius.BYTES_OUT); String pktIn = obterValor(linhas, IndiceLogRadius.PKT_IN); String pktOut = obterValor(linhas, IndiceLogRadius.PKT_OUT); unidade = new UnidadeSessaoFim( dataRegistro, parseLogValue(codigoSessao), parseLogValue(usuario), parseLogValue(duracao), parseLogValue(bytesOut), parseLogValue(bytesIn), parseLogValue(pktOut), parseLogValue(pktIn)); } return unidade; }
// start properties public String getAccountNumber() { return StringUtils.trim(accountNumber); }
public String getIdNumber() { return StringUtils.trim(idNumber); }
public static void main(String[] args) { StringUtils.trim(null); System.out.println(NumberUtils.isDigits(StringUtils.trim("123 "))); System.out.println(NumberUtils.toInt(StringUtils.trim("123 "))); }
/** tcp server thread. */ public void run() { LOG.log(Level.INFO, "Ready receiving messages..."); while (Thread.currentThread() == runner) { if (tcpServer != null) { try { // check if client is available if (client != null && client.active()) { // do not send sound status to gui - very cpu intensive! // sendSoundStatus(); if ((count % 20) == 2 && Collector.getInstance().isRandomMode()) { sendStatusToGui(); } } Client c = tcpServer.available(); if (c != null && c.available() > 0) { // clean message String msg = lastMsg + StringUtils.replace(c.readString(), "\n", ""); // add replacement end string msg = StringUtils.replace(msg, FUDI_ALTERNATIVE_END_MARKER, FUDI_MSG_END_MARKER); msg = StringUtils.trim(msg); int msgCount = StringUtils.countMatches(msg, FUDI_MSG_END_MARKER); LOG.log(Level.INFO, "Got Message: <{0}> cnt: {1}", new Object[] {msg, msgCount}); // work around bug - the puredata gui sends back a message as soon we send one long delta = System.currentTimeMillis() - lastMessageSentTimestamp; if (delta < FLOODING_TIME) { LOG.log( Level.INFO, "Ignore message, flooding protection ({0}<{1})", new String[] {"" + delta, "" + FLOODING_TIME}); // delete message msgCount = 0; msg = ""; } // ideal, one message receieved if (msgCount == 1) { msg = StringUtils.removeEnd(msg, FUDI_MSG_END_MARKER); lastMsg = ""; processMessage(StringUtils.split(msg, ' ')); } else if (msgCount == 0) { // missing end of message... save it lastMsg = msg; } else { // more than one message received, split it // TODO: reuse partial messages lastMsg = ""; String[] msgs = msg.split(FUDI_MSG_END_MARKER); for (String s : msgs) { s = StringUtils.trim(s); s = StringUtils.removeEnd(s, FUDI_MSG_END_MARKER); processMessage(StringUtils.split(s, ' ')); } } } } catch (Exception e) { } } count++; try { Thread.sleep(50); } catch (InterruptedException e) { // Ignored } } }
private static void read(Path file, String... alternativeName) throws IOException { try (CSVReader csvReader = new CSVReader( new BufferedReader( new InputStreamReader(Files.newInputStream(file), Charset.forName("CP1252"))))) { String name; if (alternativeName.length > 0) { name = alternativeName[0]; } else { name = FilenameUtils.getBaseName(file.getFileName().toString()); } Set<Timeseries> dataset = Data.oldDataset(name); if (dataset == null) { dataset = Data.addOldDataset(name); } // Check all the CDIDs in the header row: // int duplicates = 0; String[] header = csvReader.readNext(); for (int i = 1; i < header.length; i++) { Timeseries timeseries = Data.timeseries(header[i]); if (timeseries == null) { timeseries = Data.addTimeseries(header[i]); } dataset.add(timeseries); timeseries.sourceDatasets.add(name); } // Now read the data - each row *may* contain one additional value // for each timeseries: String[] row; rows: while ((row = csvReader.readNext()) != null) { // There is a blank line between the data and the // additional information below, so stop reading there: if (row.length == 0 || StringUtils.isBlank(row[0])) { break rows; } // Add data to timeseries: String date = row[0]; Data.addDateOption(date); for (int i = 1; i < Math.min(header.length, row.length); i++) { if (StringUtils.isNotBlank(header[i]) && StringUtils.isNotBlank(row[i])) { Timeseries timeseries = Data.timeseries(header[i]); String cdid = header[i]; if (cdid == null) { // This one was marked as a duplicate continue; } String value = row[i]; TimeseriesValue timeseriesValue = new TimeseriesValue(); timeseriesValue.date = StringUtils.trim(date); timeseriesValue.value = StringUtils.trim(value); timeseriesValue.sourceDataset = name; timeseries.add(timeseriesValue); // if ("404".equals(value)) { // System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 404: " // + cdid + ": " + timeseriesValue + " (" + // timeseries.name + ")"); // } // Scale values if necessary: if (timeseries.cdid().equalsIgnoreCase("abmi")) { // System.out.println("ABMI: " + // timeseries.multiply()); } scale(timeseriesValue, timeseries); } } } // Print out some sanity-check information: for (int i = 1; i < header.length; i++) { if (StringUtils.isNotBlank(header[i])) { Timeseries timeseries = Data.timeseries(header[i]); if (timeseries.years.size() == 0 && timeseries.quarters.size() == 0 && timeseries.months.size() == 0) { System.out.println(timeseries + " has no data."); } } } // if (duplicates > 0) { // System.out.println(name + " contains " + dataset.size() + // " timeseries (" + duplicates + " duplicates)"); // } else { System.out.println(name + " contains " + dataset.size() + " timeseries"); // } } }
private static String parseLogValue(String codigoSessao) { return StringUtils.trim(codigoSessao.replaceAll("\"", StringUtils.EMPTY)); }
@Override public final void characters(final char[] ch, final int start, final int length) throws SAXException { final String text = StringUtils.trim(new String(ch, start, length)); content = isMultiline ? StringUtils.join(content, text) : text; }
/** * Reads the data from the given node and generates an AmazonResult from it. * * @param nodeObj * @return */ private static AmazonResult getResultFromNode(final Object nodeObj) { Node itemAttrNode = XPath.selectNode("./ItemAttributes", nodeObj); String title = getNodeContent(itemAttrNode, "./Title"); String copyType = getNodeContent(itemAttrNode, "./Binding"); if (copyTypeMatches.containsKey(copyType) == false) { if (Logger.isErrorEnabled() == true) { Logger.error("No copytype matching configured for amazon copytype: " + copyType); } return null; } copyType = copyTypeMatches.get(copyType); if (copyType.equals("BLURAY") == true && StringUtils.contains(title, "[Blu-ray 3D]") == true) { copyType = "BLURAY3D"; } title = StringUtils.substringBefore(title, "("); if (CollectionUtils.isEmpty(removeFromTitleList) == false) { for (String removeFromTitle : removeFromTitleList) { title = StringUtils.remove(title, removeFromTitle); } } title = StringUtils.trim(title); String asin = getNodeContent(nodeObj, "./ASIN"); String ean = getNodeContent(itemAttrNode, "./EAN"); String rating = getNodeContent(itemAttrNode, "./AudienceRating"); if (ageRatingMatches.containsKey(rating) == false) { if (Logger.isErrorEnabled() == true) { Logger.error("No agerating matching configured for amazon rating: " + rating); } } else { rating = ageRatingMatches.get(rating); } final Set<String> audioTypes = new HashSet<String>(); final NodeList audioTypeNodes = XPath.selectNodes("./Languages/Language[AudioFormat and Type = 'Original']", itemAttrNode); for (int i = 0; i < audioTypeNodes.getLength(); i++) { Node langItem = audioTypeNodes.item(i); final Node nameNode = XPath.selectNode("./Name", langItem); final Node formatNode = XPath.selectNode("./AudioFormat", langItem); String audioType = StringUtils.EMPTY; if (nameNode != null && StringUtils.isEmpty(nameNode.getTextContent()) == false) { audioType = nameNode.getTextContent(); } if (formatNode != null && StringUtils.isEmpty(formatNode.getTextContent()) == false) { if (StringUtils.isEmpty(audioType) == false) { audioType += " - "; } audioType += formatNode.getTextContent(); } audioTypes.add(audioType); } final NodeList otherLanguageNodes = XPath.selectNodes("./Languages/Language[Type = 'Published']/Name", itemAttrNode); for (int i = 0; i < otherLanguageNodes.getLength(); i++) { String language = otherLanguageNodes.item(i).getTextContent(); // check if the language is already known :) boolean alreadyKnown = false; for (final String audioType : audioTypes) { if (StringUtils.startsWithIgnoreCase(audioType, language) == true) { alreadyKnown = true; break; } } if (alreadyKnown == false) { audioTypes.add(language); } } final String imageUrl = getNodeContent(nodeObj, "./MediumImage/URL"); final AmazonResult result = new AmazonResult(title, rating, copyType, asin, ean, audioTypes, imageUrl); return result; }