Example usage for org.apache.commons.lang3 StringUtils center

List of usage examples for org.apache.commons.lang3 StringUtils center

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils center.

Prototype

public static String center(String str, final int size, String padStr) 

Source Link

Document

Centers a String in a larger String of size size .

Usage

From source file:de.vandermeer.asciitable.v1.V1_AsciiTable.java

/**
 * Renders rows of content with correct separators.
 * @param row array with all lines for all columns of a single row
 * @param padChar padding character//from   w  w  w.j a v a 2  s .  c o m
 * @param theme row theme
 * @return rendered lines for the row, empty if nothing was to be rendered
 */
protected final StrBuilder renderRow(String[][] row, char padChar, char[] theme) {
    StrBuilder ret = new StrBuilder(100);
    ret.setNullText("");
    for (int k = 0; k < row.length; k++) {
        String[] ar = row[k];
        ret.append(theme[V1_TableTheme.VERTICAL]);
        //if null is in array we need to render column spans
        if (ArrayUtils.contains(ar, null)) {
            int span = 0;
            for (int i = 0; i < ar.length; i++) {
                String content = ar[i];
                if (content == null) {
                    if (i == ar.length - 1) {
                        //a null in last column, so calculate the span)
                        int width = 0;
                        //add the span column width
                        for (k = 0; k < span; k++) {
                            width += this.columns[k + 1];
                        }
                        //add the separator characters (span) plus the one for this column
                        width += span;
                        //add the current column width
                        width += this.columns[i + 1];
                        //centre content in the new column
                        ret.appendFixedWidthPadRight("", width, padChar);
                    } else {
                        span += 1;
                        continue;
                    }
                } else if ("".equals(content)) {
                    //we have an empty column, so
                    //first finish the spans
                    for (k = 0; k < span; k++) {
                        ret.appendFixedWidthPadRight("", this.columns[k + 1], padChar);
                    }
                    ret.appendFixedWidthPadRight("", span, padChar);
                    ret.append(theme[V1_TableTheme.VERTICAL]);
                    span = 0;
                    //now add the empty column
                    ret.appendFixedWidthPadRight(content, this.columns[i + 1], padChar);
                    if (i < ar.length - 1) {
                        ret.append(theme[V1_TableTheme.VERTICAL]);
                    }
                } else {
                    int width = 0;
                    //add the span column width
                    for (k = 0; k < span; k++) {
                        width += this.columns[k + 1];
                    }
                    //add the separator characters (span) plus the one for this column
                    width += span;
                    //add the current column width
                    width += this.columns[i + 1];
                    //centre content in the new column
                    ret.append(StringUtils.center(content, width, padChar));
                    if (i < ar.length - 1) {
                        ret.append(theme[V1_TableTheme.VERTICAL]);
                    }
                    span = 0;
                }
            }
        } else {
            for (int i = 0; i < ar.length; i++) {
                String content = ar[i];
                ret.appendFixedWidthPadRight(content, this.columns[i + 1], padChar);
                if (i < ar.length - 1) {
                    ret.append(theme[V1_TableTheme.VERTICAL]);
                }
            }
        }
        ret.append(theme[V1_TableTheme.VERTICAL]);
        if (k < row.length - 1) {
            ret.append('\n');
        }
    }

    return ret;
}

From source file:de.vandermeer.asciitable.v1.AsciiTable.java

/**
 * Renders rows of content with correct separators.
 * @param row array with all lines for all columns of a single row
 * @param padChar padding character//from ww  w . ja va 2s .  c  o  m
 * @param theme row theme
 * @return rendered lines for the row, empty if nothing was to be rendered
 */
protected final StrBuilder renderRow(String[][] row, char padChar, char[] theme) {
    StrBuilder ret = new StrBuilder(100);
    ret.setNullText("");
    for (int k = 0; k < row.length; k++) {
        String[] ar = row[k];
        ret.append(theme[TableTheme.VERTICAL]);
        //if null is in array we need to render column spans
        if (ArrayUtils.contains(ar, null)) {
            int span = 0;
            for (int i = 0; i < ar.length; i++) {
                String content = ar[i];
                if (content == null) {
                    if (i == ar.length - 1) {
                        //a null in last column, so calculate the span)
                        int width = 0;
                        //add the span column width
                        for (k = 0; k < span; k++) {
                            width += this.columns[k + 1];
                        }
                        //add the separator characters (span) plus the one for this column
                        width += span;
                        //add the current column width
                        width += this.columns[i + 1];
                        //centre content in the new column
                        ret.appendFixedWidthPadRight("", width, padChar);
                    } else {
                        span += 1;
                        continue;
                    }
                } else if ("".equals(content)) {
                    //we have an empty column, so
                    //first finish the spans
                    for (k = 0; k < span; k++) {
                        ret.appendFixedWidthPadRight("", this.columns[k + 1], padChar);
                    }
                    ret.appendFixedWidthPadRight("", span, padChar);
                    ret.append(theme[TableTheme.VERTICAL]);
                    span = 0;
                    //now add the empty column
                    ret.appendFixedWidthPadRight(content, this.columns[i + 1], padChar);
                    if (i < ar.length - 1) {
                        ret.append(theme[TableTheme.VERTICAL]);
                    }
                } else {
                    int width = 0;
                    //add the span column width
                    for (k = 0; k < span; k++) {
                        width += this.columns[k + 1];
                    }
                    //add the separator characters (span) plus the one for this column
                    width += span;
                    //add the current column width
                    width += this.columns[i + 1];
                    //centre content in the new column
                    ret.append(StringUtils.center(content, width, padChar));
                    if (i < ar.length - 1) {
                        ret.append(theme[TableTheme.VERTICAL]);
                    }
                    span = 0;
                }
            }
        } else {
            for (int i = 0; i < ar.length; i++) {
                String content = ar[i];
                ret.appendFixedWidthPadRight(content, this.columns[i + 1], padChar);
                if (i < ar.length - 1) {
                    ret.append(theme[TableTheme.VERTICAL]);
                }
            }
        }
        ret.append(theme[TableTheme.VERTICAL]);
        if (k < row.length - 1) {
            ret.append('\n');
        }
    }

    return ret;
}

From source file:org.apache.nifi.processors.standard.LogAttribute.java

protected String processFlowFile(final ComponentLog logger, final DebugLevels logLevel, final FlowFile flowFile,
        final ProcessSession session, final ProcessContext context) {
    final Set<String> attributeKeys = getAttributesToLog(flowFile.getAttributes().keySet(), context);
    final ComponentLog LOG = getLogger();
    final String dashedLine;

    String logPrefix = context.getProperty(LOG_PREFIX).evaluateAttributeExpressions(flowFile).getValue();

    if (StringUtil.isBlank(logPrefix)) {
        dashedLine = StringUtils.repeat('-', 50);
    } else {/*from   w  w w .j ava 2  s .com*/
        // abbreviate long lines
        logPrefix = StringUtils.abbreviate(logPrefix, 40);
        // center the logPrefix and pad with dashes
        logPrefix = StringUtils.center(logPrefix, 40, '-');
        // five dashes on the left and right side, plus the dashed logPrefix
        dashedLine = StringUtils.repeat('-', 5) + logPrefix + StringUtils.repeat('-', 5);
    }

    // Pretty print metadata
    final StringBuilder message = new StringBuilder();
    message.append("logging for flow file ").append(flowFile);
    message.append("\n");
    message.append(dashedLine);
    message.append("\nStandard FlowFile Attributes");
    message.append(
            String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "entryDate", new Date(flowFile.getEntryDate())));
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "lineageStartDate",
            new Date(flowFile.getLineageStartDate())));
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "fileSize", flowFile.getSize()));
    message.append("\nFlowFile Attribute Map Content");
    for (final String key : attributeKeys) {
        message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", key, flowFile.getAttribute(key)));
    }
    message.append("\n");
    message.append(dashedLine);

    // The user can request to log the payload
    final boolean logPayload = context.getProperty(LOG_PAYLOAD).asBoolean();
    if (logPayload) {
        message.append("\n");
        if (flowFile.getSize() < ONE_MB) {
            final FlowFilePayloadCallback callback = new FlowFilePayloadCallback();
            session.read(flowFile, callback);
            message.append(callback.getContents());
        } else {
            message.append("\n Not including payload since it is larger than one mb.");
        }
    }
    final String outputMessage = message.toString().trim();
    // Uses optional property to specify logging level
    switch (logLevel) {
    case info:
        LOG.info(outputMessage);
        break;
    case debug:
        LOG.debug(outputMessage);
        break;
    case warn:
        LOG.warn(outputMessage);
        break;
    case trace:
        LOG.trace(outputMessage);
        break;
    case error:
        LOG.error(outputMessage);
        break;
    default:
        LOG.debug(outputMessage);
    }

    return outputMessage;

}

From source file:org.pepstock.jem.ant.tasks.StepExec.java

/**
 * Prepares the files required by ANT file using the data description, locks
 * them, and prepares the right file name for GDG. Afterwards calls the
 * executable command defined in the task.
 * //from w ww.ja va  2s .  c  o m
 * @throws BuildException occurs if an error occurs
 */
@Override
public void execute() throws BuildException {
    int returnCode = Result.SUCCESS;
    // this boolean is necessary to understand if I have an exception
    // before calling the main class
    boolean isExecutionStarted = false;

    AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);
    // creates a list with all data description impl
    List<DataDescriptionImpl> ddList = null;

    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(this);
        // if list of data description is empty, go to execute the command
        if (!ddList.isEmpty()) {

            // after locking, checks for GDG
            // is sure here the root (is a properties file) of GDG is locked
            // (doesn't matter if in READ or WRITE)
            // so can read a consistent data from root and gets the right
            // generation
            // starting from relative position
            for (DataDescriptionImpl ddImpl : ddList) {
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);
                log(AntMessage.JEMA034I.toMessage().getFormattedMessage(ddImpl));
                // scans all datasets of datadescription adding new
                // environment variable
                for (DataSetImpl dataset : ddImpl.getDatasets()) {
                    addEnvVariable(ddImpl.getName(), dataset.getRealFile());
                }
            }

        }

        // calls super-method to execute the command configured into JCL
        batchSM.setInternalAction(false);
        // executes the program defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        super.execute();
    } catch (BuildException e1) {
        returnCode = Result.ERROR;
        throw e1;
    } catch (RemoteException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (IOException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } finally {
        batchSM.setInternalAction(true);

        Object rcObject = PropertyHelper.getPropertyHelper(getProject()).getProperty(RESULT_KEY);
        if (rcObject != null) {
            returnCode = Parser.parseInt(rcObject.toString(), Result.SUCCESS);
        }
        ReturnCodesContainer.getInstance().setReturnCode(getProject(), this, returnCode);

        // finally and always must release the locks previously asked
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : ddList) {
                try {
                    // consolidates the GDG situation
                    // changing the root (is a properties file)
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    if (exceptions.length() == 0) {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
            }
            if (exceptions.length() > 0) {
                log(StringUtils.center("ATTENTION", 40, "-"));
                log(exceptions.toString());
            }
        }
        batchSM.setInternalAction(false);
    }
}

From source file:org.pepstock.jem.ant.tasks.StepJava.java

/**
 * Prepares the files required by ANT file using the data description, locks
 * them, and prepares the right file name for GDG. Afterwards calls the java
 * main class defined in the task.//ww  w  . j  av a  2s  .c o  m
 * 
 * @throws BuildException occurs if an error occurs
 */
@Override
public void execute() throws BuildException {
    int returnCode = Result.SUCCESS;
    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;

    AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);

    // object serializer and deserializer into XML
    XStream xstream = new XStream();

    List<DataDescriptionImpl> ddList = null;
    InitialContext ic = null;
    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(this);
        // new intial context for JNDI
        ic = ContextUtils.getContext();

        // LOADS DataPaths Container
        Reference referencePaths = new DataPathsReference();
        // loads dataPaths on static name
        String xmlPaths = xstream.toXML(DataPathsContainer.getInstance());
        // adds the String into a data stream reference
        referencePaths.add(new StringRefAddr(StringRefAddrKeys.DATAPATHS_KEY, xmlPaths));
        // re-bind the object inside the JNDI context
        ic.rebind(AntKeys.ANT_DATAPATHS_BIND_NAME, referencePaths);

        // scans all datasource passed
        for (DataSource source : sources) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new BuildException(AntMessage.JEMA027E.toMessage().getFormattedMessage());
            } else if (source.getName() == null) {
                // if name is missing, it uses the same string 
                // used to define the resource
                source.setName(source.getResource());
            }

            // gets the RMi object to get resources
            CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
            // lookups by RMI for the database 
            Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
            if (!batchSM.checkResource(res)) {
                throw new BuildException(AntMessage.JEMA028E.toMessage().getFormattedMessage(res.toString()));
            }

            // all properties create all StringRefAddrs necessary  
            Map<String, ResourceProperty> properties = res.getProperties();

            // scans all properteis set by JCL
            for (Property property : source.getProperties()) {
                if (property.isCustom()) {
                    if (res.getCustomProperties() == null) {
                        res.setCustomProperties(new HashMap<String, String>());
                    }
                    if (!res.getCustomProperties().containsKey(property.getName())) {
                        res.getCustomProperties().put(property.getName(), property.getText().toString());
                    } else {
                        throw new BuildException(
                                AntMessage.JEMA028E.toMessage().getFormattedMessage(property.getName(), res));
                    }
                } else {
                    // if a key is defined FINAL, throw an exception
                    for (ResourceProperty resProperty : properties.values()) {
                        if (resProperty.getName().equalsIgnoreCase(property.getName())
                                && !resProperty.isOverride()) {
                            throw new BuildException(AntMessage.JEMA028E.toMessage()
                                    .getFormattedMessage(property.getName(), res));
                        }
                    }
                    ResourcePropertiesUtil.addProperty(res, property.getName(), property.getText().toString());
                }
            }

            // creates a JNDI reference
            Reference ref = getReference(resourcer, res, source, ddList);

            // loads all properties into RefAddr
            for (ResourceProperty property : properties.values()) {
                ref.add(new StringRefAddr(property.getName(), replaceProperties(property.getValue())));
            }

            // loads custom properties in a string format
            if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
                // loads all entries and substitute variables
                for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                    String value = replaceProperties(entry.getValue());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with [name]
            log(AntMessage.JEMA035I.toMessage().getFormattedMessage(res));
            ic.rebind(source.getName(), ref);
        }

        // if list of data description is empty, go to execute java main
        // class
        if (!ddList.isEmpty()) {

            // after locking, checks for GDG
            // is sure here the root (is a properties file) of GDG is locked
            // (doesn't matter if in READ or WRITE)
            // so can read a consistent data from root and gets the right
            // generation
            // starting from relative position
            for (DataDescriptionImpl ddImpl : ddList) {
                // creates a reference, accessible by name. Is data stream
                // reference because
                // contains a stream of data which represents a object
                Reference reference = new DataStreamReference();
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);

                log(AntMessage.JEMA034I.toMessage().getFormattedMessage(ddImpl));
                // serialize data descriptor object into xml string
                // in this way is easier pass to object across different
                // classloader, by JNDI.
                // This xml, by reference, will be used by DataStreamFactory
                // when
                // java main class requests a resource by a JNDI call
                String xml = xstream.toXML(ddImpl);
                // adds the String into a data stream reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));
                // re-bind the object inside the JNDI context
                ic.rebind(ddImpl.getName(), reference);
            }

        }
        // sets fork to false
        // in this way java main class runs inside the same process
        // this is mandatory if wants to JNDI without any network
        // connection, like RMI
        super.setFork(false);

        // changes the main class to apply the annotations of JEM
        setCustomMainClass();

        batchSM.setInternalAction(false);
        // executes the java main class defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        // tried to set fields where
        // annotations are used
        super.execute();
    } catch (BuildException e) {
        returnCode = Result.ERROR;
        throw e;
    } catch (RemoteException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (IOException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (NamingException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } finally {
        batchSM.setInternalAction(true);
        String rcObject = System.getProperty(RESULT_KEY);
        if (rcObject != null) {
            returnCode = Parser.parseInt(rcObject, Result.SUCCESS);
        }
        ReturnCodesContainer.getInstance().setReturnCode(getProject(), this, returnCode);
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : ddList) {
                try {
                    // consolidates the GDG situation
                    // changing the root (is a properties file)
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    if (exceptions.length() == 0) {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA037E.toMessage().getFormattedMessage(e.getMessage()));
                }
            }
            for (DataSource source : sources) {
                if (source.getName() != null) {
                    // unbinds all resources
                    try {
                        ic.unbind(source.getName());
                    } catch (NamingException e) {
                        // ignore
                        LogAppl.getInstance().ignore(e.getMessage(), e);
                        log(AntMessage.JEMA037E.toMessage().getFormattedMessage(e.getMessage()));
                    }
                }
            }
            // checks if has exception using the stringbuffer
            // used to collect exception string. 
            // Stringbuffer is not empty, throws an exception
            if (exceptions.length() > 0) {
                log(StringUtils.center("ATTENTION", 40, "-"));
                log(exceptions.toString());
            }
            batchSM.setInternalAction(false);
        }
    }
}

From source file:org.pepstock.jem.ant.tasks.WrapperTask.java

/**
 * Prepares the files required by ANT file using the data description, locks
 * them, and prepares the right file name for GDG. Afterwards calls the
 * defined task.//from   w w w  . j av  a  2 s  .co m
 * 
 * @throws BuildException occurs if an error occurs
 */
@Override
public void execute() throws BuildException {
    // this boolean is necessary to understand if I have an exception
    // before calling the main class
    boolean isExecutionStarted = false;

    AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);
    // creates a list with all data description impl
    List<DataDescriptionImpl> ddList = null;

    PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(getProject());

    // creates a thread local properties
    LocalProperties localProperties = LocalProperties.get(getProject());

    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(this);

        // if list of data description is empty, go to execute the command
        if (!ddList.isEmpty()) {
            // sets scope per properties and calls task
            // MUST BE CALLED BEFORE ADDLOCAL
            localProperties.enterScope();

            // this cycle must load variables to local properties
            for (DataDescriptionImpl ddImpl : ddList) {
                // MUST BE CALLED BEFORE setProperty of all proprties
                localProperties.addLocal(StepExec.DD_PREFIX + ddImpl.getName());
            }

            // after locking, checks for GDG
            // is sure here the root (is a properties file) of GDG is locked
            // (doesn't matter if in READ or WRITE)
            // so can read a consistent data from root and gets the right
            // generation
            // starting from relative position
            for (DataDescriptionImpl ddImpl : ddList) {
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);
                log(AntMessage.JEMA034I.toMessage().getFormattedMessage(ddImpl));
                // scans all datasets of datadescription adding new
                // environment variable
                for (DataSetImpl dataset : ddImpl.getDatasets()) {
                    propertyHelper.setProperty(StepExec.DD_PREFIX + ddImpl.getName(),
                            dataset.getRealFile().getAbsolutePath(), true);
                }
            }

        }
        // calls super-method to execute the command configured into JCL
        batchSM.setInternalAction(false);
        // executes the program defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        nestedTask.perform();
    } catch (BuildException e1) {
        throw e1;
    } catch (RemoteException e) {
        throw new BuildException(e);
    } catch (IOException e) {
        throw new BuildException(e);
    } finally {
        batchSM.setInternalAction(true);
        // finally and always must release the locks previously asked
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            // clean scope of properties
            localProperties.exitScope();

            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : ddList) {
                try {
                    // consolidates the GDG situation
                    // changing the root (is a properties file)
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    if (exceptions.length() == 0) {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
            }
            if (exceptions.length() > 0) {
                log(StringUtils.center("ATTENTION", 40, "-"));
                log(exceptions.toString());
            }
        }
        batchSM.setInternalAction(false);
    }
}

From source file:org.pepstock.jem.springbatch.tasks.JemTasklet.java

/**
 * Is called by SpringBatch framework to execute business logic.<br>
 * Prepares datasets (and the files and resources) which could be used from
 * implementation of this class.<br>
 * Loads JNDI context so all resources could be used by their name, defined
 * in JCL.//w  ww  .j ava 2 s  .  c  o m
 * 
 * @param stepContribution step contribution, passed by SpringBatch core
 * @param chunkContext chunk context, passed by SpringBatch core
 * @return always the status returned by abstract method
 *         <code>executeByJem</code>
 * @throws SpringBatchException if a error occurs
 */
@Override
public final RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext)
        throws SpringBatchException {
    LogAppl.getInstance();

    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;
    boolean isAbended = false;

    SpringBatchSecurityManager batchSM = (SpringBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);

    RepeatStatus status = null;

    // extract stepContext because the step name is necessary
    StepContext stepContext = chunkContext.getStepContext();

    List<DataDescriptionImpl> dataDescriptionImplList = ImplementationsContainer.getInstance()
            .getDataDescriptionsByItem(stepContext.getStepName());

    // new initial context for JNDI
    InitialContext ic = null;

    try {
        ic = ContextUtils.getContext();
        // scans all datasource passed
        for (DataSource source : dataSourceList) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new SpringBatchException(SpringBatchMessage.JEMS016E);
            } else if (source.getName() == null) {
                // if name is missing, it uses the same string 
                // used to define the resource
                source.setName(source.getResource());
            }
            // gets the RMi object to get resources
            CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
            // lookups by RMI for the database 
            Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
            if (!batchSM.checkResource(res)) {
                throw new SpringBatchException(SpringBatchMessage.JEMS017E, res.toString());
            }

            // all properties create all StringRefAddrs necessary
            Map<String, ResourceProperty> properties = res.getProperties();

            // scans all properteis set by JCL
            for (Property property : source.getProperties()) {
                if (property.isCustom()) {
                    if (res.getCustomProperties() == null) {
                        res.setCustomProperties(new HashMap<String, String>());
                    }
                    if (!res.getCustomProperties().containsKey(property.getName())) {
                        res.getCustomProperties().put(property.getName(), property.getValue());
                    } else {
                        throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(), res);
                    }
                } else {
                    // if a key is defined FINAL, throw an exception
                    for (ResourceProperty resProperty : properties.values()) {
                        if (resProperty.getName().equalsIgnoreCase(property.getName())
                                && !resProperty.isOverride()) {
                            throw new SpringBatchException(SpringBatchMessage.JEMS018E, property.getName(),
                                    res);
                        }
                    }
                    ResourcePropertiesUtil.addProperty(res, property.getName(), property.getValue());
                }
            }

            // creates a JNDI reference
            Reference ref = getReference(resourcer, res, source, dataDescriptionImplList);

            // loads all properties into RefAddr
            for (ResourceProperty property : properties.values()) {
                ref.add(new StringRefAddr(property.getName(), replaceProperties(property.getValue())));
            }

            // loads custom properties in a string format
            if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
                // loads all entries and substitute variables
                for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                    String value = replaceProperties(entry.getValue());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with format {type]/[name]
            LogAppl.getInstance().emit(SpringBatchMessage.JEMS024I, res);
            ic.rebind(source.getName(), ref);
        }

        // check if I have resources which must be locked
        if (!dataDescriptionImplList.isEmpty()) {

            // binds all data description impl to JNDI context
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {

                // create reference for JNDI access
                Reference reference = new DataStreamReference();

                // load GDG information, solving the real name of relative
                // position
                GDGManager.load(ddImpl);
                // serialize data description object in XML format
                XStream xstream = new XStream();
                String xml = xstream.toXML(ddImpl);
                // add string xml reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));

                LogAppl.getInstance().emit(SpringBatchMessage.JEMS023I, ddImpl);
                // bind resource using data description name
                ic.rebind(ddImpl.getName(), reference);
            }
        }
        // execute business logic
        // executes the java class defined in JCL
        // setting the boolean to TRUE
        SetFields.applyByAnnotation(this);
        isExecutionStarted = true;
        batchSM.setInternalAction(false);
        status = this.run(stepContribution, chunkContext);
    } catch (NamingException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS043E, e);
    } catch (RemoteException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } catch (IOException e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS044E, e, e.getMessage());
    } catch (Exception e) {
        isAbended = true;
        throw new SpringBatchException(SpringBatchMessage.JEMS045E, e, this.getClass().getName(),
                e.getMessage());
    } finally {
        batchSM.setInternalAction(true);
        if (!dataDescriptionImplList.isEmpty()) {
            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : dataDescriptionImplList) {
                try {
                    // commit the GDG index in the root
                    // if an exception, write on standard output of job
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);

                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, e.getMessage());
                    if (exceptions.length() == 0) {
                        exceptions.append(e.getMessage());
                    } else {
                        exceptions.append(e.getMessage()).append("\n");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS047E, e.getMessage());
                }
                if (exceptions.length() > 0 && !isAbended) {
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E,
                            StringUtils.center("ATTENTION", 40, "-"));
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS025E, exceptions.toString());
                }

            }
        }
        for (DataSource source : dataSourceList) {
            if (source.getName() != null) {
                // unbinds all resources
                try {
                    ic.unbind(source.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(SpringBatchMessage.JEMS047E, e.getMessage());
                }
            }
        }
        batchSM.setInternalAction(false);
    }
    return status;
}