List of usage examples for org.apache.commons.lang StringUtils substringBefore
public static String substringBefore(String str, String separator)
Gets the substring before the first occurrence of a separator.
From source file:com.amalto.core.query.user.UserQueryHelper.java
private static Boolean isRealXpath(MetadataRepository repository, String rightValueOrPath) { if (rightValueOrPath != null && rightValueOrPath.contains("/")) { //$NON-NLS-1$ String rightTypeName = StringUtils.substringBefore(rightValueOrPath, "/"); //$NON-NLS-1$ ComplexTypeMetadata metaData = repository.getComplexType(rightTypeName); if (repository.getComplexType(rightTypeName) != null) { String rightFieldName = StringUtils.substringAfter(rightValueOrPath, "/"); //$NON-NLS-1$ if (metaData.getField(rightFieldName) != null) { return true; }/*from www . j a v a 2 s . c o m*/ } } return false; }
From source file:info.magnolia.cms.filters.RangeSupportFilter.java
private HttpServletResponse wrapResponse(final HttpServletRequest request, final HttpServletResponse response) { return new HttpServletResponseWrapper(response) { /** default length is max. We hope that the underlying code will set proper content length as a header before we proceed serving some bytes. */ private int length = Integer.MAX_VALUE; private final Map<String, Object> headers = new HashMap<String, Object>(); private String eTag; private List<RangeInfo> ranges; private RangeInfo full; private ServletOutputStream stream; private PrintWriter writer; @Override// w ww. jav a 2s . c o m public void addDateHeader(String name, long date) { super.addDateHeader(name, date); this.headers.put(name, date); if ("Last-Modified".equalsIgnoreCase(name)) { lastModTime = date; } } @Override public void setDateHeader(String name, long date) { super.setDateHeader(name, date); this.headers.put(name, date); if ("Last-Modified".equalsIgnoreCase(name)) { lastModTime = date; } } @Override public void addHeader(String name, String value) { if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) { log.warn("content disposition enforced by underlying filter/servlet"); } super.addHeader(name, value); this.headers.put(name, value); } @Override public void setHeader(String name, String value) { if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) { log.warn("content disposition enforced by underlying filter/servlet"); } super.setHeader(name, value); this.headers.put(name, value); } @Override public void addIntHeader(String name, int value) { super.addIntHeader(name, value); this.headers.put(name, value); } @Override public void setIntHeader(String name, int value) { super.setIntHeader(name, value); this.headers.put(name, value); } @Override public void setContentLength(int len) { this.length = len; // do not propagate length up. We might not be able to change it once it is set. We will set it ourselves once we are ready to serve bytes. } @Override public ServletOutputStream getOutputStream() throws IOException { // make sure we set stream only once. Multiple calls to this method are allowed. if (this.stream == null) { ServletOutputStream stream = super.getOutputStream(); // wrap the response to filter out everything except desired range this.stream = addRangeSupportWrapper(request, response, stream); if (!isServeContent || this.stream == null) { // swallow output on head requests this.stream = new ServletOutputStream() { @Override public void write(int b) throws IOException { // do nothing, we do not write any output now } }; } } return stream; } private ServletOutputStream addRangeSupportWrapper(final HttpServletRequest request, final HttpServletResponse response, ServletOutputStream stream) throws IOException { if (!processContent(request, response)) { // we might have to return null stream instead as the previous method already called res.sendError(); return null; } if (headers.containsKey("Content-Range")) { // doesn't work for tomcat as it accesses underlying stream under our hands!!! log.debug("Range request was handled by underlying filter/servlet."); return stream; } if (ranges == null || ranges.isEmpty()) { // no op, serve all as usual log.debug("Didn't find any range to speak of. Serving all content as usual."); if (length != Integer.MAX_VALUE) { // set real length when we know it response.setContentLength(length); } } else if (ranges.size() == 1) { RangeInfo range = ranges.get(0); log.debug("Serving range [{}].", range); // setting 206 header is essential for some clients. The would abort if response is set to 200 response.setStatus(SC_PARTIAL_CONTENT); stream = new RangedOutputStream(stream, range); } else { log.error("Requested multiple ranges [{}].", ranges.size()); // TODO: add support for multiple ranges (sent as multipart request), for now just send error back response.setHeader("Content-Range", "bytes */" + length); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); // again we might have to return null stream after calling sendError() as the original stream might no longer be valid } return stream; } @Override public PrintWriter getWriter() throws IOException { if (!wrapWriter) { return super.getWriter(); } if (this.writer == null) { this.writer = new PrintWriter(new OutputStreamWriter(getOutputStream())); } return writer; } private boolean processContent(HttpServletRequest request, HttpServletResponse response) throws IOException { log.debug("Serving binary on uri {} was last modified at {}", new Object[] { request.getRequestURI(), lastModTime }); if (!isRequestValid(request, response)) { log.debug("Skipping request {} since it doesn't require body", new Object[] { request.getRequestURI() }); return false; } if (!processRange(request)) { log.debug("Could not process range of request {}", new Object[] { request.getRequestURI() }); return false; } return true; } private boolean processRange(HttpServletRequest request) throws IOException { full = new RangeInfo(0, length - 1, length); ranges = new ArrayList<RangeInfo>(); String range = request.getHeader("Range"); // Valid range header format is "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return false; } // If-Range header must match ETag or be greater then LastModified. If not, then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModTime) { ranges.add(full); } } catch (IllegalArgumentException ignore) { // happens when if-range contains something else then date ranges.add(full); } } // in case there were no invalid If-Range headers, then look at requested byte ranges. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { int start = intSubstring(StringUtils.substringBefore(part, "-")); int end = intSubstring(StringUtils.substringAfter(part, "-")); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Is range valid? if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return false; } // Add range. ranges.add(new RangeInfo(start, end, length)); } } response.setHeader("ETag", eTag); if (ranges.size() == 1) { RangeInfo r = ranges.get(0); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.totalLengthOfServedBinary); length = r.lengthOfRange; } return true; } private int intSubstring(String value) { return value.length() > 0 ? Integer.parseInt(value) : -1; } @Override public void flushBuffer() throws IOException { if (writer != null) { writer.flush(); } if (stream != null) { stream.flush(); } super.flushBuffer(); } private boolean isRequestValid(HttpServletRequest request, HttpServletResponse response) throws IOException { String fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/"); eTag = fileName + "_" + length + "_" + lastModTime; // If-None-Match header should contain "*" or ETag. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setHeader("ETag", eTag); // Required in 304. log.debug("Returning {} on header If-None-Match", HttpServletResponse.SC_NOT_MODIFIED); response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; } // If-Modified-Since header must be greater than LastModified. ignore if If-None-Match header exists long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModTime) { response.setHeader("ETag", eTag); // Required in 304. // 304 response should contain Date header unless running on timeless server (see 304 response docu) response.addDateHeader("Date", lastModTime); log.debug("Returning {} on header If-Modified-Since", HttpServletResponse.SC_NOT_MODIFIED); response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; } // If-Match header should contain "*" or ETag. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { log.debug("Returning {} on header If-Match", HttpServletResponse.SC_PRECONDITION_FAILED); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } // If-Unmodified-Since header must be greater than LastModified. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModTime) { log.debug("Returning {} on header If-Unmodified-Since", HttpServletResponse.SC_PRECONDITION_FAILED); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } log.debug("Passed all precondition checkes for request {}", request.getRequestURI()); return true; } }; }
From source file:com.hangum.tadpole.rdb.core.viewers.object.sub.utils.TadpoleObjectQuery.java
/** * @param userDB/*from w ww . j a v a 2 s .c om*/ * @param strObject * @return */ public static TableDAO getTable(UserDBDAO userDB, String strObject) throws Exception { TableDAO tableDao = null; List<TableDAO> showTables = new ArrayList<TableDAO>(); if (userDB.getDBDefine() == DBDefine.TAJO_DEFAULT) { List<TableDAO> tmpShowTables = new TajoConnectionManager().tableList(userDB); for (TableDAO dao : tmpShowTables) { if (dao.getName().equals(strObject)) { showTables.add(dao); break; } } } else if (userDB.getDBDefine() == DBDefine.HIVE_DEFAULT | userDB.getDBDefine() == DBDefine.HIVE2_DEFAULT) { SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB); List<TableDAO> tmpShowTables = sqlClient.queryForList("tableList", userDB.getDb()); //$NON-NLS-1$ for (TableDAO dao : tmpShowTables) { if (dao.getName().equals(strObject)) { showTables.add(dao); break; } } } else if (userDB.getDBDefine() == DBDefine.ALTIBASE_DEFAULT) { Map<String, Object> mapParam = new HashMap<String, Object>(); mapParam.put("user_name", StringUtils.substringBefore(strObject, ".")); //$NON-NLS-1$ mapParam.put("table_name", StringUtils.substringAfter(strObject, ".")); //$NON-NLS-1$ SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB); showTables = sqlClient.queryForList("table", mapParam); //$NON-NLS-1$ } else { Map<String, Object> mapParam = new HashMap<String, Object>(); mapParam.put("db", userDB.getDb()); //$NON-NLS-1$ mapParam.put("name", strObject); //$NON-NLS-1$ SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB); showTables = sqlClient.queryForList("table", mapParam); //$NON-NLS-1$ } /** filter . */ showTables = DBAccessCtlManager.getInstance().getTableFilter(showTables, userDB); if (!showTables.isEmpty()) { tableDao = showTables.get(0); tableDao.setSysName(SQLUtil.makeIdentifierName(userDB, tableDao.getName())); return tableDao; } else { return null; } }
From source file:its.ConnectedModeTest.java
@Test public void globalUpdate() throws Exception { updateGlobal();/*ww w . j a v a 2s .c o m*/ assertThat(engine.getState()).isEqualTo(State.UPDATED); assertThat(engine.getGlobalStorageStatus()).isNotNull(); assertThat(engine.getGlobalStorageStatus().isStale()).isFalse(); assertThat(engine.getGlobalStorageStatus().getServerVersion()) .startsWith(StringUtils.substringBefore(ORCHESTRATOR.getServer().version().toString(), "-")); if (supportHtmlDesc()) { assertThat(engine.getRuleDetails("squid:S106").getHtmlDescription()) .contains("When logging a message there are"); } else { assertThat(engine.getRuleDetails("squid:S106").getHtmlDescription()) .contains("Rule descriptions are only available in SonarLint with SonarQube 5.1+"); } assertThat(engine.getModuleStorageStatus(PROJECT_KEY_JAVA)).isNull(); }
From source file:eionet.cr.util.Util.java
/** * * @param acceptLanguageHeader/*from w ww . j a v a 2 s. c om*/ * @return */ public static List<String> getAcceptedLanguages(String acceptLanguageHeader) { final HashMap<String, Double> languageMap = new LinkedHashMap<String, Double>(); if (!StringUtils.isBlank(acceptLanguageHeader)) { String[] languageStrings = StringUtils.split(acceptLanguageHeader, ','); for (int i = 0; i < languageStrings.length; i++) { String languageString = languageStrings[i].trim(); String languageCode = StringUtils.substringBefore(languageString, ";").trim(); if (!StringUtils.isEmpty(languageCode)) { String languageCodeUnrefined = StringUtils.split(languageCode, "-_")[0]; String qualityString = StringUtils.substringAfter(languageString, ";").trim(); double qualityValue = NumberUtils.toDouble(StringUtils.substringAfter(qualityString, "="), 1.0d); Double existingQualityValue = languageMap.get(languageCodeUnrefined); if (existingQualityValue == null || qualityValue > existingQualityValue) { languageMap.put(languageCodeUnrefined, Double.valueOf(qualityValue)); } } } } ArrayList<String> result = new ArrayList<String>(languageMap.keySet()); Collections.sort(result, new Comparator() { @Override public int compare(Object o1, Object o2) { return (-1) * languageMap.get(o1).compareTo(languageMap.get(o2)); } }); if (!result.contains("en")) { result.add("en"); } result.add(""); return result; }
From source file:com.hangum.tadpole.rdb.core.viewers.object.sub.rdb.table.index.TadpoleIndexesComposite.java
/** * index ./* www. j a v a 2 s . c om*/ * @param strObjectName */ public void refreshIndexes(final UserDBDAO userDB, boolean boolRefresh, String strObjectName) { if (!boolRefresh) if (listIndexes != null) return; this.userDB = userDB; try { SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB); HashMap<String, String> map = new HashMap<String, String>(); if (userDB.getDBDefine() == DBDefine.ALTIBASE_DEFAULT) { map.put("user_name", StringUtils.substringBefore(tableDao.getName(), ".")); //$NON-NLS-1$ map.put("table_name", StringUtils.substringAfter(tableDao.getName(), ".")); //$NON-NLS-1$ } else { map.put("table_schema", userDB.getDb()); map.put("table_name", tableDao.getName()); } listIndexes = sqlClient.queryForList("indexList", map); //$NON-NLS-1$ indexTableViewer.setInput(listIndexes); indexTableViewer.refresh(); TableUtil.packTable(indexTableViewer.getTable()); // select tabitem getTabFolderObject().setSelection(tbtmIndex); selectDataOfTable(strObjectName); } catch (Exception e) { logger.error("index refresh", e); //$NON-NLS-1$ Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$ ExceptionDetailsErrorDialog.openError(getSite().getShell(), Messages.get().Error, Messages.get().ExplorerViewer_1, errStatus); //$NON-NLS-1$ } }
From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.composite.MSSQLLoginComposite.java
@Override public boolean makeUserDBDao(boolean isTest) { if (!isValidateInput(isTest)) return false; String dbUrl = ""; String strHost = StringUtils.trimToEmpty(textHost.getText()); String strPort = StringUtils.trimToEmpty(textPort.getText()); String strDB = StringUtils.trimToEmpty(textDatabase.getText()); if (StringUtils.contains(strHost, "\\")) { String strIp = StringUtils.substringBefore(strHost, "\\"); String strInstance = StringUtils.substringAfter(strHost, "\\"); dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strIp, strPort, strDB) + ";instance=" + strInstance;//from w ww .j ava2 s .co m } else if (StringUtils.contains(strHost, "/")) { String strIp = StringUtils.substringBefore(strHost, "/"); String strInstance = StringUtils.substringAfter(strHost, "/"); dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strIp, strPort, strDB) + ";instance=" + strInstance; } else { dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strHost, strPort, strDB); } if (!"".equals(textJDBCOptions.getText())) { if (StringUtils.endsWith(dbUrl, ";")) { dbUrl += textJDBCOptions.getText(); } else { dbUrl += ";" + textJDBCOptions.getText(); } } if (logger.isDebugEnabled()) logger.debug("[db url]" + dbUrl); userDB = new UserDBDAO(); userDB.setDbms_type(getSelectDB().getDBToString()); userDB.setUrl(dbUrl); userDB.setUrl_user_parameter(textJDBCOptions.getText()); userDB.setDb(StringUtils.trimToEmpty(textDatabase.getText())); userDB.setGroup_name(StringUtils.trimToEmpty(preDBInfo.getComboGroup().getText())); userDB.setDisplay_name(StringUtils.trimToEmpty(preDBInfo.getTextDisplayName().getText())); String dbOpType = PublicTadpoleDefine.DBOperationType .getNameToType(preDBInfo.getComboOperationType().getText()).name(); userDB.setOperation_type(dbOpType); if (dbOpType.equals(PublicTadpoleDefine.DBOperationType.PRODUCTION.name()) || dbOpType.equals(PublicTadpoleDefine.DBOperationType.BACKUP.name())) { userDB.setIs_lock(PublicTadpoleDefine.YES_NO.YES.name()); } userDB.setHost(StringUtils.trimToEmpty(textHost.getText())); userDB.setPort(StringUtils.trimToEmpty(textPort.getText())); userDB.setUsers(StringUtils.trimToEmpty(textUser.getText())); userDB.setPasswd(StringUtils.trimToEmpty(textPassword.getText())); // ? ?? ? . userDB.setRole_id(PublicTadpoleDefine.USER_ROLE_TYPE.ADMIN.toString()); // others connection . setOtherConnectionInfo(); return true; }
From source file:com.sfs.whichdoctor.dao.onlineapplication.BasicTrainingOnlineApplicationHandler.java
/** * Load person details from the XML application. * * @param root the root of the XML application * @return the person bean//w w w . ja v a 2 s . co m */ private PersonBean loadPersonDetails(final Element root) { PersonBean person = new PersonBean(); Element pd = root.getChild("personaldetails"); try { String name = pd.getChildText("firstname").trim(); person.setFirstName(name); if (StringUtils.contains(name, " ")) { // Split the first and middle names person.setFirstName(StringUtils.substringBefore(name, " ")); person.setMiddleName(StringUtils.substringAfter(name, " ")); } } catch (Exception e) { dataLogger.error("Error parsing firstname: " + e.getMessage()); } try { person.setPreferredName(pd.getChildText("prefname").trim()); } catch (Exception e) { dataLogger.error("Error parsing prefname: " + e.getMessage()); } try { person.setLastName(pd.getChildText("lastname").trim()); } catch (Exception e) { dataLogger.error("Error parsing lastname: " + e.getMessage()); } try { String birthDate = pd.getChildText("dob").trim(); person.setBirthDate(parseDate(birthDate)); } catch (Exception e) { dataLogger.error("Error parsing dob: " + e.getMessage()); } try { String gender = pd.getChildText("gender").trim(); person.setGender(WordUtils.capitalizeFully(gender)); } catch (Exception e) { dataLogger.error("Error parsing lastname: " + e.getMessage()); } person.setTitle("Dr"); return person; }
From source file:com.sfs.whichdoctor.dao.OnlineApplicationDAOImpl.java
/** * Gets the next step for the application. * * @param onlineApplication the online application * @return the next step// w w w . j a va 2 s .c o m */ public final String[] getNextStep(final OnlineApplicationBean onlineApplication) { String step = ""; String recordNumber = ""; Collection<ObjectTypeBean> objectTypes = new ArrayList<ObjectTypeBean>(); Map<Integer, String> statuses = new TreeMap<Integer, String>(); try { objectTypes = this.getObjectTypeDAO().load("Application Status"); } catch (SFSDaoException sfe) { dataLogger.error("Error loading list of application statuses: " + sfe.getMessage()); } String type = onlineApplication.getType(); String currentStatus = onlineApplication.getStatus(); String currentRecordId = onlineApplication.getRecordNumber(); if (objectTypes != null) { for (ObjectTypeBean objectType : objectTypes) { if (StringUtils.equalsIgnoreCase(type, objectType.getClassName())) { // This is of the type we are interested in String recordId = ""; if (StringUtils.isNotBlank(objectType.getAbbreviation())) { recordId = objectType.getAbbreviation().trim(); } int orderId = (int) objectType.getValue(); String key = objectType.getName() + "_" + recordId; statuses.put(orderId, key); if (dataLogger.isDebugEnabled()) { dataLogger.debug("Status id: " + orderId); dataLogger.debug("Status key: " + key); } } } } Document xml = null; try { xml = parseXmlApplication(onlineApplication.getApplicationXml()); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error parsing application XML: " + wde.getMessage()); } boolean setNextValue = false; for (Integer orderId : statuses.keySet()) { String value = statuses.get(orderId); String nextStep = StringUtils.substringBefore(value, "_"); String recordId = StringUtils.substringAfter(value, "_"); if (dataLogger.isDebugEnabled()) { dataLogger.debug("Status id: " + orderId); dataLogger.debug("Status raw value: " + value); dataLogger.debug("Next status step: " + nextStep); dataLogger.debug("Record id: '" + recordId + "'"); dataLogger.debug("Current record id: '" + currentRecordId + "'"); } // If the currentStatus == value then the next value is the step if (StringUtils.equalsIgnoreCase(currentStatus, nextStep) && StringUtils.equalsIgnoreCase(currentRecordId, recordId)) { setNextValue = true; dataLogger.debug(nextStep + " is the current status value"); } else { dataLogger.debug("Validating: '" + nextStep + "' - '" + recordId + "'"); // If nextValue is set the next step to the value if (setNextValue && validateNextStep(xml, nextStep, onlineApplication.getType(), recordId)) { step = nextStep; recordNumber = recordId; // Reset to false setNextValue = false; } } if (dataLogger.isDebugEnabled()) { dataLogger.debug("Loop next step value: " + step); dataLogger.debug("Loop record id value: " + recordNumber); } } String[] statusDetails = { step, recordNumber }; return statusDetails; }
From source file:captureplugin.CapturePlugin.java
@Override public boolean receivePrograms(Program[] programArr, ProgramReceiveTarget receiveTarget) { if (receiveTarget == null || receiveTarget.getTargetId() == null || receiveTarget.getTargetId().indexOf('#') == -1) { return false; }/*w w w . j a va 2s . co m*/ String id = receiveTarget.getTargetId(); String deviceid = StringUtils.substringBefore(id, "#"); String command = id.substring(id.indexOf('#')); for (DeviceIf device : mConfig.getDevices()) { if (device.getId().equals(deviceid)) { if (command.equals(REMOVE)) { for (Program program : programArr) { if (device.isInList(program)) { device.remove(getParentFrame(), program); } } updateMarkedPrograms(); return true; } else if (command.equals(RECORD)) { ArrayList<Program> successfullPrograms = new ArrayList<Program>(programArr.length); for (Program program : programArr) { if (device.add(getParentFrame(), program)) { successfullPrograms.add(program); } } device.sendProgramsToReceiveTargets( successfullPrograms.toArray(new Program[successfullPrograms.size()])); updateMarkedPrograms(); return true; } if (command.startsWith("#_")) { command = command.substring(2); String[] cmdstr = device.getAdditionalCommands(); for (int i = 0; i < cmdstr.length; i++) { if (cmdstr[i].equals(command)) { for (Program program : programArr) { device.executeAdditionalCommand(getParentFrame(), i, program); } return true; } } } } } return false; }