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:edu.ku.brc.specify.toycode.L18NStringResApp.java
/** * @param file/*from ww w . j a v a 2s . co m*/ */ protected void copyNewLines(final File file) { String dirName = RES_PATH + "values-" + destLocale.getLanguage(); String dstPath = dirName + File.separator + file.getName(); try { List<String> srcLines = (List<String>) FileUtils.readLines(file, "UTF8"); Vector<String> dstLines = new Vector<String>( (List<String>) FileUtils.readLines(new File(dstPath), "UTF8")); int dstCnt = 0; for (int i = 0; i < srcLines.size(); i++) { String srcLine = srcLines.get(i); String dstLine = dstLines.get(dstCnt++); if (StringUtils.contains(srcLine, "<?xml") && StringUtils.contains(dstLine, "<?xml")) continue; if (StringUtils.contains(srcLine, "<res") && StringUtils.contains(dstLine, "<res")) continue; if (StringUtils.contains(srcLine, "</res") && StringUtils.contains(dstLine, "</res")) continue; srcLine = StringUtils.replace(srcLine, "\\ \'", "\\\'"); srcLine = StringUtils.replace(srcLine, "s \\\'", "s\\\'"); dstLine = StringUtils.replace(dstLine, "\\ \'", "\\\'"); dstLine = StringUtils.replace(dstLine, "s \\ \'", "s\\\'"); System.out.println("--- [" + srcLine + "][" + dstLine + "] -- "); if (srcLine.equals(dstLine)) continue; boolean isSrcComment = StringUtils.contains(srcLine, "<!--"); boolean isDstComment = StringUtils.contains(dstLine, "<!--"); String srcKey = !isSrcComment ? getKey(srcLine) : ""; String dstKey = !isDstComment ? getKey(dstLine) : ""; if (srcKey != null && dstKey != null && srcKey.equals(dstKey) && srcKey.length() > 0) continue; dstLines.insertElementAt(srcLine, dstCnt++); } System.out.println("----------------------------"); for (int i = 0; i < srcLines.size(); i++) { String srcLine = srcLines.get(i); String dstLine = dstLines.get(i); srcLine = StringUtils.replace(srcLine, "\\ \'", "\\\'"); srcLine = StringUtils.replace(srcLine, "s \\\'", "s\\\'"); dstLine = StringUtils.replace(dstLine, "\\ \'", "\\\'"); dstLine = StringUtils.replace(dstLine, "s \\ \'", "s\\\'"); System.out.println("--- [" + srcLine + "] " + srcLine.length() + " [" + dstLine + "] " + dstLine.length() + " -- "); } } catch (IOException e) { e.printStackTrace(); } }
From source file:eionet.meta.imp.VocabularyCSVImportHandler.java
/** * In this method, beans are generated (either created or updated) according to values in CSV file. * * @throws eionet.meta.service.ServiceException * if there is the input is invalid *//*from w ww.ja v a 2 s .com*/ public void generateUpdatedBeans() throws ServiceException { // content. CSVReader reader = new CSVReader(this.content); DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd"); try { String[] header = reader.readNext(); // first check if headers contains fix columns String[] fixedHeaders = new String[VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT]; VocabularyCSVOutputHelper.addFixedEntryHeaders(fixedHeaders); // compare if it has URI boolean isEqual = StringUtils.equalsIgnoreCase(header[VocabularyCSVOutputHelper.URI_INDEX], fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX]); if (!isEqual) { reader.close(); throw new ServiceException("Missing header! CSV file should start with header: '" + fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX] + "'"); } List<String> fixedHeadersList = new ArrayList<String>( Arrays.asList(Arrays.copyOf(fixedHeaders, VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT))); // remove uri from header fixedHeadersList.remove(VocabularyCSVOutputHelper.URI_INDEX); Map<String, Integer> fixedHeaderIndices = new HashMap<String, Integer>(); for (int i = VocabularyCSVOutputHelper.URI_INDEX + 1; i < header.length; i++) { String elementHeader = StringUtils.trimToNull(header[i]); if (StringUtils.isBlank(elementHeader)) { throw new ServiceException("Header for column (" + (i + 1) + ") is empty!"); } int headerIndex = -1; boolean headerFound = false; for (headerIndex = 0; headerIndex < fixedHeadersList.size(); headerIndex++) { if (StringUtils.equalsIgnoreCase(elementHeader, fixedHeadersList.get(headerIndex))) { headerFound = true; break; } } // if it is a fixed header value (concept property), add to map and continue if (headerFound) { String headerValue = fixedHeadersList.remove(headerIndex); fixedHeaderIndices.put(headerValue, i); continue; } // it is not a concept attribute and but a data element identifier // if there is language appended, split it String[] tempStrArray = elementHeader.split("[@]"); if (tempStrArray.length == 2) { elementHeader = tempStrArray[0]; } // if bound elements do not contain header already, add it (if possible) if (!this.boundElementsIds.containsKey(elementHeader)) { // search for data element this.elementsFilter.setIdentifier(elementHeader); DataElementsResult elementsResult = this.dataService.searchDataElements(this.elementsFilter); // if there is one and only one element check if header and identifer exactly matches! if (elementsResult.getTotalResults() < 1) { throw new ServiceException("Cannot find any data element for column: " + elementHeader + ". Please bind element manually then upload CSV."); } else if (elementsResult.getTotalResults() > 1) { throw new ServiceException("Cannot find single data element for column: " + elementHeader + ". Search returns: " + elementsResult.getTotalResults() + " elements. Please bind element manually then upload CSV."); } else { DataElement elem = elementsResult.getDataElements().get(0); if (StringUtils.equals(elementHeader, elem.getIdentifier())) { // found it, add to list and map this.boundElementsIds.put(elementHeader, elementsResult.getDataElements().get(0).getId()); this.newBoundElement.add(elem); } else { throw new ServiceException("Found data element did not EXACTLY match with column: " + elementHeader + ", found: " + elem.getIdentifier()); } } } } // end of for loop iterating on headers String[] lineParams; // first row is header so start from 2 for (int rowNumber = 2; (lineParams = reader.readNext()) != null; rowNumber++) { if (lineParams.length != header.length) { StringBuilder message = new StringBuilder(); message.append("Row (").append(rowNumber).append(") "); message.append("did not have same number of columns with header, it was skipped."); message.append(" It should have have same number of columns (empty or filled)."); this.logMessages.add(message.toString()); continue; } // do line processing String uri = lineParams[VocabularyCSVOutputHelper.URI_INDEX]; if (StringUtils.isEmpty(uri)) { this.logMessages.add("Row (" + rowNumber + ") was skipped (Base URI was empty)."); continue; } else if (StringUtils.startsWith(uri, "//")) { this.logMessages.add("Row (" + rowNumber + ") was skipped (Concept was excluded by user from update operation)."); continue; } else if (!StringUtils.startsWith(uri, this.folderContextRoot)) { this.logMessages .add("Row (" + rowNumber + ") was skipped (Base URI did not match with Vocabulary)."); continue; } String conceptIdentifier = uri.replace(this.folderContextRoot, ""); if (StringUtils.contains(conceptIdentifier, "/") || !Util.isValidIdentifier(conceptIdentifier)) { this.logMessages.add("Row (" + rowNumber + ") did not contain a valid concept identifier."); continue; } // now we have a valid row Pair<VocabularyConcept, Boolean> foundConceptWithFlag = findOrCreateConcept(conceptIdentifier); // if vocabulary concept duplicated with another row, importer will ignore it not to repeat if (foundConceptWithFlag == null || foundConceptWithFlag.getRight()) { this.logMessages .add("Row (" + rowNumber + ") duplicated with a previous concept, it was skipped."); continue; } VocabularyConcept lastFoundConcept = foundConceptWithFlag.getLeft(); // vocabulary concept found or created this.toBeUpdatedConcepts.add(lastFoundConcept); Integer conceptPropertyIndex = null; // check label conceptPropertyIndex = fixedHeaderIndices.get(fixedHeaders[VocabularyCSVOutputHelper.LABEL_INDEX]); if (conceptPropertyIndex != null) { lastFoundConcept.setLabel(StringUtils.trimToNull(lineParams[conceptPropertyIndex])); } // check definition conceptPropertyIndex = fixedHeaderIndices .get(fixedHeaders[VocabularyCSVOutputHelper.DEFINITION_INDEX]); if (conceptPropertyIndex != null) { lastFoundConcept.setDefinition(StringUtils.trimToNull(lineParams[conceptPropertyIndex])); } // check notation conceptPropertyIndex = fixedHeaderIndices .get(fixedHeaders[VocabularyCSVOutputHelper.NOTATION_INDEX]); if (conceptPropertyIndex != null) { lastFoundConcept.setNotation(StringUtils.trimToNull(lineParams[conceptPropertyIndex])); } // TODO: update - with merging flexible csv import // check start date // ignore status and accepteddate changes // now it is time iterate on rest of the columns, here is the tricky part List<DataElement> elementsOfConcept = null; List<DataElement> elementsOfConceptByLang = null; String prevHeader = null; String prevLang = null; for (int k = VocabularyCSVOutputHelper.URI_INDEX + 1; k < lineParams.length; k++) { if (StringUtils.isEmpty(lineParams[k])) { // value is empty, no need to proceed continue; } if (fixedHeaderIndices.containsValue(k)) { // concept property, already handled continue; } String elementHeader = header[k]; String lang = null; String[] tempStrArray = elementHeader.split("[@]"); if (tempStrArray.length == 2) { elementHeader = tempStrArray[0]; lang = tempStrArray[1]; } if (!StringUtils.equals(elementHeader, prevHeader)) { elementsOfConcept = getDataElementValuesByName(elementHeader, lastFoundConcept.getElementAttributes()); if (elementsOfConcept == null) { elementsOfConcept = new ArrayList<DataElement>(); lastFoundConcept.getElementAttributes().add(elementsOfConcept); } } if (!StringUtils.equals(elementHeader, prevHeader) || !StringUtils.equals(lang, prevLang)) { elementsOfConceptByLang = getDataElementValuesByNameAndLang(elementHeader, lang, lastFoundConcept.getElementAttributes()); } prevLang = lang; prevHeader = elementHeader; VocabularyConcept foundRelatedConcept = null; if (Util.isValidUri(lineParams[k])) { foundRelatedConcept = findRelatedConcept(lineParams[k]); } // check for pre-existence of the VCE by attribute value or related concept id Integer relatedId = null; if (foundRelatedConcept != null) { relatedId = foundRelatedConcept.getId(); } boolean returnFromThisPoint = false; for (DataElement elemByLang : elementsOfConceptByLang) { String elementValueByLang = elemByLang.getAttributeValue(); if (StringUtils.equals(lineParams[k], elementValueByLang)) { // vocabulary concept element already in database, no need to continue, return returnFromThisPoint = true; break; } if (relatedId != null) { Integer relatedConceptId = elemByLang.getRelatedConceptId(); if (relatedConceptId != null && relatedConceptId.intValue() == relatedId.intValue()) { // vocabulary concept element already in database, no need to continue, return returnFromThisPoint = true; break; } } } // check if an existing VCE found or not if (returnFromThisPoint) { continue; } // create VCE DataElement elem = new DataElement(); elementsOfConcept.add(elem); elem.setAttributeLanguage(lang); elem.setIdentifier(elementHeader); elem.setId(this.boundElementsIds.get(elementHeader)); // check if there is a found related concept if (foundRelatedConcept != null) { elem.setRelatedConceptIdentifier(foundRelatedConcept.getIdentifier()); int id = foundRelatedConcept.getId(); elem.setRelatedConceptId(id); elem.setAttributeValue(null); if (id < 0) { addToElementsReferringNotCreatedConcepts(id, elem); } } else { elem.setAttributeValue(lineParams[k]); elem.setRelatedConceptId(null); } } // end of for loop iterating on rest of the columns (for data elements) } // end of row iterator (while loop on rows) processUnseenConceptsForRelatedElements(); } catch (IOException e) { e.printStackTrace(); throw new ServiceException(e.getMessage()); } catch (RuntimeException e) { e.printStackTrace(); throw new ServiceException(e.getMessage()); } finally { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:hydrograph.ui.expression.editor.buttons.ValidateExpressionToolButton.java
public static Object[] getBuildPathForMethodInvocation() throws JavaModelException, MalformedURLException { String transfromJarPath = null; Object[] returnObj = new Object[3]; IJavaProject iJavaProject = JavaCore .create(BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject()); List<URL> urlList = new ArrayList<>(); Properties properties = ConfigFileReader.INSTANCE.getCommonConfigurations(); for (IPackageFragmentRoot iPackageFragmentRoot : iJavaProject.getAllPackageFragmentRoots()) { if (!iPackageFragmentRoot.isExternal() || StringUtils.contains(iPackageFragmentRoot.getElementName(), properties.getProperty(Constants.KEY_TRANSFORMATION_JAR)) || StringUtils.contains(iPackageFragmentRoot.getElementName(), Constants.ANTLR_JAR_FILE_NAME) || StringUtils.contains(iPackageFragmentRoot.getElementName(), Constants.BEAN_SHELLJAR_FILE_NAME) || StringUtils.contains(iPackageFragmentRoot.getElementName(), Constants.SL4JLOG) || StringUtils.contains(iPackageFragmentRoot.getElementName(), properties.getProperty(Constants.KEY_EXPRESSION_JAR))) { URL url = null;/*from w w w. j a va 2 s . c o m*/ if (!iPackageFragmentRoot.isExternal()) { url = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject() .getFile(iPackageFragmentRoot.getPath().removeFirstSegments(1)).getLocation().toFile() .toURI().toURL(); urlList.add(url); } else { url = iPackageFragmentRoot.getPath().toFile().toURI().toURL(); urlList.add(url); } if (!iPackageFragmentRoot.isExternal() || StringUtils.contains(iPackageFragmentRoot.getElementName(), properties.getProperty(Constants.KEY_TRANSFORMATION_JAR))) { if (transfromJarPath == null) { if (OSValidator.isMac() || OSValidator.isUnix()) transfromJarPath = url.getPath() + Constants.COLON; else transfromJarPath = url.getPath() + Constants.SEMICOLON; } else { if (OSValidator.isMac() || OSValidator.isUnix()) transfromJarPath = transfromJarPath + url.getPath() + Constants.COLON; else transfromJarPath = transfromJarPath + url.getPath() + Constants.SEMICOLON; } } } } returnObj[0] = urlList; returnObj[1] = transfromJarPath; returnObj[2] = getPropertyFilePath(iJavaProject); iJavaProject.close(); return returnObj; }
From source file:cec.easyshop.storefront.filters.cms.CMSSiteFilter.java
/** * Processing preview request (i.e. request with additional parameters like {@link CMSFilter#PREVIEW_TOKEN} requested * from cmscockpit) )/*from ww w . j av a2s .c o m*/ * <p/> * <b>Note:</b> Processing preview data in order to generate target URL, and load necessary information in user * session * <ul> * <li>Initialize information (Active CMSSite, Catalog versions,Current catalog version ) information getting from * valid Preview Data</li> * <li>Load all fake information (like: User, User group, Language, Time ...) * <li>Generating target URL according to Preview Data * </ul> * * @param httpRequest * current request * @return target URL */ protected String processPreviewRequest(final HttpServletRequest httpRequest, final CmsPageRequestContextData cmsPageRequestContextData) { final PreviewDataModel previewDataModel = cmsPageRequestContextData.getPreviewData(); previewDataModel.setLanguage(filterPreviewLanguageForSite(httpRequest, previewDataModel.getLanguage())); previewDataModel.setUiExperience(previewDataModel.getUiExperience()); //load necessary information getContextInformationLoader().initializePreviewRequest(previewDataModel); //load fake context information getContextInformationLoader().loadFakeContextInformation(httpRequest, previewDataModel); //generate destination URL final String destinationURL = generatePreviewUrl(httpRequest, previewDataModel); // persist changes previewDataModel.setResourcePath(destinationURL); getContextInformationLoader().storePreviewData(previewDataModel); final CMSPreviewTicketModel ticket = getCmsPreviewService().createPreviewTicket(previewDataModel); String parameterDelimiter = "?"; if (StringUtils.contains(destinationURL, "?")) { parameterDelimiter = "&"; } return destinationURL + parameterDelimiter + PREVIEW_TICKET_ID_PARAM + "=" + ticket.getId(); }
From source file:au.com.rayh.AbstractXCodeBuilder.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(), getGlobalConfiguration().getXcodebuildPath()).exists()) { listener.fatalError(/*w w w.ja va 2s . c o m*/ Messages.XCodeBuilder_xcodebuildNotFound(getGlobalConfiguration().getXcodebuildPath())); return false; } if (!new FilePath(projectRoot.getChannel(), getGlobalConfiguration().getAgvtoolPath()).exists()) { listener.fatalError(Messages.XCodeBuilder_avgtoolNotFound(getGlobalConfiguration().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 codeSigningIdentity = envs.expand(this.codeSigningIdentity); String ipaName = envs.expand(this.ipaName); String ipaOutputDirectory = envs.expand(this.ipaOutputDirectory); // 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(getGlobalConfiguration().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(getGlobalConfiguration().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(getGlobalConfiguration().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(cfBundleVersion)); 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(getGlobalConfiguration().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(getGlobalConfiguration().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 != null && unlockKeychain) { // Let's unlock the keychain Keychain keychain = getKeychain(); if (keychain == null) { listener.fatalError(Messages.XCodeBuilder_keychainNotConfigured()); return false; } String keychainPath = envs.expand(keychain.getKeychainPath()); String keychainPwd = envs.expand(keychain.getKeychainPassword()); 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; } // Show the keychain info after unlocking, if not, OS X will prompt for the keychain password launcher.launch().envs(envs).cmds("/usr/bin/security", "show-keychain-info", keychainPath) .stdout(listener).pwd(projectRoot).join(); } // 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(getGlobalConfiguration().getXcodebuildPath(), "-showsdks").stdout(listener).pwd(projectRoot) .join(); { List<String> commandLine = Lists.newArrayList(getGlobalConfiguration().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 JenkinsXCodeBuildOutputParser(projectRoot, listener); List<String> commandLine = Lists.newArrayList(getGlobalConfiguration().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"); } // 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"); } if (!StringUtils.isEmpty(configuration)) { commandLine.add("-configuration"); commandLine.add(configuration); xcodeReport.append(", configuration: ").append(configuration); } if (runTests) { commandLine.add("-destination"); String destination = "devicetype=iOS Simulator,name="; destination += testDevice; destination += ",OS=" + testOsVersion; commandLine.add(destination); xcodeReport.append("testing for: " + testDevice + ", on " + testOsVersion); } if (cleanBeforeBuild) { commandLine.add("clean"); xcodeReport.append(", clean: YES"); } else { xcodeReport.append(", clean: NO"); } String action = runTests ? "test" : "build"; commandLine.add(action); if (generateArchive != null && generateArchive) { commandLine.add("archive"); xcodeReport.append(", archive:YES"); } else { xcodeReport.append(", archive:NO"); } 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)); } // Reset simulator if requested, by blowing away ~/Library/Application Support/iPhone Simulator/VERSION if (resetSimulator) { String path = System.getProperty("user.home") + "/Library/Application Support/iPhone Simulator/" + testOsVersion; xcodeReport.append("resetting simulator at location: ").append(path); FilePath filePath = new FilePath(new File(path)); if (filePath.exists() && filePath.isDirectory()) { filePath.deleteRecursive(); } } listener.getLogger().println(xcodeReport.toString()); returnCode = launcher.launch().envs(envs).cmds(commandLine).stdout(reportGenerator.getOutputStream()) .pwd(projectRoot).join(); if (allowFailingBuildResults != null && allowFailingBuildResults.booleanValue() == false) { 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 FilePath ipaOutputPath = null; if (ipaOutputDirectory != null && !StringUtils.isEmpty(ipaOutputDirectory)) { ipaOutputPath = buildDirectory.child(ipaOutputDirectory); // Create if non-existent if (!ipaOutputPath.exists()) { ipaOutputPath.mkdirs(); } } if (ipaOutputPath == null) { ipaOutputPath = buildDirectory; } listener.getLogger().println(Messages.XCodeBuilder_cleaningIPA()); for (FilePath path : ipaOutputPath.list("*.ipa")) { path.delete(); } listener.getLogger().println(Messages.XCodeBuilder_cleaningDSYM()); for (FilePath path : ipaOutputPath.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 = ""; String shortVersion = ""; if (!provideApplicationVersion) { try { output.reset(); returnCode = launcher.launch().envs(envs) .cmds("/usr/libexec/PlistBuddy", "-c", "Print :CFBundleVersion", app.absolutize().child("Info.plist").getRemote()) .stdout(output).pwd(projectRoot).join(); if (returnCode == 0) { version = output.toString().trim(); } output.reset(); returnCode = launcher.launch().envs(envs) .cmds("/usr/libexec/PlistBuddy", "-c", "Print :CFBundleShortVersionString", app.absolutize().child("Info.plist").getRemote()) .stdout(output).pwd(projectRoot).join(); if (returnCode == 0) { shortVersion = output.toString().trim(); } } catch (Exception ex) { listener.getLogger().println("Failed to get version from Info.plist: " + ex.toString()); return false; } } else { if (!StringUtils.isEmpty(cfBundleVersionValue)) { version = cfBundleVersionValue; } else if (!StringUtils.isEmpty(cfBundleShortVersionStringValue)) { shortVersion = cfBundleShortVersionStringValue; } else { listener.getLogger().println( "You have to provide a value for either the marketing or technical version. Found neither."); return false; } } File file = new File(app.absolutize().getRemote()); String lastModified = new SimpleDateFormat("yyyy.MM.dd").format(new Date(file.lastModified())); String baseName = app.getBaseName().replaceAll(" ", "_") + (shortVersion.isEmpty() ? "" : "-" + shortVersion) + (version.isEmpty() ? "" : "-" + version); // If custom .ipa name pattern has been provided, use it and expand version and build date variables if (!StringUtils.isEmpty(ipaName)) { EnvVars customVars = new EnvVars("BASE_NAME", app.getBaseName().replaceAll(" ", "_"), "VERSION", version, "SHORT_VERSION", shortVersion, "BUILD_DATE", lastModified); baseName = customVars.expand(ipaName); } FilePath ipaLocation = ipaOutputPath.child(baseName + ".ipa"); FilePath payload = ipaOutputPath.child("Payload"); payload.deleteRecursive(); payload.mkdirs(); listener.getLogger().println( "Packaging " + app.getBaseName() + ".app => " + ipaLocation.absolutize().getRemote()); List<String> packageCommandLine = new ArrayList<String>(); packageCommandLine.add(getGlobalConfiguration().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", ipaOutputPath.child(baseName + "-dSYM.zip").absolutize().getRemote()) .join(); if (returnCode > 0) { listener.getLogger().println(Messages.XCodeBuilder_zipFailed(baseName)); continue; } payload.deleteRecursive(); } } return true; }
From source file:com.ebook.storefront.filters.cms.CMSSiteFilter.java
/** * Processing preview request (i.e. request with additional parameters like {@link CMSFilter#PREVIEW_TOKEN} requested * from cmscockpit) )/*from w w w . j av a 2 s . com*/ * <p/> * <b>Note:</b> Processing preview data in order to generate target URL, and load necessary information in user * session * <ul> * <li>Initialize information (Active CMSSite, Catalog versions,Current catalog version ) information getting from * valid Preview Data</li> * <li>Load all fake information (like: User, User group, Language, Time ...) * <li>Generating target URL according to Preview Data * </ul> * * @param httpRequest * current request * @return target URL */ protected String processPreviewRequest(final HttpServletRequest httpRequest, final CmsPageRequestContextData cmsPageRequestContextData) { final PreviewDataModel previewDataModel = cmsPageRequestContextData.getPreviewData(); previewDataModel.setLanguage(filterPreviewLanguageForSite(httpRequest, previewDataModel.getLanguage())); previewDataModel.setUiExperience(previewDataModel.getUiExperience()); //load necessary information getContextInformationLoader().initializePreviewRequest(previewDataModel); //load fake context information getContextInformationLoader().loadFakeContextInformation(httpRequest, previewDataModel); //generate destination URL final String destinationURL = generatePreviewUrl(httpRequest, previewDataModel); // persist changes previewDataModel.setResourcePath(destinationURL); getContextInformationLoader().storePreviewData(previewDataModel); final CMSPreviewTicketModel ticket = getCmsPreviewService().createPreviewTicket(previewDataModel); String parameterDelimiter = "?"; if (StringUtils.contains(destinationURL, "?")) { parameterDelimiter = "&"; } return destinationURL + parameterDelimiter + PREVIEW_TICKET_ID_PARAM + "=" + ticket.getId(); }
From source file:com.epam.cme.storefront.filters.cms.CMSSiteFilter.java
/** * Processing preview request (i.e. request with additional parameters like * {@link CMSFilter#PREVIEW_TOKEN} requested from cmscockpit) ) * <p/>/* w w w . j a va 2s. c om*/ * <b>Note:</b> Processing preview data in order to generate target URL, and load necessary * information in user session * <ul> * <li>Initialize information (Active CMSSite, Catalog versions,Current catalog version ) * information getting from valid Preview Data</li> * <li>Load all fake information (like: User, User group, Language, Time ...) * <li>Generating target URL according to Preview Data * </ul> * * @param httpRequest * current request * @return target URL */ protected String processPreviewRequest(final HttpServletRequest httpRequest, final CmsPageRequestContextData cmsPageRequestContextData) { final PreviewDataModel previewDataModel = cmsPageRequestContextData.getPreviewData(); previewDataModel.setLanguage(filterPreviewLanguageForSite(httpRequest, previewDataModel.getLanguage())); previewDataModel.setUiExperience(previewDataModel.getUiExperience()); // load necessary information getContextInformationLoader().initializePreviewRequest(previewDataModel); // load fake context information getContextInformationLoader().loadFakeContextInformation(httpRequest, previewDataModel); // generate destination URL final String destinationURL = generatePreviewUrl(httpRequest, previewDataModel); // persist changes previewDataModel.setResourcePath(destinationURL); getContextInformationLoader().storePreviewData(previewDataModel); final CMSPreviewTicketModel ticket = getCmsPreviewService().createPreviewTicket(previewDataModel); String parameterDelimiter = "?"; if (StringUtils.contains(destinationURL, "?")) { parameterDelimiter = "&"; } return destinationURL + parameterDelimiter + PREVIEW_TICKET_ID_PARAM + "=" + ticket.getId(); }
From source file:com.hangum.tadpole.rdb.core.editors.main.utils.ExtMakeContentAssistUtil.java
/** * List of assist table column name/* w w w. jav a 2 s . c om*/ * * @param userDB * @param tableName * @return */ public String getAssistColumnList(final UserDBDAO userDB, final String tableName) { String strColumnlist = ""; //$NON-NLS-1$ String strSchemaName = ""; String strTableName = tableName; if (userDB.getDBDefine() != DBDefine.ALTIBASE_DEFAULT) { if (StringUtils.contains(tableName, '.')) { String[] arrTblInfo = StringUtils.split(tableName, "."); strSchemaName = arrTblInfo[0]; strTableName = arrTblInfo[1]; } } // ? ? ?? ? ? ? . TadpoleMetaData tadpoleMetaData = TadpoleSQLManager.getDbMetadata(userDB); if (tadpoleMetaData.getSTORE_TYPE() == TadpoleMetaData.STORES_FIELD_TYPE.LOWCASE_BLANK) { strSchemaName = StringUtils.upperCase(strSchemaName); strTableName = StringUtils.upperCase(strTableName); } else if (tadpoleMetaData.getSTORE_TYPE() == TadpoleMetaData.STORES_FIELD_TYPE.UPPERCASE_BLANK) { strSchemaName = StringUtils.lowerCase(strSchemaName); strTableName = StringUtils.lowerCase(strTableName); } try { TableDAO table = new TableDAO(strTableName, ""); table.setSysName(strTableName); table.setSchema_name(strSchemaName); table.setName(strTableName); List<TableColumnDAO> showTableColumns = TadpoleObjectQuery.getTableColumns(userDB, table); for (TableColumnDAO tableDao : showTableColumns) { strColumnlist += tableDao.getSysName() + _PRE_DEFAULT + tableDao.getType() + _PRE_GROUP; //$NON-NLS-1$ } strColumnlist = StringUtils.removeEnd(strColumnlist, _PRE_GROUP); //$NON-NLS-1$ } catch (Exception e) { logger.error("MainEditor get the table column list", e); //$NON-NLS-1$ } return strColumnlist; }
From source file:com.glaf.core.xml.XmlBuilder.java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected void processForEachNode(Element element, Map<String, DatasetModel> dataSetMap, Map<String, Object> myDataMap, String systemName, Map<String, Object> params) { //LOG.debug("---------------------processForEachNode-----------------------"); Element parent = element.getParent(); String dsId = element.attributeValue("DataSetId"); if (StringUtils.isNotEmpty(dsId)) { if (myDataMap != null && !myDataMap.isEmpty()) { params.putAll(myDataMap);/* w ww. j av a 2 s .c o m*/ } DatasetModel dsm = dataSetMap.get(dsId); String sql = dsm.getSql(); String queryId = dsm.getQueryId(); List<Map<String, Object>> rows = null; if (StringUtils.isNotEmpty(queryId)) { Environment.setCurrentSystemName(systemName); List<Object> list = entityService.getList(queryId, params); if (list != null && !list.isEmpty()) { rows = new ArrayList<Map<String, Object>>(); for (Object object : list) { if (object instanceof Map) { Map dataMap = (Map) object; rows.add(dataMap); } else { try { Map dataMap = BeanUtils.describe(object); rows.add(dataMap); } catch (Exception e) { } } } } } else if (StringUtils.isNotEmpty(sql)) { LOG.debug("sql:" + sql); LOG.debug("params:" + params); rows = queryHelper.getResultList(systemName, sql, params); // ITablePageService tablePageService = // ContextFactory.getBean("tablePageService"); // rows = queryHelper.getResultList(systemName, sql, params); // Environment.setCurrentSystemName(systemName); // rows = tablePageService.getListData(sql, params); LOG.debug("#1 rows:" + rows.size()); } if (rows != null && !rows.isEmpty()) { int sortNo = 0; List<?> elements = element.elements(); if (elements != null && elements.size() == 1) { Element elem = (Element) elements.get(0); LOG.debug("name:" + elem.getName()); for (Map<String, Object> dataMap : rows) { sortNo = sortNo + 1; dataMap.put("sortNo", sortNo); Element e = elem.createCopy(); if (dsm.getControllers() != null && !dsm.getControllers().isEmpty()) { List<FieldController> controllers = dsm.getControllers(); for (FieldController c : controllers) { Class<?> x = ClassUtils.classForName(c.getProvider()); FieldConverter fp = (FieldConverter) ReflectUtils.newInstance(x); fp.convert(c.getFromName(), c.getToName(), dataMap); } } if (e.isTextOnly()) { String value = e.getStringValue(); if (StringUtils.contains(value, "#{") && StringUtils.contains(value, "}")) { String text = QueryUtils.replaceBlankParas(value, dataMap); e.setText(text); } } List<?> attrs = e.attributes(); Iterator<?> iter = attrs.iterator(); while (iter.hasNext()) { Attribute attr = (Attribute) iter.next(); String value = attr.getValue(); if (StringUtils.contains(value, "#{") && StringUtils.contains(value, "}")) { String text = QueryUtils.replaceBlankParas(value, dataMap); attr.setValue(text); } } e.setParent(null); parent.add(e); } } } } parent.remove(element); }
From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.MSSQLLoginComposite.java
/** * ip? instance ping.//from w ww . j av a 2 s. c o m */ public boolean isPing(String strHost, String port) { if (StringUtils.contains(strHost, "\\")) { String strIp = StringUtils.substringBefore(strHost, "\\"); return super.isPing(strIp, port); } else if (StringUtils.contains(strHost, "/")) { String strIp = StringUtils.substringBefore(strHost, "/"); return super.isPing(strIp, port); } else { return super.isPing(strHost, port); } }