Search in sources :

Example 1 with Integer

use of org.apache.axis2.databinding.types.soapencoding.Integer in project wso2-synapse by wso2.

the class Axis2HttpRequest method streamMessageContents.

/**
 * Start streaming the message into the Pipe, so that the contents could be read off the source
 * channel returned by getSourceChannel()
 *
 * @throws AxisFault on error
 */
public void streamMessageContents() throws AxisFault {
    if (log.isDebugEnabled()) {
        log.debug("Start streaming outgoing http request : [Message ID : " + msgContext.getMessageID() + "]");
        if (log.isTraceEnabled()) {
            log.trace("Message [Request Message ID : " + msgContext.getMessageID() + "] " + "[Request Message Payload : [ " + msgContext.getEnvelope() + "]");
        }
    }
    NHttpConfiguration cfg = NHttpConfiguration.getInstance();
    int senderTimeout = cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000);
    long startTime = System.currentTimeMillis();
    synchronized (this) {
        while (!readyToStream && !completed) {
            try {
                this.wait(senderTimeout + 10000);
                if ((startTime + senderTimeout + 5000) < System.currentTimeMillis()) {
                    handleException("Thread " + Thread.currentThread().getName() + " is blocked longer than the send timeout when trying to send the message :" + msgContext.getMessageID() + ". Releasing thread", new AxisFault("Sender thread was not notified within send timeout"));
                }
            } catch (InterruptedException ignore) {
            }
        }
    }
    if (!completed) {
        OutputStream out = new ContentOutputStream(outputBuffer);
        try {
            if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
                writeMessageFromTempData(out);
            } else {
                if (chunked) {
                    messageFormatter.writeTo(msgContext, format, out, false);
                } else {
                    writeMessageFromTempData(out);
                }
            }
        } catch (Exception e) {
            Throwable t = e.getCause();
            if (t != null && t.getCause() != null && t.getCause() instanceof ClosedChannelException) {
                if (log.isDebugEnabled()) {
                    log.debug("Ignore closed channel exception, as the " + "SessionRequestCallback handles this exception");
                }
            } else {
                Integer errorCode = msgContext == null ? null : (Integer) msgContext.getProperty(NhttpConstants.ERROR_CODE);
                if (errorCode == null || errorCode == NhttpConstants.SEND_ABORT) {
                    if (log.isDebugEnabled()) {
                        log.debug("Remote server aborted request being sent, and responded");
                    }
                } else {
                    if (e instanceof AxisFault) {
                        throw (AxisFault) e;
                    } else {
                        handleException("Error streaming message context", e);
                    }
                }
            }
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                handleException("Error closing outgoing message stream", e);
            }
            setSendingCompleted(true);
        }
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) ClosedChannelException(java.nio.channels.ClosedChannelException) OutputStream(java.io.OutputStream) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) ContentOutputStream(org.apache.http.nio.entity.ContentOutputStream) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) HttpException(org.apache.http.HttpException)

Example 2 with Integer

use of org.apache.axis2.databinding.types.soapencoding.Integer in project wso2-synapse by wso2.

the class FailoverEndpoint method sendMessage.

private void sendMessage(MessageContext synCtx) {
    logSetter();
    if (log.isDebugEnabled()) {
        log.debug("Failover Endpoint : " + getName());
    }
    if (getContext().isState(EndpointContext.ST_OFF)) {
        informFailure(synCtx, SynapseConstants.ENDPOINT_FO_NONE_READY, "Failover endpoint : " + getName() != null ? getName() : SynapseConstants.ANONYMOUS_ENDPOINT + " - is inactive");
        return;
    }
    boolean isARetry = false;
    Map<String, Integer> mEndpointLog = null;
    if (synCtx.getProperty(SynapseConstants.LAST_ENDPOINT) == null) {
        if (log.isDebugEnabled()) {
            log.debug(this + " Building the SoapEnvelope");
        }
        // If buildMessage attribute available in failover config it is honoured, else global property is considered
        if (isBuildMessageAttAvailable) {
            if (buildMessageAtt) {
                buildMessage(synCtx);
            }
        } else if (buildMessage) {
            buildMessage(synCtx);
        }
        synCtx.getEnvelope().buildWithAttachments();
        // If the endpoint failed during the sending, we need to keep the original envelope and reuse that for other endpoints
        if (Boolean.TRUE.equals(((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) {
            synCtx.setProperty(SynapseConstants.LB_FO_ENDPOINT_ORIGINAL_MESSAGE, synCtx.getEnvelope());
        }
        mEndpointLog = new HashMap<String, Integer>();
        synCtx.setProperty(SynapseConstants.ENDPOINT_LOG, mEndpointLog);
    } else {
        isARetry = true;
        mEndpointLog = (Map<String, Integer>) synCtx.getProperty(SynapseConstants.ENDPOINT_LOG);
    }
    if (getChildren().isEmpty()) {
        informFailure(synCtx, SynapseConstants.ENDPOINT_FO_NONE_READY, "FailoverLoadbalance endpoint : " + getName() + " - no child endpoints");
        return;
    }
    // evaluate the endpoint properties
    evaluateProperties(synCtx);
    if (dynamic) {
        // Dynamic fail-over mode - Switch to a backup endpoint when an error occurs
        // in the primary endpoint. But switch back to the primary as soon as it becomes
        // active again.
        boolean foundEndpoint = false;
        for (Endpoint endpoint : getChildren()) {
            if (endpoint.readyToSend()) {
                foundEndpoint = true;
                if (isARetry && metricsMBean != null) {
                    metricsMBean.reportSendingFault(SynapseConstants.ENDPOINT_FO_FAIL_OVER);
                }
                synCtx.pushFaultHandler(this);
                if (endpoint instanceof AbstractEndpoint) {
                    org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
                    Pipe pipe = (Pipe) axisMC.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
                    if (pipe != null) {
                        pipe.forceSetSerializationRest();
                    }
                    // allow the message to be content aware if the given message comes via PT
                    if (axisMC.getProperty(PassThroughConstants.PASS_THROUGH_PIPE) != null) {
                        ((AbstractEndpoint) endpoint).setContentAware(true);
                        ((AbstractEndpoint) endpoint).setForceBuildMC(true);
                        if (endpoint instanceof TemplateEndpoint && ((TemplateEndpoint) endpoint).getRealEndpoint() != null) {
                            if (((TemplateEndpoint) endpoint).getRealEndpoint() instanceof AbstractEndpoint) {
                                ((AbstractEndpoint) ((TemplateEndpoint) endpoint).getRealEndpoint()).setContentAware(true);
                                ((AbstractEndpoint) ((TemplateEndpoint) endpoint).getRealEndpoint()).setForceBuildMC(true);
                            }
                        }
                    }
                }
                if (endpoint.getName() != null) {
                    mEndpointLog.put(endpoint.getName(), null);
                }
                endpoint.send(synCtx);
                break;
            }
        }
        if (!foundEndpoint) {
            String msg = "Failover endpoint : " + (getName() != null ? getName() : SynapseConstants.ANONYMOUS_ENDPOINT) + " - no ready child endpoints";
            log.warn(msg);
            informFailure(synCtx, SynapseConstants.ENDPOINT_FO_NONE_READY, msg);
        }
    } else {
        if (currentEndpoint == null) {
            currentEndpoint = getChildren().get(0);
        }
        if (currentEndpoint.readyToSend()) {
            if (isARetry && metricsMBean != null) {
                metricsMBean.reportSendingFault(SynapseConstants.ENDPOINT_FO_FAIL_OVER);
            }
            synCtx.pushFaultHandler(this);
            currentEndpoint.send(synCtx);
        } else {
            boolean foundEndpoint = false;
            for (Endpoint endpoint : getChildren()) {
                if (endpoint.readyToSend()) {
                    foundEndpoint = true;
                    currentEndpoint = endpoint;
                    if (isARetry && metricsMBean != null) {
                        metricsMBean.reportSendingFault(SynapseConstants.ENDPOINT_FO_FAIL_OVER);
                    }
                    synCtx.pushFaultHandler(this);
                    currentEndpoint.send(synCtx);
                    break;
                }
            }
            if (!foundEndpoint) {
                String msg = "Failover endpoint : " + (getName() != null ? getName() : SynapseConstants.ANONYMOUS_ENDPOINT) + " - no ready child endpoints";
                log.warn(msg);
                informFailure(synCtx, SynapseConstants.ENDPOINT_FO_NONE_READY, msg);
            }
        }
    }
}
Also used : Pipe(org.apache.synapse.transport.passthru.Pipe) Integer(org.apache.axis2.databinding.types.soapencoding.Integer) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 3 with Integer

use of org.apache.axis2.databinding.types.soapencoding.Integer in project wso2-synapse by wso2.

the class VFSTransportListener method scanFileOrDirectory.

/**
 * Search for files that match the given regex pattern and create a list
 * Then process each of these files and update the status of the scan on
 * the poll table
 * @param entry the poll table entry for the scan
 * @param fileURI the file or directory to be scanned
 */
private void scanFileOrDirectory(final PollTableEntry entry, String fileURI) {
    if (log.isDebugEnabled()) {
        log.debug("Polling: " + VFSUtils.maskURLPassword(fileURI));
    }
    if (entry.isClusterAware()) {
        boolean leader = true;
        ClusteringAgent agent = getConfigurationContext().getAxisConfiguration().getClusteringAgent();
        if (agent != null && agent.getParameter("domain") != null) {
            // hazelcast clustering instance name
            String hazelcastInstanceName = agent.getParameter("domain").getValue() + ".instance";
            HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName(hazelcastInstanceName);
            if (instance != null) {
                // dirty leader election
                leader = instance.getCluster().getMembers().iterator().next().localMember();
            } else {
                log.warn("Clustering error, running the polling task in this node");
            }
        } else {
            log.warn("Although proxy is cluster aware, clustering config are not present, hence running the" + " the polling task in this node");
        }
        if (!leader) {
            if (log.isDebugEnabled()) {
                log.debug("This Member is not the leader");
            }
            entry.setLastPollState(PollTableEntry.NONE);
            long now = System.currentTimeMillis();
            entry.setLastPollTime(now);
            entry.setNextPollTime(now + entry.getPollInterval());
            onPollCompletion(entry);
            return;
        }
        if (log.isDebugEnabled()) {
            log.debug("This Member is the leader");
        }
    }
    FileSystemOptions fso = null;
    setFileSystemClosed(false);
    try {
        fso = VFSUtils.attachFileSystemOptions(entry.getVfsSchemeProperties(), fsManager);
    } catch (Exception e) {
        log.error("Error while attaching VFS file system properties. " + e.getMessage());
    }
    FileObject fileObject = null;
    // TODO : Trying to make the correct URL out of the malformed one.
    if (fileURI.contains("vfs:")) {
        fileURI = fileURI.substring(fileURI.indexOf("vfs:") + 4);
    }
    if (log.isDebugEnabled()) {
        log.debug("Scanning directory or file : " + VFSUtils.maskURLPassword(fileURI));
    }
    boolean wasError = true;
    int retryCount = 0;
    int maxRetryCount = entry.getMaxRetryCount();
    long reconnectionTimeout = entry.getReconnectTimeout();
    while (wasError) {
        try {
            retryCount++;
            fileObject = fsManager.resolveFile(fileURI, fso);
            if (fileObject == null) {
                log.error("fileObject is null");
                throw new FileSystemException("fileObject is null");
            }
            wasError = false;
        } catch (FileSystemException e) {
            if (retryCount >= maxRetryCount) {
                processFailure("Repeatedly failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI), e, entry);
                closeFileSystem(fileObject);
                return;
            } else {
                log.warn("Failed to resolve the file URI: " + VFSUtils.maskURLPassword(fileURI) + ", in attempt " + retryCount + ", " + e.getMessage() + " Retrying in " + reconnectionTimeout + " milliseconds.");
            }
        }
        if (wasError) {
            try {
                Thread.sleep(reconnectionTimeout);
            } catch (InterruptedException e2) {
                log.error("Thread was interrupted while waiting to reconnect.", e2);
            }
        }
    }
    try {
        if (fileObject.exists() && fileObject.isReadable()) {
            entry.setLastPollState(PollTableEntry.NONE);
            FileObject[] children = null;
            try {
                children = fileObject.getChildren();
            } catch (FileNotFolderException ignored) {
            } catch (FileSystemException ex) {
                log.error(ex.getMessage(), ex);
            }
            // if this is a file that would translate to a single message
            if (children == null || children.length == 0) {
                boolean isFailedRecord = false;
                if (entry.getMoveAfterMoveFailure() != null) {
                    isFailedRecord = isFailedRecord(fileObject, entry);
                }
                if (fileObject.getType() == FileType.FILE && !isFailedRecord) {
                    boolean runPostProcess = true;
                    if (!entry.isFileLockingEnabled() || (entry.isFileLockingEnabled() && acquireLock(fsManager, fileObject, entry, fso, true))) {
                        try {
                            if (fileObject.getType() == FileType.FILE) {
                                processFile(entry, fileObject);
                                entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                                metrics.incrementMessagesReceived();
                            } else {
                                runPostProcess = false;
                            }
                        } catch (AxisFault e) {
                            if (e.getCause() instanceof FileNotFoundException) {
                                log.warn("Error processing File URI : " + VFSUtils.maskURLPassword(fileObject.getName().toString()) + ". This can be due to file moved from another process.");
                                runPostProcess = false;
                            } else {
                                logException("Error processing File URI : " + VFSUtils.maskURLPassword(fileObject.getName().getURI()), e);
                                entry.setLastPollState(PollTableEntry.FAILED);
                                metrics.incrementFaultsReceiving();
                            }
                        }
                        if (runPostProcess) {
                            try {
                                moveOrDeleteAfterProcessing(entry, fileObject, fso);
                            } catch (AxisFault axisFault) {
                                logException("File object '" + VFSUtils.maskURLPassword(fileObject.getURL().toString()) + "' " + "cloud not be moved", axisFault);
                                entry.setLastPollState(PollTableEntry.FAILED);
                                String timeStamp = VFSUtils.getSystemTime(entry.getFailedRecordTimestampFormat());
                                addFailedRecord(entry, fileObject, timeStamp);
                            }
                        }
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject, fso);
                            if (log.isDebugEnabled()) {
                                log.debug("Removed the lock file '" + VFSUtils.maskURLPassword(fileObject.toString()) + ".lock' of the file '" + VFSUtils.maskURLPassword(fileObject.toString()));
                            }
                        }
                    } else if (log.isDebugEnabled()) {
                        log.debug("Couldn't get the lock for processing the file : " + VFSUtils.maskURLPassword(fileObject.getName().getURI()));
                    } else if (isFailedRecord) {
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, fileObject, fso);
                        }
                        // schedule a cleanup task if the file is there
                        if (fsManager.resolveFile(fileObject.getURL().toString(), fso) != null && removeTaskState == STATE_STOPPED && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, fileObject, fso));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString()) + "' has been marked as a failed" + " record, it will not process");
                        }
                    }
                }
            } else {
                int failCount = 0;
                int successCount = 0;
                int processCount = 0;
                Integer iFileProcessingInterval = entry.getFileProcessingInterval();
                Integer iFileProcessingCount = entry.getFileProcessingCount();
                if (log.isDebugEnabled()) {
                    log.debug("File name pattern : " + entry.getFileNamePattern());
                }
                // Sort the files
                String strSortParam = entry.getFileSortParam();
                if (strSortParam != null) {
                    log.debug("Start Sorting the files.");
                    boolean bSortOrderAsscending = entry.isFileSortAscending();
                    if (log.isDebugEnabled()) {
                        log.debug("Sorting the files by : " + strSortParam + ". (" + bSortOrderAsscending + ")");
                    }
                    if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_NAME) && bSortOrderAsscending) {
                        Arrays.sort(children, new FileNameAscComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_NAME) && !bSortOrderAsscending) {
                        Arrays.sort(children, new FileNameDesComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_SIZE) && bSortOrderAsscending) {
                        Arrays.sort(children, new FileSizeAscComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_SIZE) && !bSortOrderAsscending) {
                        Arrays.sort(children, new FileSizeDesComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP) && bSortOrderAsscending) {
                        Arrays.sort(children, new FileLastmodifiedtimestampAscComparator());
                    } else if (strSortParam.equals(VFSConstants.FILE_SORT_VALUE_LASTMODIFIEDTIMESTAMP) && !bSortOrderAsscending) {
                        Arrays.sort(children, new FileLastmodifiedtimestampDesComparator());
                    }
                    log.debug("End Sorting the files.");
                }
                for (FileObject child : children) {
                    // Stop processing when service get undeployed
                    if (state != BaseConstants.STARTED || !entry.getService().isActive()) {
                        return;
                    }
                    /**
                     * Before starting to process another file, see whether the proxy is stopped or not.
                     */
                    if (entry.isCanceled()) {
                        break;
                    }
                    // skipping *.lock file
                    if (child.getName().getBaseName().endsWith(".lock")) {
                        continue;
                    }
                    // skipping subfolders
                    if (child.getType() != FileType.FILE) {
                        continue;
                    }
                    // skipping files depending on size limitation
                    if (entry.getFileSizeLimit() >= 0 && child.getContent().getSize() > entry.getFileSizeLimit()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Ignoring file - " + child.getName().getBaseName() + " size - " + child.getContent().getSize() + " since it exceeds file size limit - " + entry.getFileSizeLimit());
                        }
                        continue;
                    }
                    boolean isFailedRecord = false;
                    if (entry.getMoveAfterMoveFailure() != null) {
                        isFailedRecord = isFailedRecord(child, entry);
                    }
                    if (entry.getFileNamePattern() != null && child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        // now we try to get the lock and process
                        if (log.isDebugEnabled()) {
                            log.debug("Matching file : " + child.getName().getBaseName());
                        }
                        boolean runPostProcess = true;
                        if ((!entry.isFileLockingEnabled() || (entry.isFileLockingEnabled() && VFSUtils.acquireLock(fsManager, child, fso, true))) && !isFailedRecord) {
                            // process the file
                            try {
                                if (log.isDebugEnabled()) {
                                    log.debug("Processing file :" + VFSUtils.maskURLPassword(child.toString()));
                                }
                                processCount++;
                                if (child.getType() == FileType.FILE) {
                                    processFile(entry, child);
                                    successCount++;
                                    // tell moveOrDeleteAfterProcessing() file was success
                                    entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                                    metrics.incrementMessagesReceived();
                                } else {
                                    runPostProcess = false;
                                }
                            } catch (Exception e) {
                                if (e.getCause() instanceof FileNotFoundException) {
                                    log.warn("Error processing File URI : " + VFSUtils.maskURLPassword(child.getName().toString()) + ". This can be due to file moved from another process.");
                                    runPostProcess = false;
                                } else {
                                    logException("Error processing File URI : " + VFSUtils.maskURLPassword(child.getName().getURI()), e);
                                    failCount++;
                                    // tell moveOrDeleteAfterProcessing() file failed
                                    entry.setLastPollState(PollTableEntry.FAILED);
                                    metrics.incrementFaultsReceiving();
                                }
                            }
                            // skipping un-locking file if failed to do delete/move after process
                            boolean skipUnlock = false;
                            if (runPostProcess) {
                                try {
                                    moveOrDeleteAfterProcessing(entry, child, fso);
                                } catch (AxisFault axisFault) {
                                    logException("File object '" + VFSUtils.maskURLPassword(child.getURL().toString()) + "'cloud not be moved, will remain in \"locked\" state", axisFault);
                                    skipUnlock = true;
                                    failCount++;
                                    entry.setLastPollState(PollTableEntry.FAILED);
                                    String timeStamp = VFSUtils.getSystemTime(entry.getFailedRecordTimestampFormat());
                                    addFailedRecord(entry, child, timeStamp);
                                }
                            }
                            // if there is a failure or not we'll try to release the lock
                            if (entry.isFileLockingEnabled() && !skipUnlock) {
                                VFSUtils.releaseLock(fsManager, child, fso);
                            }
                        }
                    } else if (entry.getFileNamePattern() != null && !child.getName().getBaseName().matches(entry.getFileNamePattern())) {
                        // child's file name does not match the file name pattern
                        if (log.isDebugEnabled()) {
                            log.debug("Non-Matching file : " + child.getName().getBaseName());
                        }
                    } else if (isFailedRecord) {
                        // it is a failed record
                        if (entry.isFileLockingEnabled()) {
                            VFSUtils.releaseLock(fsManager, child, fso);
                            VFSUtils.releaseLock(fsManager, fileObject, fso);
                        }
                        if (fsManager.resolveFile(child.getURL().toString(), fso) != null && removeTaskState == STATE_STOPPED && entry.getMoveAfterMoveFailure() != null) {
                            workerPool.execute(new FileRemoveTask(entry, child, fso));
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("File '" + VFSUtils.maskURLPassword(fileObject.getURL().toString()) + "' has been marked as a failed record, it will not " + "process");
                        }
                    }
                    if (iFileProcessingInterval != null && iFileProcessingInterval > 0) {
                        try {
                            if (log.isDebugEnabled()) {
                                log.debug("Put the VFS processor to sleep for : " + iFileProcessingInterval);
                            }
                            Thread.sleep(iFileProcessingInterval);
                        } catch (InterruptedException ie) {
                            log.error("Unable to set the interval between file processors." + ie);
                        }
                    } else if (iFileProcessingCount != null && iFileProcessingCount <= processCount) {
                        break;
                    }
                }
                if (failCount == 0 && successCount > 0) {
                    entry.setLastPollState(PollTableEntry.SUCCSESSFUL);
                } else if (successCount == 0 && failCount > 0) {
                    entry.setLastPollState(PollTableEntry.FAILED);
                } else {
                    entry.setLastPollState(PollTableEntry.WITH_ERRORS);
                }
            }
            // processing of this poll table entry is complete
            long now = System.currentTimeMillis();
            entry.setLastPollTime(now);
            entry.setNextPollTime(now + entry.getPollInterval());
        } else if (log.isDebugEnabled()) {
            log.debug("Unable to access or read file or directory : " + VFSUtils.maskURLPassword(fileURI) + "." + " Reason: " + (fileObject.exists() ? (fileObject.isReadable() ? "Unknown reason" : "The file can not be read!") : "The file does not exists!"));
        }
        onPollCompletion(entry);
    } catch (FileSystemException e) {
        processFailure("Error checking for existence and readability : " + VFSUtils.maskURLPassword(fileURI), e, entry);
    } catch (Exception ex) {
        processFailure("Un-handled exception thrown when processing the file : ", ex, entry);
    } finally {
        closeFileSystem(fileObject);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) FileNotFoundException(org.apache.commons.vfs2.FileNotFoundException) ClusteringAgent(org.apache.axis2.clustering.ClusteringAgent) FileNotFolderException(org.apache.commons.vfs2.FileNotFolderException) SecureVaultException(org.wso2.securevault.SecureVaultException) FileSystemException(org.apache.commons.vfs2.FileSystemException) ParseException(javax.mail.internet.ParseException) IOException(java.io.IOException) FileNotFoundException(org.apache.commons.vfs2.FileNotFoundException) FileNotFolderException(org.apache.commons.vfs2.FileNotFolderException) FileSystemException(org.apache.commons.vfs2.FileSystemException) HazelcastInstance(com.hazelcast.core.HazelcastInstance) FileObject(org.apache.commons.vfs2.FileObject) FileSystemOptions(org.apache.commons.vfs2.FileSystemOptions)

Example 4 with Integer

use of org.apache.axis2.databinding.types.soapencoding.Integer in project wso2-synapse by wso2.

the class SourceResponseFactory method create.

public static SourceResponse create(MessageContext msgContext, SourceRequest sourceRequest, SourceConfiguration sourceConfiguration) {
    // determine the status code to be sent
    int statusCode = PassThroughTransportUtils.determineHttpStatusCode(msgContext);
    SourceResponse sourceResponse;
    String statusLine = PassThroughTransportUtils.determineHttpStatusLine(msgContext);
    if (msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_SC) != null && statusCode == ((Integer) msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_SC))) {
        sourceResponse = new SourceResponse(sourceConfiguration, statusCode, statusLine, sourceRequest);
    } else {
        if (msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_REASON_PHRASE) != null && (statusLine.equals(msgContext.getProperty(PassThroughConstants.ORIGINAL_HTTP_REASON_PHRASE)))) {
            sourceResponse = new SourceResponse(sourceConfiguration, statusCode, sourceRequest);
        } else {
            sourceResponse = new SourceResponse(sourceConfiguration, statusCode, statusLine, sourceRequest);
        }
    }
    // set any transport headers
    Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH);
    boolean forceContentLengthCopy = msgContext.isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING);
    if (forceContentLength && forceContentLengthCopy && msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH) != null) {
        sourceResponse.addHeader(HTTP.CONTENT_LEN, (String) msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH));
    }
    // set to sourceResponse.
    if (sourceRequest != null && PassThroughConstants.HTTP_HEAD.equalsIgnoreCase(sourceRequest.getRequest().getRequestLine().getMethod()) && msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH) != null) {
        sourceResponse.addHeader(PassThroughConstants.ORGINAL_CONTEN_LENGTH, (String) msgContext.getProperty(PassThroughConstants.ORGINAL_CONTEN_LENGTH));
    }
    if (transportHeaders != null && msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) != null) {
        if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE) != null && msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE).toString().contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
            transportHeaders.put(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED);
        } else {
            Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
            if (pipe != null && !Boolean.TRUE.equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) {
                transportHeaders.put(HTTP.CONTENT_TYPE, msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE));
            }
        }
    }
    if (transportHeaders != null) {
        addResponseHeader(sourceResponse, transportHeaders);
    } else {
        Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY);
        if (noEntityBody == null || Boolean.FALSE == noEntityBody) {
            OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
            transportHeaders = new HashMap();
            MessageFormatter messageFormatter = MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext);
            if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) == null) {
                transportHeaders.put(HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            }
            addResponseHeader(sourceResponse, transportHeaders);
        }
    }
    // Add excess response header.
    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
    Map excessHeaders = (Map) msgContext.getProperty(excessProp);
    if (excessHeaders != null) {
        for (Iterator iterator = excessHeaders.keySet().iterator(); iterator.hasNext(); ) {
            String key = (String) iterator.next();
            for (String excessVal : (Collection<String>) excessHeaders.get(key)) {
                sourceResponse.addHeader(key, (String) excessVal);
            }
        }
    }
    // keep alive
    String noKeepAlive = (String) msgContext.getProperty(PassThroughConstants.NO_KEEPALIVE);
    if ("true".equals(noKeepAlive) || PassThroughConfiguration.getInstance().isKeepAliveDisabled()) {
        sourceResponse.setKeepAlive(false);
    } else {
        // that, disable keep-alive to avoid re-using the existing connection by client for the next request.
        if (sourceRequest != null) {
            String requestMethod = sourceRequest.getRequest().getRequestLine().getMethod();
            if (requestMethod != null && isPayloadOptionalMethod(requestMethod.toUpperCase()) && (sourceRequest.getHeaders().containsKey(HTTP.CONTENT_LEN) || sourceRequest.getHeaders().containsKey(HTTP.TRANSFER_ENCODING))) {
                if (log.isDebugEnabled()) {
                    log.debug("Disable keep-alive in the client connection : Content-length/Transfer-encoding" + " headers present for GET/HEAD/DELETE request");
                }
                sourceResponse.setKeepAlive(false);
            }
        }
    }
    return sourceResponse;
}
Also used : SourceResponse(org.apache.synapse.transport.passthru.SourceResponse) HashMap(java.util.HashMap) Iterator(java.util.Iterator) Collection(java.util.Collection) Pipe(org.apache.synapse.transport.passthru.Pipe) MessageFormatter(org.apache.axis2.transport.MessageFormatter) OMOutputFormat(org.apache.axiom.om.OMOutputFormat) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with Integer

use of org.apache.axis2.databinding.types.soapencoding.Integer in project wso2-synapse by wso2.

the class ClientConnFactoryBuilder method parseSSL.

public ClientConnFactoryBuilder parseSSL() throws AxisFault {
    Parameter keyParam = transportOut.getParameter("keystore");
    Parameter trustParam = transportOut.getParameter("truststore");
    Parameter httpsProtocolsParam = transportOut.getParameter("HttpsProtocols");
    Parameter preferredCiphersParam = transportOut.getParameter(NhttpConstants.PREFERRED_CIPHERS);
    OMElement ksEle = null;
    OMElement tsEle = null;
    if (keyParam != null) {
        ksEle = keyParam.getParameterElement().getFirstElement();
    }
    boolean novalidatecert = ParamUtils.getOptionalParamBoolean(transportOut, "novalidatecert", false);
    if (trustParam != null) {
        if (novalidatecert) {
            if (log.isWarnEnabled()) {
                log.warn(name + " Ignoring novalidatecert parameter since a truststore has been specified");
            }
        }
        tsEle = trustParam.getParameterElement().getFirstElement();
    }
    SSLContext sslContext = createSSLContext(ksEle, tsEle, novalidatecert);
    final Parameter hvp = transportOut.getParameter("HostnameVerifier");
    final String hvs = hvp != null ? hvp.getValue().toString() : null;
    final X509HostnameVerifier hostnameVerifier;
    if ("Strict".equalsIgnoreCase(hvs)) {
        hostnameVerifier = ClientSSLSetupHandler.STRICT;
    } else if ("AllowAll".equalsIgnoreCase(hvs)) {
        hostnameVerifier = ClientSSLSetupHandler.ALLOW_ALL;
    } else if ("DefaultAndLocalhost".equalsIgnoreCase(hvs)) {
        hostnameVerifier = ClientSSLSetupHandler.DEFAULT_AND_LOCALHOST;
    } else {
        hostnameVerifier = ClientSSLSetupHandler.DEFAULT;
    }
    final Parameter cvp = transportOut.getParameter("CertificateRevocationVerifier");
    final String cvEnable = cvp != null ? cvp.getParameterElement().getAttribute(new QName("enable")).getAttributeValue() : null;
    RevocationVerificationManager revocationVerifier = null;
    if ("true".equalsIgnoreCase(cvEnable)) {
        String cacheSizeString = cvp.getParameterElement().getFirstChildWithName(new QName("CacheSize")).getText();
        String cacheDelayString = cvp.getParameterElement().getFirstChildWithName(new QName("CacheDelay")).getText();
        Integer cacheSize = null;
        Integer cacheDelay = null;
        try {
            cacheSize = new Integer(cacheSizeString);
            cacheDelay = new Integer(cacheDelayString);
        } catch (NumberFormatException e) {
        }
        revocationVerifier = new RevocationVerificationManager(cacheSize, cacheDelay);
    }
    // Process HttpProtocols
    OMElement httpsProtocolsEl = httpsProtocolsParam != null ? httpsProtocolsParam.getParameterElement() : null;
    String[] httpsProtocols = null;
    final String configuredHttpsProtocols = httpsProtocolsEl != null ? httpsProtocolsEl.getText() : null;
    if (configuredHttpsProtocols != null && configuredHttpsProtocols.trim().length() != 0) {
        String[] configuredValues = configuredHttpsProtocols.trim().split(",");
        List<String> protocolList = new ArrayList<String>(configuredValues.length);
        for (String protocol : configuredValues) {
            if (!protocol.trim().isEmpty()) {
                protocolList.add(protocol.trim());
            }
        }
        httpsProtocols = protocolList.toArray(new String[protocolList.size()]);
    }
    // Initiated separately to cater setting https protocols
    ClientSSLSetupHandler clientSSLSetupHandler = new ClientSSLSetupHandler(hostnameVerifier, revocationVerifier);
    if (null != httpsProtocols) {
        clientSSLSetupHandler.setHttpsProtocols(httpsProtocols);
    }
    // Process enabled ciphers
    OMElement preferredCiphersEl = preferredCiphersParam != null ? preferredCiphersParam.getParameterElement() : null;
    String[] preferredCiphers = null;
    final String configuredWeakCiphers = preferredCiphersEl != null ? preferredCiphersEl.getText() : null;
    if (configuredWeakCiphers != null && configuredWeakCiphers.trim().length() != 0) {
        String[] configuredValues = configuredWeakCiphers.trim().split(",");
        List<String> ciphersList = new ArrayList<String>(configuredValues.length);
        for (String cipher : configuredValues) {
            cipher = cipher.trim();
            if (!cipher.isEmpty()) {
                ciphersList.add(cipher);
            }
        }
        preferredCiphers = ciphersList.toArray(new String[ciphersList.size()]);
        clientSSLSetupHandler.setPreferredCiphers(preferredCiphers);
    }
    ssl = new SSLContextDetails(sslContext, clientSSLSetupHandler);
    sslByHostMap = getCustomSSLContexts(transportOut);
    return this;
}
Also used : ClientSSLSetupHandler(org.apache.synapse.transport.http.conn.ClientSSLSetupHandler) SSLContextDetails(org.apache.synapse.transport.http.conn.SSLContextDetails) QName(javax.xml.namespace.QName) ArrayList(java.util.ArrayList) OMElement(org.apache.axiom.om.OMElement) SSLContext(javax.net.ssl.SSLContext) X509HostnameVerifier(org.apache.http.conn.ssl.X509HostnameVerifier) Parameter(org.apache.axis2.description.Parameter) RevocationVerificationManager(org.apache.synapse.transport.certificatevalidation.RevocationVerificationManager)

Aggregations

IOException (java.io.IOException)4 OMElement (org.apache.axiom.om.OMElement)4 MessageContext (org.apache.axis2.context.MessageContext)4 Parameter (org.apache.axis2.description.Parameter)4 QName (javax.xml.namespace.QName)3 DeploymentException (org.apache.axis2.deployment.DeploymentException)3 Pipe (org.apache.synapse.transport.passthru.Pipe)3 File (java.io.File)2 OutputStream (java.io.OutputStream)2 ArrayList (java.util.ArrayList)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 XMLStreamException (javax.xml.stream.XMLStreamException)2 OMOutputFormat (org.apache.axiom.om.OMOutputFormat)2 AxisFault (org.apache.axis2.AxisFault)2 TransportInDescription (org.apache.axis2.description.TransportInDescription)2 MessageFormatter (org.apache.axis2.transport.MessageFormatter)2 NHttpServerConnection (org.apache.http.nio.NHttpServerConnection)2 Message (quickfix.Message)2 HazelcastInstance (com.hazelcast.core.HazelcastInstance)1