Java Code Examples for org.codehaus.plexus.util.StringUtils#isEmpty()
The following examples show how to use
org.codehaus.plexus.util.StringUtils#isEmpty() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SqlExecMojo.java From sql-maven-plugin with Apache License 2.0 | 6 votes |
/** * parse driverProperties into Properties set * * @return the driver properties * @throws MojoExecutionException */ protected Properties getDriverProperties() throws MojoExecutionException { Properties properties = new Properties(); if ( !StringUtils.isEmpty( this.driverProperties ) ) { String[] tokens = StringUtils.split( this.driverProperties, "," ); for ( int i = 0; i < tokens.length; ++i ) { String[] keyValueTokens = StringUtils.split( tokens[i].trim(), "=" ); if ( keyValueTokens.length != 2 ) { throw new MojoExecutionException( "Invalid JDBC Driver properties: " + this.driverProperties ); } properties.setProperty( keyValueTokens[0], keyValueTokens[1] ); } } return properties; }
Example 2
Source File: DefaultArtifactDownloader.java From opoopress with Apache License 2.0 | 6 votes |
private ArtifactRepository parseRepository(String repo, ArtifactRepositoryPolicy policy) throws MojoFailureException { // if it's a simple url String id = null; ArtifactRepositoryLayout layout = getLayout("default"); String url = repo; // if it's an extended repo URL of the form id::layout::url if (repo.contains("::")) { Matcher matcher = ALT_REPO_SYNTAX_PATTERN.matcher(repo); if (!matcher.matches()) { throw new MojoFailureException(repo, "Invalid syntax for repository: " + repo, "Invalid syntax for repository. Use \"id::layout::url\" or \"URL\"."); } id = matcher.group(1).trim(); if (!StringUtils.isEmpty(matcher.group(2))) { layout = getLayout(matcher.group(2).trim()); } url = matcher.group(3).trim(); } return artifactRepositoryFactory.createArtifactRepository(id, url, layout, policy, policy); }
Example 3
Source File: JavaServiceWrapperDaemonGenerator.java From appassembler with MIT License | 6 votes |
private static void createParameters( Daemon daemon, FormattedProperties confFile ) { int count = StringUtils.isEmpty( daemon.getMainClass() ) ? 1 : 2; for ( Iterator<String> i = daemon.getCommandLineArguments().iterator(); i.hasNext(); count++ ) { String argument = i.next(); if ( StringUtils.isNotEmpty( argument ) ) { confFile.setProperty( "wrapper.app.parameter." + count, argument ); } } if ( count == 1 ) { // Remove default parameter if not set confFile.removeProperty( "wrapper.app.parameter.1" ); } }
Example 4
Source File: AbstractCodegenMojo.java From cxf with Apache License 2.0 | 5 votes |
protected void configureProxyServerSettings() throws MojoExecutionException { Proxy proxy = mavenSession.getSettings().getActiveProxy(); if (proxy != null) { getLog().info("Using proxy server configured in maven."); if (proxy.getHost() == null) { throw new MojoExecutionException("Proxy in settings.xml has no host"); } if (proxy.getHost() != null) { System.setProperty(HTTP_PROXY_HOST, proxy.getHost()); } if (String.valueOf(proxy.getPort()) != null) { System.setProperty(HTTP_PROXY_PORT, String.valueOf(proxy.getPort())); } if (proxy.getNonProxyHosts() != null) { System.setProperty(HTTP_NON_PROXY_HOSTS, proxy.getNonProxyHosts()); } if (!StringUtils.isEmpty(proxy.getUsername()) && !StringUtils.isEmpty(proxy.getPassword())) { final String authUser = proxy.getUsername(); final String authPassword = proxy.getPassword(); Authenticator.setDefault(new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(authUser, authPassword.toCharArray()); } }); System.setProperty(HTTP_PROXY_USER, authUser); System.setProperty(HTTP_PROXY_PASSWORD, authPassword); } } }
Example 5
Source File: DockerFileBuilder.java From docker-maven-plugin with Apache License 2.0 | 5 votes |
/** * Adds the RUN Commands within the build image section * @param runCmds * @return */ public DockerFileBuilder run(List<String> runCmds) { if (runCmds != null) { for (String cmd : runCmds) { if (!StringUtils.isEmpty(cmd)) { this.runCmds.add(cmd); } } } return this; }
Example 6
Source File: AbstractDeployMojo.java From opoopress with Apache License 2.0 | 5 votes |
public static ProxyInfo getProxyInfo(Repository repository, WagonManager wagonManager) { ProxyInfo proxyInfo = wagonManager.getProxy(repository.getProtocol()); if (proxyInfo == null) { return null; } String host = repository.getHost(); String nonProxyHostsAsString = proxyInfo.getNonProxyHosts(); for (String nonProxyHost : StringUtils.split(nonProxyHostsAsString, ",;|")) { if (org.apache.commons.lang.StringUtils.contains(nonProxyHost, "*")) { // Handle wildcard at the end, beginning or middle of the nonProxyHost final int pos = nonProxyHost.indexOf('*'); String nonProxyHostPrefix = nonProxyHost.substring(0, pos); String nonProxyHostSuffix = nonProxyHost.substring(pos + 1); // prefix* if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && StringUtils.isEmpty(nonProxyHostSuffix)) { return null; } // *suffix if (StringUtils.isEmpty(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) { return null; } // prefix*suffix if (StringUtils.isNotEmpty(nonProxyHostPrefix) && host.startsWith(nonProxyHostPrefix) && StringUtils.isNotEmpty(nonProxyHostSuffix) && host.endsWith(nonProxyHostSuffix)) { return null; } } else if (host.equals(nonProxyHost)) { return null; } } return proxyInfo; }
Example 7
Source File: MojoUtils.java From frontend-maven-plugin with Apache License 2.0 | 5 votes |
static Server decryptServer(String serverId, MavenSession mavenSession, SettingsDecrypter decrypter) { if (StringUtils.isEmpty(serverId)) { return null; } Server server = mavenSession.getSettings().getServer(serverId); if (server != null) { final DefaultSettingsDecryptionRequest decryptionRequest = new DefaultSettingsDecryptionRequest(server); SettingsDecryptionResult decryptedResult = decrypter.decrypt(decryptionRequest); return decryptedResult.getServer(); } else { LOGGER.warn("Could not find server '" + serverId + "' in settings.xml"); return null; } }
Example 8
Source File: Kasaaja.java From KantaCDA-API with Apache License 2.0 | 5 votes |
/** * Lisää clinicalDocumentiin relatedDocument rakenteen johon sijoitetaan annetut oid ja setId ja haetaan code * elemettiin arvot annetulla propertycodella <relatedDocument typeCode="RPLC/APND/..."> <parentDocument> * <id root="[oid]"/> <code code="{propertycode.code}" codeSystem="{propertycode.codeSystem}" codesystemName= * "{propertycode.codeSystemName}" displayName= "{propertycode.displayName}"/> <setId root="[setId]"/> * </parentDocument> </relatedDocument> * * @param clinicalDocument * POCDMT00040ClinicalDocument johon relatedDocument elementti lisätään * @param oid * String alkuperäisen dokumentin oid * @param setid * String alkuperäisen dokumentin setId * @param propertycode * String avain jolla code kenttä täytetään property tiedoista * @param relationType * Relaation tyyppikoodi (RPLC korjaus, APND uusiminen) */ protected void addRelatedDocument(POCDMT000040ClinicalDocument clinicalDocument, String oid, String setid, String propertycode, XActRelationshipDocument relationType) { POCDMT000040RelatedDocument relatedDocument = of.createPOCDMT000040RelatedDocument(); relatedDocument.setTypeCode(relationType); relatedDocument.setParentDocument(of.createPOCDMT000040ParentDocument()); relatedDocument.getParentDocument().getIds().add(of.createII()); relatedDocument.getParentDocument().getIds().get(0).setRoot(oid); relatedDocument.getParentDocument().setCode(of.createCE()); fetchAttributes(propertycode, relatedDocument.getParentDocument().getCode()); clinicalDocument.getRelatedDocuments().add(relatedDocument); if ( relationType == XActRelationshipDocument.APND ) { CD value = new CD(); fetchAttributes(Kasaaja.LM_UUSIMISPYYNTO, value); relatedDocument.getParentDocument().setCode(value); if ( !StringUtils.isEmpty(setid) ) { relatedDocument.getParentDocument().setSetId(of.createII()); relatedDocument.getParentDocument().getSetId().setRoot(setid); } } else { relatedDocument.getParentDocument().setSetId(of.createII()); relatedDocument.getParentDocument().getSetId().setRoot(setid); } }
Example 9
Source File: Kasaaja.java From KantaCDA-API with Apache License 2.0 | 5 votes |
protected String getDocumentId(final LeimakentatTO<?> leimakentat) { if ( StringUtils.isEmpty(documentId) ) { documentId = generator.createNewDocumentOid(leimakentat.getCDAOidBase()); } return documentId; }
Example 10
Source File: StartContainerExecutor.java From docker-maven-plugin with Apache License 2.0 | 5 votes |
String getExposedPropertyKeyPart() { String propKey = imageConfig.getRunConfiguration() != null ? imageConfig.getRunConfiguration().getExposedPropertyKey() : ""; if (StringUtils.isEmpty(propKey)) { propKey = imageConfig.getAlias(); } return propKey; }
Example 11
Source File: AbstractCodegenMojo.java From cxf with Apache License 2.0 | 5 votes |
private void restoreProxySetting(String originalProxyHost, String originalProxyPort, String originalNonProxyHosts, String originalProxyUser, String originalProxyPassword) { if (originalProxyHost != null) { System.setProperty(HTTP_PROXY_HOST, originalProxyHost); } else { System.getProperties().remove(HTTP_PROXY_HOST); } if (originalProxyPort != null) { System.setProperty(HTTP_PROXY_PORT, originalProxyPort); } else { System.getProperties().remove(HTTP_PROXY_PORT); } if (originalNonProxyHosts != null) { System.setProperty(HTTP_NON_PROXY_HOSTS, originalNonProxyHosts); } else { System.getProperties().remove(HTTP_NON_PROXY_HOSTS); } if (originalProxyUser != null) { System.setProperty(HTTP_PROXY_USER, originalProxyUser); } else { System.getProperties().remove(HTTP_PROXY_USER); } if (originalProxyPassword != null) { System.setProperty(HTTP_PROXY_PASSWORD, originalProxyPassword); } else { System.getProperties().remove(HTTP_PROXY_PASSWORD); } Proxy proxy = mavenSession.getSettings().getActiveProxy(); if (proxy != null && !StringUtils.isEmpty(proxy.getUsername()) && !StringUtils.isEmpty(proxy.getPassword())) { Authenticator.setDefault(null); } }
Example 12
Source File: Platform.java From appassembler with MIT License | 5 votes |
private String addJvmSetting( String argType, String extraJvmArgument, String vmArgs ) { if ( StringUtils.isEmpty( extraJvmArgument ) ) { return vmArgs; } return vmArgs + " " + argType + extraJvmArgument; }
Example 13
Source File: SimpleTests.java From azure-documentdb-java with MIT License | 4 votes |
private void readIds() throws IOException { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); connectionPolicy.setConnectionMode(ConnectionMode.valueOf(connectionMode)); List<String> regions = Arrays.asList(preferredRegions.split(";")); connectionPolicy.setPreferredLocations(regions); client = new DocumentClient(endpoint, key, connectionPolicy, ConsistencyLevel.valueOf(consistencyLevel)); final String collectionLink = String.format("dbs/%s/colls/%s", dbName, collectionName); List<PartitionKeyRange> partitionKeyRanges = client.readPartitionKeyRanges(collectionLink, (FeedOptions) null) .getQueryIterable().toList(); List<String> ids = new ArrayList<>(); for (PartitionKeyRange r : partitionKeyRanges) { FeedOptions feedOptions = new FeedOptions(); feedOptions.setPartitionKeyRangeIdInternal(r.getId()); feedOptions.setPageSize(1); try { List<Document> docs = client.readDocuments(collectionLink, feedOptions).getQueryIterable().fetchNextBlock(); for (Document doc : docs) { ids.add(doc.getId()); } } catch (DocumentClientException e) { logger.error("Failed to read documents from partition {}", r.getId()); } } if (StringUtils.isEmpty(docIdFilePath)) { logger.error("IDs file path is empty"); return; } PrintWriter writer = new PrintWriter(new FileWriter(docIdFilePath)); for (String idString : ids) { writer.println(idString); } writer.close(); }
Example 14
Source File: DefaultDaemonGeneratorService.java From appassembler with MIT License | 4 votes |
public void generateDaemon( DaemonGenerationRequest request ) throws DaemonGeneratorException { String platform = request.getPlatform(); if ( platform == null || StringUtils.isEmpty( platform ) ) { throw new DaemonGeneratorException( "Missing required property in request: platform." ); } // ----------------------------------------------------------------------- // Get the generator // ----------------------------------------------------------------------- DaemonGenerator generator = (DaemonGenerator) generators.get( platform ); if ( generator == null ) { throw new DaemonGeneratorException( "Could not find a generator for platform '" + platform + "'." ); } // ----------------------------------------------------------------------- // Load the model // ----------------------------------------------------------------------- Daemon fileDaemon = null; File stubDescriptor = request.getStubDescriptor(); if ( stubDescriptor != null ) { getLogger().debug( "Loading daemon descriptor: " + stubDescriptor.getAbsolutePath() ); fileDaemon = loadModel( stubDescriptor ); } // ----------------------------------------------------------------------- // Merge the given stub daemon // ----------------------------------------------------------------------- Daemon mergedDaemon = mergeDaemons( request.getStubDaemon(), fileDaemon ); // ----------------------------------------------------------------------- // // ----------------------------------------------------------------------- validateDaemon( mergedDaemon, stubDescriptor ); // ----------------------------------------------------------------------- // Generate! // ----------------------------------------------------------------------- request.setDaemon( mergedDaemon ); generator.generate( request ); }
Example 15
Source File: JpaSchemaGeneratorMojo.java From jpa-schema-maven-plugin with Apache License 2.0 | 4 votes |
public String getLineSeparator() { String actual = StringUtils.isEmpty(lineSeparator) ? null : LINE_SEPARATOR_MAP.get(lineSeparator.toUpperCase()); return actual == null ? System.getProperty("line.separator", "\n") : actual; }
Example 16
Source File: SimpleTests.java From azure-documentdb-java with MIT License | 4 votes |
private void readThroughput() throws InterruptedException { ConnectionPolicy connectionPolicy = new ConnectionPolicy(); connectionPolicy.setConnectionMode(ConnectionMode.valueOf(connectionMode)); if (connectionPoolSize > 0) { connectionPolicy.setMaxPoolSize(connectionPoolSize); } if (requestTimeout > 0) { connectionPolicy.setRequestTimeout(requestTimeout); } if (idleConnectionTimeout > 0) { connectionPolicy.setIdleConnectionTimeout(idleConnectionTimeout); } connectionPolicy.setEnableEndpointDiscovery(false); List<String> regions = Arrays.asList(preferredRegions.split(";")); connectionPolicy.setPreferredLocations(regions); client = new DocumentClient(endpoint, key, connectionPolicy, ConsistencyLevel.valueOf(consistencyLevel)); List<String> documentIds = new ArrayList<>(); if (!StringUtils.isEmpty(docIdFilePath)) { try { File file = new File(docIdFilePath); FileReader fileReader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; while ((line = bufferedReader.readLine()) != null) { documentIds.add(line); } fileReader.close(); } catch (Exception e) { logger.error("Failed to read document IDs list at {}", docIdFilePath, e); } } else if (!StringUtils.isEmpty(docId)) { documentIds.add(docId); } if (documentIds.size() == 0) { logger.error("Cannot continue with empty Document IDs list."); return; } Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; ++i) { final int index = i; threads[i] = new Thread(new Runnable() { @Override public void run() { LatencyLogger latencyLogger = new LatencyLogger(!StringUtils.isEmpty(logLatencyPath), String.format("%s/%d-thread%03d.log", logLatencyPath, runId, index), warmupRequestCount, logBatchEntryCount, printLatency); long remainingOperations = totalOperations; while (remainingOperations-- > 0) { try { String docId = documentIds.get(index % documentIds.size()); RequestOptions options = new RequestOptions(); options.setPartitionKey(new PartitionKey(docId)); String documentLink = String.format("dbs/%s/colls/%s/docs/%s", dbName, collectionName, docId); latencyLogger.requestStart(); Document readDocument = client.readDocument(documentLink, options).getResource(); latencyLogger.requestEnd(); successMeter.mark(); } catch (Exception e) { logger.error(e.getMessage(), e); failureMeter.mark(); } } latencyLogger.writeToLogFile(); } }); threads[i].start(); } for (Thread t : threads) { if (t != null) { t.join(); } } }
Example 17
Source File: DefaultDaemonGeneratorService.java From appassembler with MIT License | 4 votes |
public void validateDaemon( Daemon daemon, File descriptor ) throws DaemonGeneratorException { if ( daemon == null ) { throw new DaemonGeneratorException( "Illegal argument: daemon must be passed." ); } String mainClass = daemon.getMainClass(); String missingRequiredField; if ( descriptor != null ) { missingRequiredField = "Missing required field from '" + descriptor.getAbsolutePath() + "': "; } else { missingRequiredField = "Missing required field in daemon descriptor: "; } // ----------------------------------------------------------------------- // // ----------------------------------------------------------------------- if ( StringUtils.isEmpty( daemon.getWrapperMainClass() ) && StringUtils.isEmpty( mainClass ) ) { throw new DaemonGeneratorException( missingRequiredField + "mainClass or wrapperMainClass" ); } if ( StringUtils.isEmpty( daemon.getId() ) ) { String id = mainClass; if ( StringUtils.isEmpty( id ) ) { throw new DaemonGeneratorException( missingRequiredField + "id" ); } int i = id.lastIndexOf( '.' ); if ( i > 0 ) { id = mainClass.substring( i + 1 ); } id = StringUtils.addAndDeHump( id ); daemon.setId( id ); } }
Example 18
Source File: NativeLinkMojo.java From maven-native with MIT License | 4 votes |
@Override public void execute() throws MojoExecutionException { if ( StringUtils.isEmpty( this.classifier ) ) { this.classifier = null; } Linker linker = this.getLinker(); this.config = this.createLinkerConfiguration(); try { List<File> allCompilerOuputFiles = this.getAllCompilersOutputFileList(); File outputFile = linker.link( config, allCompilerOuputFiles ); allCompilerOuputFiles.clear(); // to be used by post linker mojo like native:manifest @SuppressWarnings({ "unused", "unchecked" }) Object unchecked = this.getPluginContext().put( AbstractNativeMojo.LINKER_OUTPUT_PATH, outputFile ); } catch ( IOException ioe ) { throw new MojoExecutionException( ioe.getMessage(), ioe ); } catch ( NativeBuildException nbe ) { throw new MojoExecutionException( nbe.getMessage(), nbe ); } if ( this.attach ) { this.attachPrimaryArtifact(); this.attachSecondaryArtifacts(); } }
Example 19
Source File: JpaSchemaGeneratorUtils.java From jpa-schema-maven-plugin with Apache License 2.0 | 4 votes |
public static Map<String, Object> buildProperties(JpaSchemaGeneratorMojo mojo) { Map<String, Object> map = new HashMap<>(); Map<String, String> properties = mojo.getProperties(); /* * Common JPA options */ // mode map.put(Constants.JAVAX_SCHEMA_GENERATION_DATABASE_ACTION, mojo.getDatabaseAction().toLowerCase()); map.put(Constants.JAVAX_SCHEMA_GENERATION_SCRIPTS_ACTION, mojo.getScriptAction().toLowerCase()); // output files if (isScriptTarget(mojo)) { if (mojo.getOutputDirectory() == null) { throw new NullArgumentException("outputDirectory is required for script generation."); } map.put(Constants.JAVAX_SCHEMA_GENERATION_SCRIPTS_CREATE_TARGET, mojo.getCreateOutputFile().toURI().toString()); map.put(Constants.JAVAX_SCHEMA_GENERATION_SCRIPTS_DROP_TARGET, mojo.getDropOutputFile().toURI().toString()); } // database emulation options map.put(Constants.JAVAX_SCHEMA_DATABASE_PRODUCT_NAME, mojo.getDatabaseProductName()); map.put(Constants.JAVAX_SCHEMA_DATABASE_MAJOR_VERSION, Optional.ofNullable(mojo.getDatabaseMajorVersion()).map(String::valueOf)); map.put(Constants.JAVAX_SCHEMA_DATABASE_MINOR_VERSION, Optional.ofNullable(mojo.getDatabaseMinorVersion()).map(String::valueOf)); // database options map.put(Constants.JAVAX_JDBC_DRIVER, mojo.getJdbcDriver()); map.put(Constants.JAVAX_JDBC_URL, mojo.getJdbcUrl()); map.put(Constants.JAVAX_JDBC_USER, mojo.getJdbcUser()); map.put(Constants.JAVAX_JDBC_PASSWORD, mojo.getJdbcPassword()); // source selection map.put(Constants.JAVAX_SCHEMA_GENERATION_CREATE_SOURCE, mojo.getCreateSourceMode()); if (mojo.getCreateSourceFile() == null) { if (!Constants.JAVAX_SCHEMA_GENERATION_METADATA_SOURCE.equals(mojo.getCreateSourceMode())) { throw new IllegalArgumentException("create source file is required for mode " + mojo.getCreateSourceMode()); } } else { map.put(Constants.JAVAX_SCHEMA_GENERATION_CREATE_SCRIPT_SOURCE, mojo.getCreateSourceFile().toURI().toString()); } map.put(Constants.JAVAX_SCHEMA_GENERATION_DROP_SOURCE, mojo.getDropSourceMode()); if (mojo.getDropSourceFile() == null) { if (!Constants.JAVAX_SCHEMA_GENERATION_METADATA_SOURCE.equals(mojo.getDropSourceMode())) { throw new IllegalArgumentException("drop source file is required for mode " + mojo.getDropSourceMode()); } } else { map.put(Constants.JAVAX_SCHEMA_GENERATION_DROP_SCRIPT_SOURCE, mojo.getDropSourceFile().toURI().toString()); } /* * EclipseLink specific */ // persistence.xml map.put(Constants.ECLIPSELINK_PERSISTENCE_XML, mojo.getPersistenceXml()); // disable weaving map.put(Constants.ECLIPSELINK_WEAVING, "false"); /* * Hibernate specific */ final String productName = mojo.getDatabaseProductName(); final int minorVersion = Optional.ofNullable(mojo.getDatabaseMinorVersion()).orElse(0); final int majorVersion = Optional.ofNullable(mojo.getDatabaseMajorVersion()).orElse(0); // auto-detect map.put(Constants.HIBERNATE_AUTODETECTION, "class,hbm"); // dialect (without jdbc connection) String dialect = properties.get(Constants.HIBERNATE_DIALECT); if (StringUtils.isEmpty(dialect) && StringUtils.isEmpty(mojo.getJdbcUrl())) { dialect = HibernateDialectResolver.resolve(productName, majorVersion, minorVersion); } if (dialect != null) { properties.remove(Constants.HIBERNATE_DIALECT); map.put(Constants.HIBERNATE_DIALECT, dialect); } if (!isDatabaseTarget(mojo) && StringUtils.isEmpty(mojo.getJdbcUrl())) { map.put(Constants.JAVAX_SCHEMA_GEN_CONNECTION, new ConnectionMock(productName, majorVersion, minorVersion)); } map.putAll(mojo.getProperties()); /* force override JTA to RESOURCE_LOCAL */ map.put(Constants.JAVAX_TRANSACTION_TYPE, Constants.JAVAX_TRANSACTION_TYPE_RESOURCE_LOCAL); map.put(Constants.JAVAX_JTA_DATASOURCE, null); map.put(Constants.JAVAX_NON_JTA_DATASOURCE, null); map.put(Constants.JAVAX_VALIDATION_MODE, "NONE"); // normalize - remove null List<String> keys = new ArrayList<>(map.keySet()); for (String key : keys) { if (map.get(key) == null) { map.remove(key); } } return map; }
Example 20
Source File: FormatterMojo.java From formatter-maven-plugin with Apache License 2.0 | 4 votes |
/** * Execute. * * @throws MojoExecutionException * the mojo execution exception * @throws MojoFailureException * the mojo failure exception * * @see org.apache.maven.plugin.AbstractMojo#execute() */ @Override public void execute() throws MojoExecutionException, MojoFailureException { if (this.skipFormatting) { getLog().info("Formatting is skipped"); return; } long startClock = System.currentTimeMillis(); if (StringUtils.isEmpty(this.encoding)) { this.encoding = ReaderFactory.FILE_ENCODING; getLog().warn("File encoding has not been set, using platform encoding (" + this.encoding + ") to format source files, i.e. build is platform dependent!"); } else { if (!Charset.isSupported(this.encoding)) { throw new MojoExecutionException("Encoding '" + this.encoding + "' is not supported"); } getLog().info("Using '" + this.encoding + "' encoding to format source files."); } List<File> files = new ArrayList<>(); if (this.directories != null) { for (File directory : this.directories) { if (directory.exists() && directory.isDirectory()) { files.addAll(addCollectionFiles(directory)); } } } else { // Using defaults of source main and test dirs if (this.sourceDirectory != null && this.sourceDirectory.exists() && this.sourceDirectory.isDirectory()) { files.addAll(addCollectionFiles(this.sourceDirectory)); } if (this.testSourceDirectory != null && this.testSourceDirectory.exists() && this.testSourceDirectory.isDirectory()) { files.addAll(addCollectionFiles(this.testSourceDirectory)); } } int numberOfFiles = files.size(); Log log = getLog(); log.info("Number of files to be formatted: " + numberOfFiles); if (numberOfFiles > 0) { createCodeFormatter(); ResultCollector rc = new ResultCollector(); Properties hashCache = readFileHashCacheFile(); String basedirPath = getBasedirPath(); for (int i = 0, n = files.size(); i < n; i++) { File file = files.get(i); if (file.exists()) { if (file.canWrite()) { formatFile(file, rc, hashCache, basedirPath); } else { rc.readOnlyCount++; } } else { rc.failCount++; } } storeFileHashCache(hashCache); long endClock = System.currentTimeMillis(); log.info("Successfully formatted: " + rc.successCount + FILE_S); log.info("Fail to format: " + rc.failCount + FILE_S); log.info("Skipped: " + rc.skippedCount + FILE_S); log.info("Read only skipped: " + rc.readOnlyCount + FILE_S); log.info("Approximate time taken: " + ((endClock - startClock) / 1000) + "s"); } }