List of usage examples for org.apache.commons.lang StringUtils contains
public static boolean contains(String str, String searchStr)
Checks if String contains a search String, handling null
.
From source file:com.adobe.acs.commons.wcm.impl.AemEnvironmentIndicatorFilter.java
@Override @SuppressWarnings("squid:S3776") public final void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) { filterChain.doFilter(servletRequest, servletResponse); return;/*from ww w .j av a2s. c om*/ } final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; if (!this.accepts(request)) { filterChain.doFilter(request, response); return; } final BufferingResponse capturedResponse = new BufferingResponse(response); filterChain.doFilter(request, capturedResponse); boolean doInclude = true; if (ArrayUtils.isNotEmpty(excludedWCMModes)) { // Test for configured WCM modes, where the indicators are not displayed WCMMode wcmmode = extractFromRequest(request); if (wcmmode != null) { for (String m : excludedWCMModes) { if (StringUtils.equalsIgnoreCase(wcmmode.name(), m)) { doInclude = false; break; } } } else { // No wcmmode could be extracted from the request } } // Get contents final String contents = capturedResponse.getContents(); if (doInclude && contents != null && StringUtils.contains(response.getContentType(), "html")) { final int bodyIndex = contents.indexOf("</body>"); if (bodyIndex != -1) { final PrintWriter printWriter = response.getWriter(); printWriter.write(contents.substring(0, bodyIndex)); if (StringUtils.isNotBlank(css)) { printWriter.write("<style>" + css + " </style>"); printWriter.write("<div id=\"" + DIV_ID + "\">" + innerHTML + "</div>"); } if (StringUtils.isNotBlank(titlePrefix)) { printWriter.printf(TITLE_UPDATE_SCRIPT, titlePrefix); } printWriter.write(contents.substring(bodyIndex)); return; } } if (contents != null) { response.getWriter().write(contents); } }
From source file:cec.easyshop.storefront.controllers.misc.StoreSessionController.java
protected String getReturnRedirectUrlForUrlEncoding(final HttpServletRequest request, final String old, final String current) { final String originalReferer = (String) request.getSession() .getAttribute(StorefrontFilter.ORIGINAL_REFERER); if (StringUtils.isNotBlank(originalReferer)) { return REDIRECT_PREFIX + StringUtils.replace(originalReferer, "/" + old + "/", "/" + current + "/"); }//from w w w .j a v a 2s . c o m String referer = StringUtils.remove(request.getRequestURL().toString(), request.getServletPath()); if (!StringUtils.endsWith(referer, "/")) { referer = referer + "/"; } if (referer != null && !referer.isEmpty() && StringUtils.contains(referer, "/" + old + "/")) { return REDIRECT_PREFIX + StringUtils.replace(referer, "/" + old + "/", "/" + current + "/"); } return REDIRECT_PREFIX + referer; }
From source file:com.haulmont.cuba.gui.app.security.constraint.edit.ConstraintEditor.java
protected List<Suggestion> requestHint(SourceCodeEditor sender, String text, int cursorPosition) { if (entityName.getValue() == null) { return Collections.emptyList(); }/*from w ww .j av a 2 s. c om*/ String joinStr = joinClause.getValue(); String whereStr = whereClause.getValue(); // the magic entity name! The length is three character to match "{E}" length in query String entityNameAlias = "a39"; int position = 0; StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("select "); queryBuilder.append(entityNameAlias); queryBuilder.append(" from "); queryBuilder.append(entities.get(entityName.getValue())); queryBuilder.append(" "); queryBuilder.append(entityNameAlias); queryBuilder.append(" "); if (StringUtils.isNotEmpty(joinStr)) { if (sender == joinClause) { position = queryBuilder.length() + cursorPosition - 1; } if (!StringUtils.containsIgnoreCase(joinStr, "join") && !StringUtils.contains(joinStr, ",")) { queryBuilder.append("join ").append(joinStr); position += "join ".length(); } else { queryBuilder.append(joinStr); } } if (StringUtils.isNotEmpty(whereStr)) { if (sender == whereClause) { position = queryBuilder.length() + " WHERE ".length() + cursorPosition - 1; } queryBuilder.append(" WHERE ").append(whereStr); } String query = queryBuilder.toString(); query = query.replace("{E}", entityNameAlias); List<Suggestion> suggestions = JpqlSuggestionFactory.requestHint(query, position, sender.getAutoCompleteSupport(), cursorPosition); addSpecificSuggestions(sender, text, cursorPosition, suggestions); return suggestions; }
From source file:de.awtools.basic.file.AWToolsFileUtils.java
/** * Siehe die Beschreibung in Methode/* w w w. j av a 2 s. c om*/ * {@link #findFiles(java.io.File, java.lang.String, java.lang.String)}. * * @param basePath Basisverzeichnis. * @param fileName Die gesuchte Datei. * @return Eine Liste der gefundenen Dateien. * * @see #findFiles(java.io.File, java.lang.String, java.lang.String) */ public static List<File> findFiles(final File basePath, final String fileName) { String relativePath = ""; String realFileName = fileName; if ((StringUtils.contains(fileName, "/"))) { relativePath = StringUtils.substringBeforeLast(fileName, "/"); realFileName = StringUtils.substringAfterLast(fileName, "/"); } if (log.isDebugEnabled()) { log.debug("basePath ......: " + basePath); log.debug("relativePath ..: " + relativePath); log.debug("realFileName ..: " + realFileName); } return AWToolsFileUtils.findFiles(basePath, relativePath, realFileName); }
From source file:com.edgenius.wiki.render.MarkupUtil.java
/** * Simply replace all filter keywords with leading odd number slash "\" by Hiding character, now it is "HH". * It is useful while only detect if the valid filter exist or not, or get length Index value of valid filter (as the * replacement does not change the content length) * @param text//from ww w. jav a 2 s. c o m * @return */ public static CharSequence hideEscapeMarkup(String input) { if (input == null) return new StringBuilder(); int len = input.length(); StringBuilder sb = new StringBuilder(); int slash = 0; boolean odd; int currLen; for (int idx = 0; idx < len; idx++) { char c = input.charAt(idx); if (c == '\\') { slash++; sb.append(c); continue; } odd = slash % 2 != 0; //even ">" is not filter pattern keyword, but it use in markup link. // For example[view has \\> char>link],here must escape \> to entity, then in LinkFilter could correctly convert \&#(int >); // to ">", as it will call unescapeMarkupLink() to remove another "\" if (StringUtils.contains(FilterRegxConstants.FILTER_KEYWORD + ">", c) && odd) { currLen = sb.length() - 1; sb.deleteCharAt(currLen); //delete last slash sb.append(HIDE_TOKEN); } else sb.append(c); slash = 0; } return sb; }
From source file:com.cws.esolutions.security.config.xml.SecurityConfigurationData.java
public static final String expandEnvVars(final String value) { final String methodName = SecurityConfigurationData.CNAME + "#expandEnvVars(final String value)"; if (DEBUG) {//from ww w. jav a 2 s . c om DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", value); } String returnValue = null; if (!(StringUtils.contains(value, "$"))) { return null; } final Properties sysProps = System.getProperties(); final Map<String, String> envMap = System.getenv(); final String text = StringUtils.replaceEachRepeatedly(value.split("=")[1].trim(), new String[] { "${", "}" }, new String[] { "", "" }).trim(); if (DEBUG) { DEBUGGER.debug("Properties sysProps: {}", sysProps); DEBUGGER.debug("Map<String, String> envMap: {}", envMap); DEBUGGER.debug("String text: {}", text); } for (Entry<Object, Object> property : sysProps.entrySet()) { if (DEBUG) { DEBUGGER.debug("Entry<Object, Object> property: {}", property); } String key = (String) property.getKey(); if (DEBUG) { DEBUGGER.debug("String key: {}", key); } if (StringUtils.equals(key.trim(), text)) { returnValue = sysProps.getProperty(key.trim()); break; } } for (Entry<String, String> entry : envMap.entrySet()) { if (DEBUG) { DEBUGGER.debug("Entry<String, String> entry: {}", entry); } String key = entry.getKey(); if (DEBUG) { DEBUGGER.debug("String key: {}", key); } if (StringUtils.equals(key.trim(), text)) { returnValue = entry.getValue(); break; } } if (DEBUG) { DEBUGGER.debug("String returnValue: {}", returnValue); } return returnValue; }
From source file:com.epam.trade.storefront.controllers.misc.StoreSessionController.java
protected String getReturnRedirectUrlForUrlEncoding(final HttpServletRequest request, final String old, final String current) { final String originalReferer = (String) request.getAttribute(StorefrontFilter.ORIGINAL_REFERER); if (StringUtils.isNotBlank(originalReferer)) { return REDIRECT_PREFIX + StringUtils.replace(originalReferer, "/" + old + "/", "/" + current + "/"); }// w w w .j ava2 s . com String referer = StringUtils.remove(request.getRequestURL().toString(), request.getServletPath()); if (!StringUtils.endsWith(referer, "/")) { referer = referer + "/"; } if (referer != null && !referer.isEmpty() && StringUtils.contains(referer, "/" + old + "/")) { return REDIRECT_PREFIX + StringUtils.replace(referer, "/" + old + "/", "/" + current + "/"); } return REDIRECT_PREFIX + referer; }
From source file:net.kamhon.ieagle.dao.JpaDao.java
@Override public void findForDatagrid(DatagridModel<T> datagridModel, String alias, String queryString, Object... objectArray) {/* ww w . j a v a2 s . c o m*/ queryString = convertJpaPositionParams(queryString); Assert.isTrue(StringUtils.isNotBlank(alias), "The alias can not be BLANK!!"); Assert.isTrue(StringUtils.isNotBlank(queryString), "The queryString can not be BLANK!!"); if (CollectionUtil.isNotEmpty(datagridModel.getFilters())) { Assert.doesNotContain(queryString, BasicDao.FILTER_PARAMS, "The " + BasicDao.FILTER_PARAMS + " is not found in Query [" + queryString + "] if FILTERS is not EMPTY!!"); } /************************* * END VALIDATION ************************/ String finalQuery = queryString.trim(); List<Object> params = new ArrayList<Object>(); if (objectArray != null) { if (objectArray.length == 1 && objectArray[0] instanceof List) params = (List<Object>) objectArray[0]; else params = Arrays.asList(objectArray); } if (CollectionUtil.isNotEmpty(datagridModel.getFilters())) { for (Filter filter : datagridModel.getFilters()) { if (filter != null) throw new DataException("The Filter features still not implemented yet"); } } List<Object> countParams = new ArrayList<Object>(params); String countQuery = "SELECT COUNT(" + alias + ") "; if (finalQuery.toUpperCase().startsWith("SELECT")) { int ind = finalQuery.toUpperCase().indexOf("FROM"); countQuery += finalQuery.substring(ind); } else { countQuery += finalQuery; } if (!datagridModel.isDisableSort() && CollectionUtil.isNotEmpty(datagridModel.getSorters())) { if (StringUtils.contains(finalQuery.toUpperCase(), "ORDER BY")) { finalQuery += ", "; } else { finalQuery += " ORDER BY "; } for (Iterator<Sorter> iter = datagridModel.getSorters().iterator(); iter.hasNext();) { Sorter sorter = iter.next(); finalQuery += alias + "." + sorter.getColumn() + " " + sorter.getDirection(); if (iter.hasNext()) { finalQuery += ", "; } } } // log.debug("countParams = " + countParams); // log.debug("countQuery = " + countQuery); // log.debug("params = " + params); // log.debug("finalQuery = " + finalQuery); List<T> result = (List<T>) findBlock(finalQuery, datagridModel.getRecordOffset(), datagridModel.getPageSize(), params.toArray()); datagridModel.setRecords(result); Long count = (Long) this.findUnique(countQuery, countParams.toArray()); datagridModel.setTotalRecords(count); }
From source file:com.cws.esolutions.security.filters.SessionAuthenticationFilter.java
public void doFilter(final ServletRequest sRequest, final ServletResponse sResponse, final FilterChain filterChain) throws IOException, ServletException { final String methodName = SessionAuthenticationFilter.CNAME + "#doFilter(final ServletRequest sRequest, final ServletResponse sResponse, final FilterChain filterChain) throws IOException, ServletException"; if (DEBUG) {/* w w w. j av a2s .c om*/ DEBUGGER.debug(methodName); DEBUGGER.debug("ServletRequest: {}", sRequest); DEBUGGER.debug("ServletResponse: {}", sResponse); } final HttpServletRequest hRequest = (HttpServletRequest) sRequest; final HttpServletResponse hResponse = (HttpServletResponse) sResponse; final HttpSession hSession = hRequest.getSession(false); final String requestURI = hRequest.getRequestURI(); final String passwdPage = hRequest.getContextPath() + this.passwordURI; final StringBuilder redirectPath = new StringBuilder().append(hRequest.getContextPath() + this.loginURI) .append("?vpath=" + requestURI); if (DEBUG) { DEBUGGER.debug("HttpServletRequest: {}", hRequest); DEBUGGER.debug("HttpServletResponse: {}", hResponse); DEBUGGER.debug("HttpSession: {}", hSession); DEBUGGER.debug("RequestURI: {}", requestURI); DEBUGGER.debug("passwdPage: {}", passwdPage); DEBUGGER.debug("redirectPath: {}", redirectPath); DEBUGGER.debug("Dumping session content:"); Enumeration<?> sessionEnumeration = hSession.getAttributeNames(); while (sessionEnumeration.hasMoreElements()) { String element = (String) sessionEnumeration.nextElement(); Object value = hSession.getAttribute(element); DEBUGGER.debug("Attribute: {}; Value: {}", element, value); } DEBUGGER.debug("Dumping request content:"); Enumeration<?> requestEnumeration = hRequest.getAttributeNames(); while (requestEnumeration.hasMoreElements()) { String element = (String) requestEnumeration.nextElement(); Object value = hRequest.getAttribute(element); DEBUGGER.debug("Attribute: {}; Value: {}", element, value); } DEBUGGER.debug("Dumping request parameters:"); Enumeration<?> paramsEnumeration = hRequest.getParameterNames(); while (paramsEnumeration.hasMoreElements()) { String element = (String) paramsEnumeration.nextElement(); Object value = hRequest.getParameter(element); DEBUGGER.debug("Parameter: {}; Value: {}", element, value); } } if (StringUtils.equals(this.loginURI, requestURI)) { if (DEBUG) { DEBUGGER.debug("Request authenticated. No action taken !"); } filterChain.doFilter(sRequest, sResponse); return; } if ((this.ignoreURIs != null) && (this.ignoreURIs.length != 0)) { if (Arrays.asList(this.ignoreURIs).contains("ALL")) { if (DEBUG) { DEBUGGER.debug("ALL URIs are ignored. Breaking ..."); } filterChain.doFilter(sRequest, sResponse); return; } // hostname isnt in ignore list for (String uri : this.ignoreURIs) { uri = hRequest.getContextPath().trim() + uri.trim(); if (DEBUG) { DEBUGGER.debug(uri); DEBUGGER.debug(requestURI); } if (StringUtils.contains(requestURI, uri)) { // ignore if (DEBUG) { DEBUGGER.debug("URI matched to ignore list - breaking out"); } filterChain.doFilter(sRequest, sResponse); return; } } } if (hRequest.isRequestedSessionIdFromURL()) { ERROR_RECORDER.error("Session found is from URL. Redirecting request to " + hRequest.getContextPath() + this.loginURI); // invalidate the session hRequest.getSession(false).invalidate(); hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT); hSession.invalidate(); hResponse.sendRedirect(hRequest.getContextPath() + this.loginURI); return; } Enumeration<?> sessionAttributes = hSession.getAttributeNames(); if (DEBUG) { DEBUGGER.debug("Enumeration<String>: {}", sessionAttributes); } while (sessionAttributes.hasMoreElements()) { String element = (String) sessionAttributes.nextElement(); if (DEBUG) { DEBUGGER.debug("element: {}", element); } Object value = hSession.getAttribute(element); if (DEBUG) { DEBUGGER.debug("sessionValue: {}", value); } if (value instanceof UserAccount) { UserAccount userAccount = (UserAccount) value; if (DEBUG) { DEBUGGER.debug("UserAccount: {}", userAccount); } if (userAccount.getStatus() != null) { switch (userAccount.getStatus()) { case EXPIRED: if ((!(StringUtils.equals(requestURI, passwdPage)))) { ERROR_RECORDER.error( "Account is expired and this request is not for the password page. Redirecting !"); hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI); return; } filterChain.doFilter(sRequest, sResponse); return; case RESET: if ((!(StringUtils.equals(requestURI, passwdPage)))) { ERROR_RECORDER.error( "Account has status RESET and this request is not for the password page. Redirecting !"); hResponse.sendRedirect(hRequest.getContextPath() + this.passwordURI); return; } filterChain.doFilter(sRequest, sResponse); return; case SUCCESS: filterChain.doFilter(sRequest, sResponse); return; default: break; } } } } // no user account in the session ERROR_RECORDER.error("Session contains no existing user account. Redirecting request to " + hRequest.getContextPath() + this.loginURI); // invalidate the session hSession.removeAttribute(SessionAuthenticationFilter.USER_ACCOUNT); hSession.invalidate(); if (StringUtils.isNotEmpty(hRequest.getQueryString())) { redirectPath.append("?" + hRequest.getQueryString()); } if (DEBUG) { DEBUGGER.debug("redirectPath: {}", redirectPath.toString()); } hResponse.sendRedirect(URLEncoder.encode(redirectPath.toString(), systemConfig.getEncoding())); return; }
From source file:au.com.rayh.XCodeBuilder.java
@Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { EnvVars envs = build.getEnvironment(listener); FilePath projectRoot = build.getWorkspace(); // check that the configured tools exist if (!new FilePath(projectRoot.getChannel(), getDescriptor().getXcodebuildPath()).exists()) { listener.fatalError(Messages.XCodeBuilder_xcodebuildNotFound(getDescriptor().getXcodebuildPath())); return false; }//www .j a v a 2 s. co m if (!new FilePath(projectRoot.getChannel(), getDescriptor().getAgvtoolPath()).exists()) { listener.fatalError(Messages.XCodeBuilder_avgtoolNotFound(getDescriptor().getAgvtoolPath())); return false; } // Start expanding all string variables in parameters // NOTE: we currently use variable shadowing to avoid having to rewrite all code (and break pull requests), this will be cleaned up at later stage. String configuration = envs.expand(this.configuration); String target = envs.expand(this.target); String sdk = envs.expand(this.sdk); String symRoot = envs.expand(this.symRoot); String configurationBuildDir = envs.expand(this.configurationBuildDir); String xcodeProjectPath = envs.expand(this.xcodeProjectPath); String xcodeProjectFile = envs.expand(this.xcodeProjectFile); String xcodebuildArguments = envs.expand(this.xcodebuildArguments); String xcodeSchema = envs.expand(this.xcodeSchema); String xcodeWorkspaceFile = envs.expand(this.xcodeWorkspaceFile); String embeddedProfileFile = envs.expand(this.embeddedProfileFile); String cfBundleVersionValue = envs.expand(this.cfBundleVersionValue); String cfBundleShortVersionStringValue = envs.expand(this.cfBundleShortVersionStringValue); String keychainPath = envs.expand(this.keychainPath); String keychainPwd = envs.expand(this.keychainPwd); String codeSigningIdentity = envs.expand(this.codeSigningIdentity); // End expanding all string variables in parameters // Set the working directory if (!StringUtils.isEmpty(xcodeProjectPath)) { projectRoot = projectRoot.child(xcodeProjectPath); } listener.getLogger().println(Messages.XCodeBuilder_workingDir(projectRoot)); // Infer as best we can the build platform String buildPlatform = "iphoneos"; if (!StringUtils.isEmpty(sdk)) { if (StringUtils.contains(sdk.toLowerCase(), "iphonesimulator")) { // Building for the simulator buildPlatform = "iphonesimulator"; } } // Set the build directory and the symRoot // String symRootValue = null; if (!StringUtils.isEmpty(symRoot)) { try { // If not empty we use the Token Expansion to replace it // https://wiki.jenkins-ci.org/display/JENKINS/Token+Macro+Plugin symRootValue = TokenMacro.expandAll(build, listener, symRoot).trim(); } catch (MacroEvaluationException e) { listener.error(Messages.XCodeBuilder_symRootMacroError(e.getMessage())); return false; } } String configurationBuildDirValue = null; FilePath buildDirectory; if (!StringUtils.isEmpty(configurationBuildDir)) { try { configurationBuildDirValue = TokenMacro.expandAll(build, listener, configurationBuildDir).trim(); } catch (MacroEvaluationException e) { listener.error(Messages.XCodeBuilder_configurationBuildDirMacroError(e.getMessage())); return false; } } if (configurationBuildDirValue != null) { // If there is a CONFIGURATION_BUILD_DIR, that overrides any use of SYMROOT. Does not require the build platform and the configuration. buildDirectory = new FilePath(projectRoot.getChannel(), configurationBuildDirValue); } else if (symRootValue != null) { // If there is a SYMROOT specified, compute the build directory from that. buildDirectory = new FilePath(projectRoot.getChannel(), symRootValue) .child(configuration + "-" + buildPlatform); } else { // Assume its a build for the handset, not the simulator. buildDirectory = projectRoot.child("build").child(configuration + "-" + buildPlatform); } // XCode Version int returnCode = launcher.launch().envs(envs).cmds(getDescriptor().getXcodebuildPath(), "-version") .stdout(listener).pwd(projectRoot).join(); if (returnCode > 0) { listener.fatalError(Messages.XCodeBuilder_xcodeVersionNotFound()); return false; // We fail the build if XCode isn't deployed } ByteArrayOutputStream output = new ByteArrayOutputStream(); // Try to read CFBundleShortVersionString from project listener.getLogger().println(Messages.XCodeBuilder_fetchingCFBundleShortVersionString()); String cfBundleShortVersionString = ""; returnCode = launcher.launch().envs(envs).cmds(getDescriptor().getAgvtoolPath(), "mvers", "-terse1") .stdout(output).pwd(projectRoot).join(); // only use this version number if we found it if (returnCode == 0) cfBundleShortVersionString = output.toString().trim(); if (StringUtils.isEmpty(cfBundleShortVersionString)) listener.getLogger().println(Messages.XCodeBuilder_CFBundleShortVersionStringNotFound()); else listener.getLogger() .println(Messages.XCodeBuilder_CFBundleShortVersionStringFound(cfBundleShortVersionString)); listener.getLogger() .println(Messages.XCodeBuilder_CFBundleShortVersionStringValue(cfBundleShortVersionString)); output.reset(); // Try to read CFBundleVersion from project listener.getLogger().println(Messages.XCodeBuilder_fetchingCFBundleVersion()); String cfBundleVersion = ""; returnCode = launcher.launch().envs(envs).cmds(getDescriptor().getAgvtoolPath(), "vers", "-terse") .stdout(output).pwd(projectRoot).join(); // only use this version number if we found it if (returnCode == 0) cfBundleVersion = output.toString().trim(); if (StringUtils.isEmpty(cfBundleVersion)) listener.getLogger().println(Messages.XCodeBuilder_CFBundleVersionNotFound()); else listener.getLogger().println(Messages.XCodeBuilder_CFBundleVersionFound(cfBundleShortVersionString)); listener.getLogger().println(Messages.XCodeBuilder_CFBundleVersionValue(cfBundleVersion)); String buildDescription = cfBundleShortVersionString + " (" + cfBundleVersion + ")"; XCodeAction a = new XCodeAction(buildDescription); build.addAction(a); // Update the Marketing version (CFBundleShortVersionString) if (!StringUtils.isEmpty(cfBundleShortVersionStringValue)) { try { // If not empty we use the Token Expansion to replace it // https://wiki.jenkins-ci.org/display/JENKINS/Token+Macro+Plugin cfBundleShortVersionString = TokenMacro.expandAll(build, listener, cfBundleShortVersionStringValue); listener.getLogger().println( Messages.XCodeBuilder_CFBundleShortVersionStringUpdate(cfBundleShortVersionString)); returnCode = launcher.launch().envs(envs) .cmds(getDescriptor().getAgvtoolPath(), "new-marketing-version", cfBundleShortVersionString) .stdout(listener).pwd(projectRoot).join(); if (returnCode > 0) { listener.fatalError(Messages .XCodeBuilder_CFBundleShortVersionStringUpdateError(cfBundleShortVersionString)); return false; } } catch (MacroEvaluationException e) { listener.fatalError(Messages.XCodeBuilder_CFBundleShortVersionStringMacroError(e.getMessage())); // Fails the build return false; } } // Update the Technical version (CFBundleVersion) if (!StringUtils.isEmpty(cfBundleVersionValue)) { try { // If not empty we use the Token Expansion to replace it // https://wiki.jenkins-ci.org/display/JENKINS/Token+Macro+Plugin cfBundleVersion = TokenMacro.expandAll(build, listener, cfBundleVersionValue); listener.getLogger().println(Messages.XCodeBuilder_CFBundleVersionUpdate(cfBundleVersion)); returnCode = launcher.launch().envs(envs) .cmds(getDescriptor().getAgvtoolPath(), "new-version", "-all", cfBundleVersion) .stdout(listener).pwd(projectRoot).join(); if (returnCode > 0) { listener.fatalError(Messages.XCodeBuilder_CFBundleVersionUpdateError(cfBundleVersion)); return false; } } catch (MacroEvaluationException e) { listener.fatalError(Messages.XCodeBuilder_CFBundleVersionMacroError(e.getMessage())); // Fails the build return false; } } listener.getLogger() .println(Messages.XCodeBuilder_CFBundleShortVersionStringUsed(cfBundleShortVersionString)); listener.getLogger().println(Messages.XCodeBuilder_CFBundleVersionUsed(cfBundleVersion)); // Clean build directories if (cleanBeforeBuild) { listener.getLogger() .println(Messages.XCodeBuilder_cleaningBuildDir(buildDirectory.absolutize().getRemote())); buildDirectory.deleteRecursive(); } // remove test-reports and *.ipa if (cleanTestReports != null && cleanTestReports) { listener.getLogger().println(Messages.XCodeBuilder_cleaningTestReportsDir( projectRoot.child("test-reports").absolutize().getRemote())); projectRoot.child("test-reports").deleteRecursive(); } if (unlockKeychain) { // Let's unlock the keychain launcher.launch().envs(envs).cmds("/usr/bin/security", "list-keychains", "-s", keychainPath) .stdout(listener).pwd(projectRoot).join(); launcher.launch().envs(envs) .cmds("/usr/bin/security", "default-keychain", "-d", "user", "-s", keychainPath) .stdout(listener).pwd(projectRoot).join(); if (StringUtils.isEmpty(keychainPwd)) returnCode = launcher.launch().envs(envs).cmds("/usr/bin/security", "unlock-keychain", keychainPath) .stdout(listener).pwd(projectRoot).join(); else returnCode = launcher.launch().envs(envs) .cmds("/usr/bin/security", "unlock-keychain", "-p", keychainPwd, keychainPath) .masks(false, false, false, true, false).stdout(listener).pwd(projectRoot).join(); if (returnCode > 0) { listener.fatalError(Messages.XCodeBuilder_unlockKeychainFailed()); return false; } } // display useful setup information listener.getLogger().println(Messages.XCodeBuilder_DebugInfoLineDelimiter()); listener.getLogger().println(Messages.XCodeBuilder_DebugInfoAvailablePProfiles()); /*returnCode =*/ launcher.launch().envs(envs) .cmds("/usr/bin/security", "find-identity", "-p", "codesigning", "-v").stdout(listener) .pwd(projectRoot).join(); if (!StringUtils.isEmpty(codeSigningIdentity)) { listener.getLogger().println(Messages.XCodeBuilder_DebugInfoCanFindPProfile()); /*returnCode =*/ launcher .launch().envs(envs).cmds("/usr/bin/security", "find-certificate", "-a", "-c", codeSigningIdentity, "-Z", "|", "grep", "^SHA-1") .stdout(listener).pwd(projectRoot).join(); // We could fail here, but this doesn't seem to work as it should right now (output not properly redirected. We might need a parser) } listener.getLogger().println(Messages.XCodeBuilder_DebugInfoAvailableSDKs()); /*returnCode =*/ launcher.launch().envs(envs).cmds(getDescriptor().getXcodebuildPath(), "-showsdks") .stdout(listener).pwd(projectRoot).join(); { List<String> commandLine = Lists.newArrayList(getDescriptor().getXcodebuildPath()); commandLine.add("-list"); // xcodebuild -list -workspace $workspace listener.getLogger().println(Messages.XCodeBuilder_DebugInfoAvailableSchemes()); if (!StringUtils.isEmpty(xcodeWorkspaceFile)) { commandLine.add("-workspace"); commandLine.add(xcodeWorkspaceFile + ".xcworkspace"); } else if (!StringUtils.isEmpty(xcodeProjectFile)) { commandLine.add("-project"); commandLine.add(xcodeProjectFile); } returnCode = launcher.launch().envs(envs).cmds(commandLine).stdout(listener).pwd(projectRoot).join(); if (returnCode > 0) return false; } listener.getLogger().println(Messages.XCodeBuilder_DebugInfoLineDelimiter()); // Build StringBuilder xcodeReport = new StringBuilder(Messages.XCodeBuilder_invokeXcodebuild()); XCodeBuildOutputParser reportGenerator = new XCodeBuildOutputParser(projectRoot, listener); List<String> commandLine = Lists.newArrayList(getDescriptor().getXcodebuildPath()); // Prioritizing schema over target setting if (!StringUtils.isEmpty(xcodeSchema)) { commandLine.add("-scheme"); commandLine.add(xcodeSchema); xcodeReport.append(", scheme: ").append(xcodeSchema); } else if (StringUtils.isEmpty(target)) { commandLine.add("-alltargets"); xcodeReport.append("target: ALL"); } else { commandLine.add("-target"); commandLine.add(target); xcodeReport.append("target: ").append(target); } if (!StringUtils.isEmpty(sdk)) { commandLine.add("-sdk"); commandLine.add(sdk); xcodeReport.append(", sdk: ").append(sdk); } else { xcodeReport.append(", sdk: DEFAULT"); } xcodeReport.append(". xcodebuildAction: ").append(this.xcodebuildAction); // Prioritizing workspace over project setting if (!StringUtils.isEmpty(xcodeWorkspaceFile)) { commandLine.add("-workspace"); commandLine.add(xcodeWorkspaceFile + ".xcworkspace"); xcodeReport.append(", workspace: ").append(xcodeWorkspaceFile); } else if (!StringUtils.isEmpty(xcodeProjectFile)) { commandLine.add("-project"); commandLine.add(xcodeProjectFile); xcodeReport.append(", project: ").append(xcodeProjectFile); } else { xcodeReport.append(", project: DEFAULT"); } commandLine.add("-configuration"); commandLine.add(configuration); xcodeReport.append(", configuration: ").append(configuration); if (cleanBeforeBuild) { commandLine.add("clean"); xcodeReport.append(", clean: YES"); } else { xcodeReport.append(", clean: NO"); } commandLine.add(this.xcodebuildAction); if (!StringUtils.isEmpty(symRootValue)) { commandLine.add("SYMROOT=" + symRootValue); xcodeReport.append(", symRoot: ").append(symRootValue); } else { xcodeReport.append(", symRoot: DEFAULT"); } // CONFIGURATION_BUILD_DIR if (!StringUtils.isEmpty(configurationBuildDirValue)) { commandLine.add("CONFIGURATION_BUILD_DIR=" + configurationBuildDirValue); xcodeReport.append(", configurationBuildDir: ").append(configurationBuildDirValue); } else { xcodeReport.append(", configurationBuildDir: DEFAULT"); } // handle code signing identities if (!StringUtils.isEmpty(codeSigningIdentity)) { commandLine.add("CODE_SIGN_IDENTITY=" + codeSigningIdentity); xcodeReport.append(", codeSignIdentity: ").append(codeSigningIdentity); } else { xcodeReport.append(", codeSignIdentity: DEFAULT"); } // Additional (custom) xcodebuild arguments if (!StringUtils.isEmpty(xcodebuildArguments)) { commandLine.addAll(splitXcodeBuildArguments(xcodebuildArguments)); } listener.getLogger().println(xcodeReport.toString()); returnCode = launcher.launch().envs(envs).cmds(commandLine).stdout(reportGenerator.getOutputStream()) .pwd(projectRoot).join(); if (reportGenerator.getExitCode() != 0) return false; if (returnCode > 0) return false; // Package IPA if (buildIpa) { if (!buildDirectory.exists() || !buildDirectory.isDirectory()) { listener.fatalError( Messages.XCodeBuilder_NotExistingBuildDirectory(buildDirectory.absolutize().getRemote())); return false; } // clean IPA listener.getLogger().println(Messages.XCodeBuilder_cleaningIPA()); for (FilePath path : buildDirectory.list("*.ipa")) { path.delete(); } listener.getLogger().println(Messages.XCodeBuilder_cleaningDSYM()); for (FilePath path : buildDirectory.list("*-dSYM.zip")) { path.delete(); } // packaging IPA listener.getLogger().println(Messages.XCodeBuilder_packagingIPA()); List<FilePath> apps = buildDirectory.list(new AppFileFilter()); // FilePath is based on File.listFiles() which can randomly fail | http://stackoverflow.com/questions/3228147/retrieving-the-underlying-error-when-file-listfiles-return-null if (apps == null) { listener.fatalError( Messages.XCodeBuilder_NoAppsInBuildDirectory(buildDirectory.absolutize().getRemote())); return false; } for (FilePath app : apps) { String version; if (StringUtils.isEmpty(cfBundleShortVersionString) && StringUtils.isEmpty(cfBundleVersion)) version = Integer.toString(build.getNumber()); else if (StringUtils.isEmpty(cfBundleVersion)) version = cfBundleShortVersionString; else version = cfBundleVersion; String baseName = app.getBaseName().replaceAll(" ", "_") + "-" + configuration.replaceAll(" ", "_") + (StringUtils.isEmpty(version) ? "" : "-" + version); FilePath ipaLocation = buildDirectory.child(baseName + ".ipa"); FilePath payload = buildDirectory.child("Payload"); payload.deleteRecursive(); payload.mkdirs(); listener.getLogger().println( "Packaging " + app.getBaseName() + ".app => " + ipaLocation.absolutize().getRemote()); List<String> packageCommandLine = new ArrayList<String>(); packageCommandLine.add(getDescriptor().getXcrunPath()); packageCommandLine.add("-sdk"); if (!StringUtils.isEmpty(sdk)) { packageCommandLine.add(sdk); } else { packageCommandLine.add(buildPlatform); } packageCommandLine.addAll(Lists.newArrayList("PackageApplication", "-v", app.absolutize().getRemote(), "-o", ipaLocation.absolutize().getRemote())); if (!StringUtils.isEmpty(embeddedProfileFile)) { packageCommandLine.add("--embed"); packageCommandLine.add(embeddedProfileFile); } if (!StringUtils.isEmpty(codeSigningIdentity)) { packageCommandLine.add("--sign"); packageCommandLine.add(codeSigningIdentity); } returnCode = launcher.launch().envs(envs).stdout(listener).pwd(projectRoot).cmds(packageCommandLine) .join(); if (returnCode > 0) { listener.getLogger().println("Failed to build " + ipaLocation.absolutize().getRemote()); continue; } // also zip up the symbols, if present returnCode = launcher.launch().envs(envs).stdout(listener).pwd(buildDirectory) .cmds("ditto", "-c", "-k", "--keepParent", "-rsrc", app.absolutize().getRemote() + ".dSYM", baseName + "-dSYM.zip") .join(); if (returnCode > 0) { listener.getLogger().println(Messages.XCodeBuilder_zipFailed(baseName)); continue; } payload.deleteRecursive(); } } return true; }