Example usage for java.io OutputStream toString

List of usage examples for java.io OutputStream toString

Introduction

In this page you can find the example usage for java.io OutputStream toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java

/**
 * This method will make a POST call to the vApp deploy URL to deploy the vApp and it's
 * children Vms./*from www.  j a v  a  2  s .  c o m*/
 * 
 * @param vApp the vApp instance to deploy
 * @return a TaskType that can be used to monitor the status of the task
 */
private TaskType deploy(VAppType vApp) {
    String deployHref = null;

    // Search the list of links for the vApp rel="deploy" to get the correct Href
    for (LinkType link : vApp.getLink()) {
        if (link.getRel().equalsIgnoreCase("deploy")) {
            deployHref = link.getHref();
            break;
        }
    }

    // Only proceed if we found a valid deploy Href
    if (null != deployHref) {
        DeployVAppParamsType deployParams = new DeployVAppParamsType();
        deployParams.setPowerOn(Boolean.TRUE);

        // Create HttpPost request to perform InstantiatevApp action
        HttpPost instantiateVAppPost = vcd.post(deployHref, options);

        ObjectFactory objFactory = new ObjectFactory();
        JAXBElement<DeployVAppParamsType> deployParamsType = objFactory.createDeployVAppParams(deployParams);

        OutputStream os = null;

        JAXBContext jaxbContexts = null;
        try {
            jaxbContexts = JAXBContext.newInstance(DeployVAppParamsType.class);
        } catch (JAXBException ex) {
            throw new RuntimeException("Problem creating JAXB Context: ", ex);
        }

        try {
            javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
            marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            os = new ByteArrayOutputStream();
            // Marshal the object via JAXB to XML
            marshaller.marshal(deployParamsType, os);
        } catch (JAXBException e) {
            throw new RuntimeException("Problem marshalling instantiation vApp template", e);
        }

        HttpPost deployPost = vcd.post(deployHref, options);
        ;
        // Set the Content-Type header for the VM vApp template parameters
        ContentType contentType = ContentType.create("application/vnd.vmware.vcloud.deployVAppParams+xml",
                "ISO-8859-1");
        StringEntity deployEntity = new StringEntity(os.toString(), contentType);
        deployPost.setEntity(deployEntity);

        // Invoke the HttoPost to initiate the VM creation process
        HttpResponse response = HttpUtils.httpInvoke(deployPost);

        // Make sure response status is 201 Created
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
            TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class);
            return taskType;
        }
    }

    throw new RuntimeException("Could not deploy " + vApp.getName());
}

From source file:org.codehaus.mojo.antlr.AbstractAntlrMojo.java

protected void performGeneration(GenerationPlan plan, Artifact antlrArtifact) throws MojoExecutionException {
    if (!plan.getGenerationDirectory().getParentFile().exists()) {
        plan.getGenerationDirectory().getParentFile().mkdirs();
    }//from   w ww. j  a va  2 s.c o  m

    // ----------------------------------------------------------------------
    // Wrap arguments
    // Note: grammar file should be last
    // ----------------------------------------------------------------------

    List arguments = new LinkedList();
    addArgIf(arguments, debug, "-debug");
    addArgIf(arguments, diagnostic, "-diagnostic");
    addArgIf(arguments, trace, "-trace");
    addArgIf(arguments, traceParser, "-traceParser");
    addArgIf(arguments, traceLexer, "-traceLexer");
    addArgIf(arguments, traceTreeParser, "-traceTreeParser");

    addArgs(arguments);

    arguments.add("-o");
    arguments.add(plan.getGenerationDirectory().getPath());

    if (plan.getCollectedSuperGrammarIds().size() > 0) {
        arguments.add("-glib");
        StringBuffer buffer = new StringBuffer();
        Iterator ids = plan.getCollectedSuperGrammarIds().iterator();
        while (ids.hasNext()) {
            buffer.append(new File(sourceDirectory, (String) ids.next()));
            if (ids.hasNext()) {
                buffer.append(';');
            }
        }
        arguments.add(buffer.toString());
    }

    arguments.add(plan.getSource().getPath());

    String[] args = (String[]) arguments.toArray(new String[arguments.size()]);

    if (plan.getImportVocabTokenTypesDirectory() != null
            && !plan.getImportVocabTokenTypesDirectory().equals(plan.getGenerationDirectory())) {
        // we need to spawn a new process to properly set up PWD
        CommandLine commandLine = new CommandLine("java");
        commandLine.addArgument("-classpath", false);
        commandLine.addArgument(generateClasspathForProcessSpawning(antlrArtifact), true);
        commandLine.addArgument("antlr.Tool", false);
        commandLine.addArguments(args, true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(plan.getImportVocabTokenTypesDirectory());
        try {
            executor.execute(commandLine);
        } catch (IOException e) {
            getLog().warn("Error spawning process to execute antlr tool : " + e.getMessage());
        }

        return;
    }

    // ----------------------------------------------------------------------
    // Call Antlr
    // ----------------------------------------------------------------------

    if (getLog().isDebugEnabled()) {
        getLog().debug("antlr args=\n" + StringUtils.join(args, "\n"));
    }

    boolean failedSetManager = false;
    SecurityManager oldSm = null;
    try {
        oldSm = System.getSecurityManager();
        System.setSecurityManager(NoExitSecurityManager.INSTANCE);
    } catch (SecurityException ex) {
        // ANTLR-12
        oldSm = null;
        failedSetManager = true;
        // ignore, in embedded environment the security manager can already be set.
        // in such a case assume the exit call is handled properly..
        getLog().warn("Cannot set custom SecurityManager. "
                + "Antlr's call to System.exit() can cause application shutdown "
                + "if not handled by the current SecurityManager.");
    }

    String originalUserDir = null;
    if (plan.getImportVocabTokenTypesDirectory() != null) {
        originalUserDir = System.getProperty("user.dir");
        System.setProperty("user.dir", plan.getImportVocabTokenTypesDirectory().getPath());
    }

    PrintStream oldErr = System.err;

    OutputStream errOS = new StringOutputStream();
    PrintStream err = new PrintStream(errOS);
    System.setErr(err);

    try {
        executeAntlrInIsolatedClassLoader((String[]) arguments.toArray(new String[0]), antlrArtifact);
    } catch (SecurityException e) {
        if (e.getMessage().equals("exitVM-0")
                || e.getClass().getName().equals("org.netbeans.core.execution.ExitSecurityException")) // netbeans
                                                                                                                                             // IDE Sec
                                                                                                                                             // Manager.
        {
            // ANTLR-12
            // now basically every secutiry manager could set different message, how to handle in generic way?
            // probably only by external execution
            // / in case of NetBeans SecurityManager, it's not possible to distinguish exit codes, rather swallow
            // than fail.
            getLog().debug(e);
        } else {
            throw new MojoExecutionException(
                    "Antlr execution failed: " + e.getMessage() + "\n Error output:\n" + errOS, e);
        }
    } finally {
        if (originalUserDir != null) {
            System.setProperty("user.dir", originalUserDir);
        }
        if (!failedSetManager) {
            System.setSecurityManager(oldSm);
        }
        System.setErr(oldErr);
        System.err.println(errOS.toString());
    }
}

From source file:com.aurel.track.exchange.msProject.exporter.MsProjectExporterBL.java

/**
 * Export the MsProject data/*from   w ww  .  j a  va 2s. c o  m*/
 * 
 * @param msProjectExchangeDataStoreBean
 * @param notClosed
 * @return
 */
public static ProjectFile export(MsProjectExchangeDataStoreBean msProjectExchangeDataStoreBean,
        boolean notClosed, Integer personID) {
    loadConfigFromFile();
    Integer entityID = msProjectExchangeDataStoreBean.getEntityID();
    int entityType = msProjectExchangeDataStoreBean.getEntityType();
    Integer projectID = msProjectExchangeDataStoreBean.getProjectID();
    Integer issueType = msProjectExchangeDataStoreBean.getIssueType();

    TProjectBean projectBean = msProjectExchangeDataStoreBean.getProjectBean();
    String name = msProjectExchangeDataStoreBean.getName();
    ProjectFile project = msProjectExchangeDataStoreBean.getProject();

    Integer defaultTaskType = PropertiesHelper.getIntegerProperty(projectBean.getMoreProps(),
            TProjectBean.MOREPPROPS.DEFAULT_TASK_TYPE);
    if (defaultTaskType == null) {
        defaultTaskType = project.getProjectHeader().getDefaultTaskType().getValue();
        if (defaultTaskType == null) {
            defaultTaskType = Integer.valueOf(TASK_TYPE.FIXED_UNITS);
        }
    }
    Integer durationFormat = PropertiesHelper.getIntegerProperty(projectBean.getMoreProps(),
            TProjectBean.MOREPPROPS.DURATION_FORMAT);
    Double hoursPerWorkDay = ProjectBL.getHoursPerWorkingDay(projectBean.getObjectID());
    Map<Integer, Integer> resourceUIDToPersonIDMap = msProjectExchangeDataStoreBean
            .getResourceUIDToPersonIDMap();
    // int maxResourceID = getMaxInteger(resourceUIDToPersonIDMap.keySet());
    // can be that the same Genji person is mapped for more than one
    // MSProject resource
    Map<Integer, List<Integer>> personIDToResourceUIDMap = GeneralUtils
            .getInvertedDuplicatedValuesMap(resourceUIDToPersonIDMap);
    /**
     * add/update the resources and calendars
     */
    // get the potential resource persons, this
    // TODO get only the persons with no read restrictions for
    // TReportLayoutBean.PSEUDO_COLUMNS.MY_EXPENSE_TIME (old).
    List<TPersonBean> addExpenseRolePersons = PersonBL.getPersonsWithRightInProjectAndListType(projectID,
            issueType, AccessBeans.AccessFlagIndexes.MODIFYANYTASK, true,
            TPersonBean.PERSON_CATEGORY.ALL_PERSONS, null, true, true);
    List<TPersonBean> personsWithWork = PersonBL.getPersonsWithWorkInProject(entityID, entityType, issueType);
    List<Integer> addExpenseRolePersonIDs = GeneralUtils.createIntegerListFromBeanList(addExpenseRolePersons);
    List<Integer> personIDsWithWork = GeneralUtils.createIntegerListFromBeanList(personsWithWork);
    Set<Integer> personIDs = new HashSet<Integer>();
    personIDs.addAll(addExpenseRolePersonIDs);
    personIDs.addAll(personIDsWithWork);
    /*
     * List<TPersonBean> personBeans = PersonBL.getPersonsByCategory(
     * personIDs, TPersonBean.PERSON_CATEGORY.ALL_DIRECT, false, true,
     * null);
     */
    // TODO check
    // exportResourcesAndCalendars(personBeans, project,
    // personIDToResourceUIDMap,maxResourceID);

    /**
     * get the Genji side data
     */
    // 'Task' type workItems already existing in track+ left joined with
    // TMSProjectTask (ordered by outlineNumber and created)
    List<TWorkItemBean> existingTrackPlusWorkItemsList = MsProjectExchangeBL.getTaskWorkItemsForExport(entityID,
            entityType, notClosed);
    Map<Integer, TWorkItemBean> existingTrackPlusWorkItemsMap = GeneralUtils
            .createMapFromList(existingTrackPlusWorkItemsList);
    int[] workItemIDs = GeneralUtils.createIntArrFromSet(existingTrackPlusWorkItemsMap.keySet());
    LocalLookupContainer lookupContainer = ItemBL.getItemHierarchyContainer(existingTrackPlusWorkItemsList);

    Map<Integer, TMSProjectTaskBean> existingTrackPlusTasks = MsProjectExchangeBL
            .getMsProjectTasksForExport(entityID, entityType, notClosed);
    // the taskUID to workItemID mapping for existing tasks
    // the workItemID to taskUID mapping for existing tasks
    Map<Integer, Integer> workItemIDToTaskUIDMap = MsProjectExchangeBL
            .getWorkItemIDToTaskUIDMap(existingTrackPlusTasks);
    // the new workItems (without corresponding task elements) should be put
    // at the end
    // (after a database ASC ordering those with null values are the first
    // ones)
    List<TWorkItemBean> newWorkItemBeans = new ArrayList<TWorkItemBean>();
    for (Iterator<TWorkItemBean> iterator = existingTrackPlusWorkItemsList.iterator(); iterator.hasNext();) {
        TWorkItemBean workItemBean = iterator.next();
        if (!workItemIDToTaskUIDMap.containsKey(workItemBean.getObjectID())) {
            iterator.remove();
            newWorkItemBeans.add(workItemBean);
        }
    }
    existingTrackPlusWorkItemsList.addAll(newWorkItemBeans);
    // last imported tasks
    List<Task> lastImportedMsProjectTasksList = msProjectExchangeDataStoreBean.getTasks();
    Map<Integer, Task> lastImportedMsProjectTasksMap = MsProjectExchangeDOMHelper
            .createIntegerElementMapFromListForTasks(lastImportedMsProjectTasksList);
    // get the parent to children map
    Map<Integer, List<Integer>> parentToChildrenListMap = getParentToChildrenMap(existingTrackPlusWorkItemsList,
            existingTrackPlusTasks, workItemIDToTaskUIDMap);
    // get the last planned work for existing task workItems independently
    // of the date
    List<Integer> fieldIDs = new LinkedList<Integer>();
    fieldIDs.add(FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.PLAN);
    List<TComputedValuesBean> plannedTimesList = ComputedValuesLoaderBL.loadByWorkItemKeys(
            existingTrackPlusWorkItemsList,
            AccessBeans.getFieldRestrictions(personID, existingTrackPlusWorkItemsList, fieldIDs, false),
            TComputedValuesBean.EFFORTTYPE.TIME, TComputedValuesBean.COMPUTEDVALUETYPE.PLAN, null, false,
            FieldsRestrictionsToRoleBL.PSEUDO_COLUMNS.PLAN);
    Map<Integer, TComputedValuesBean> plannedTimesMap = new HashMap<Integer, TComputedValuesBean>();
    for (TComputedValuesBean computedValuesBean : plannedTimesList) {
        plannedTimesMap.put(computedValuesBean.getWorkitemKey(), computedValuesBean);
    }
    List<TCostBean> costBeanList = ExpenseBL.loadByWorkItemKeys(workItemIDs, null, null, null, null, true);
    Map<Integer, List<TCostBean>> costBeanMap = ExpenseBL.getCostBeansByWorkItemMap(costBeanList);
    // get the remaining work for existing task workItems
    Map<Integer, TActualEstimatedBudgetBean> remainingBudgetMap = RemainingPlanBL
            .loadRemainingBudgetMapByItemIDs(workItemIDs);
    // set project elements
    Date actualStartDate = getProjectActualStartDate(costBeanList);
    Date startDate = getProjectDate(existingTrackPlusWorkItemsList, true);
    if (actualStartDate != null) {
        if (startDate == null || startDate.after(actualStartDate)) {
            startDate = actualStartDate;
        }
    }
    String projectStartDate = MsProjectExchangeBL.formatDateTime(startDate);
    String projectEndDate = MsProjectExchangeBL
            .formatDateTime(getProjectDate(existingTrackPlusWorkItemsList, false));

    DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    if (projectStartDate == null || projectStartDate == "") {
        projectStartDate = dateTimeFormat.format(new Date()).toString();
    }
    if (projectEndDate == null || projectEndDate == "") {
        projectEndDate = dateTimeFormat.format(new Date()).toString();
    }

    setProjectElements(project, name, projectStartDate, projectEndDate, projectBean, defaultTaskType,
            durationFormat, hoursPerWorkDay);
    Set<Integer> personsHavingWork = getPersonsWithWork(costBeanList);
    Map<Integer, Resource> UIDBasedResourceElementsMap = getUIDBasedResources(project);
    Map<Integer, ProjectCalendar> UIDBasedCalendarElementsMap = getUIDBasedCalendars(project);
    NumberFormat numberFormatTimeSpan = new DecimalFormat("00");
    /**
     * get the working times for base calendars
     */
    Map<Integer, Map<String, List<String[]>>> calendarUIDBasedBaseCalendarExceptionWorkingTimes = new HashMap<Integer, Map<String, List<String[]>>>();
    Map<Integer, Map<Integer, List<String[]>>> calendarUIDBasedBaseCalendarWeekDayWorkingTimes = new HashMap<Integer, Map<Integer, List<String[]>>>();

    getUIDBasedBaseCalendarWorkingTimes(project, allowOvertimeBookings, maxOvertimeHoursPerDay,
            numberFormatTimeSpan, calendarUIDBasedBaseCalendarExceptionWorkingTimes,
            calendarUIDBasedBaseCalendarWeekDayWorkingTimes);
    /**
     * get the person specific working times
     */
    Map<Integer, Integer> personIDToBaseCalendar = new HashMap<Integer, Integer>();
    Map<Integer, Map<String, List<String[]>>> personBasedCalendarExceptionWorkingTimes = new HashMap<Integer, Map<String, List<String[]>>>();
    Map<Integer, Map<Integer, List<String[]>>> personBasedCalendarWeekDayWorkingTimes = new HashMap<Integer, Map<Integer, List<String[]>>>();
    getPersonIDBasedBaseCalendarWorkingTimes(personsHavingWork, personIDToResourceUIDMap,
            UIDBasedResourceElementsMap, UIDBasedCalendarElementsMap, allowOvertimeBookings,
            maxOvertimeHoursPerDay, numberFormatTimeSpan, personIDToBaseCalendar,
            personBasedCalendarExceptionWorkingTimes, personBasedCalendarWeekDayWorkingTimes);
    IDCounter idCounter = new IDCounter();
    // initialize the taskUID with the maximal existing value
    idCounter.setTaskUID(getMaxInteger(existingTrackPlusTasks.keySet()));
    int currentLevel = -1;

    for (Iterator it = existingTrackPlusWorkItemsList.iterator(); it.hasNext();) {
        TWorkItemBean workItemBean = (TWorkItemBean) it.next();
        Integer parentID = workItemBean.getSuperiorworkitem();
        // first add those at the upper level (without task parents)
        if (parentID == null || !existingTrackPlusWorkItemsMap.containsKey(parentID))
            listWorkItems(workItemBean, new OutlineStructure(++currentLevel), idCounter,
                    existingTrackPlusWorkItemsMap, parentToChildrenListMap, project, workItemIDToTaskUIDMap,
                    lastImportedMsProjectTasksMap, existingTrackPlusTasks, plannedTimesMap, costBeanMap,
                    remainingBudgetMap, hoursPerWorkDay, defaultTaskType, durationFormat,
                    calendarUIDBasedBaseCalendarExceptionWorkingTimes,
                    calendarUIDBasedBaseCalendarWeekDayWorkingTimes, lookupContainer);
    }
    // remove the tasks not any more present in the track+ side but present
    // in the last imported file
    // (if a Task type workItem was closed or deleted or changed to other
    // issueType or mover to other project or...
    // the task should be removed from the last exported document together
    // with all assignments to that task)
    Set<Integer> removedTaskIDs = new HashSet<Integer>();
    for (Iterator<Integer> itrLastImportedTask = lastImportedMsProjectTasksMap.keySet()
            .iterator(); itrLastImportedTask.hasNext();) {
        Integer taskID = itrLastImportedTask.next();
        if (!existingTrackPlusTasks.containsKey(taskID)) {
            Task lastImportedTaskElement = lastImportedMsProjectTasksMap.get(taskID);
            if (MsProjectExchangeDOMHelper.UIDIsValidTask(lastImportedTaskElement)) {
                // TODO Possible probelem in old xml version it was:
                // lastImportedTaskElement.getParentNode().removeChild(lastImportedTaskElement);
                removedTaskIDs.add(taskID);
            }

        }
    }
    exportTaskDependencyLinks(project, workItemIDToTaskUIDMap);
    exportAssignments(project, existingTrackPlusWorkItemsMap, costBeanList, workItemIDToTaskUIDMap,
            personIDToResourceUIDMap, hoursPerWorkDay, removedTaskIDs, allowOvertimeBookings,
            maxOvertimeHoursPerDay, allowOverdayBookings, allowActualWorkOverlap,
            calendarUIDBasedBaseCalendarExceptionWorkingTimes, calendarUIDBasedBaseCalendarWeekDayWorkingTimes,
            personBasedCalendarExceptionWorkingTimes, personBasedCalendarWeekDayWorkingTimes,
            personIDToBaseCalendar);
    try {
        OutputStream out = new ByteArrayOutputStream();
        ProjectWriter writer = new MSPDIWriter();
        writer.write(msProjectExchangeDataStoreBean.getProject(), out);
        String content = out.toString();
        MsProjectExchangeBL.saveMSProjectExportFile(msProjectExchangeDataStoreBean, content);
    } catch (Exception ex) {
        LOGGER.error(ex.getMessage());
    }
    setTasksOrderByWbs(project);
    setTrackPlusAliasForIdMapping(project);
    updatingWorkBudget(project, costBeanList);
    return project;
}

From source file:com.vmware.vchs.publicapi.samples.VMCreateSample.java

/**
 * This method will update the passed in vApp network by adding an additional
 * NetworkConfigSection that uses the command line options.networkName. It makes a PUT call
 * to the edit link of the NetworkConfigSection section of the vApp passed in. The
 * passed in VdcType is used to look up the parent network which is required for the update
 * process of the vApp NetworkConfigSection.
 * /*from   w  w w.ja v a  2s . co  m*/
 * NOTE: This step, updating the vApp network section, must be done BEFORE any of the vApp's
 * children Vm's network sections are updated.
 * 
 * @param vApp the vApp instance to update network configuration for
 * @param vdc the VDC this vApp is deployed to
 * @return a TaskType instance if successful, otherwise an exception is thrown
 */
private TaskType updateVAppNetwork(VAppType vApp, VdcType vdc) {
    List<JAXBElement<? extends SectionType>> sections = vApp.getSection();
    for (JAXBElement<? extends SectionType> section : sections) {
        if (section.getName().toString().contains("NetworkConfigSection")) {
            NetworkConfigSectionType ncst = (NetworkConfigSectionType) section.getValue();
            // Find the EDIT link to make a PUT call to to update the network config info
            List<LinkType> links = ncst.getLink();
            String editHref = null;
            for (LinkType link : links) {
                if (link.getRel().equalsIgnoreCase("edit")) {
                    editHref = link.getHref();
                    break;
                }
            }

            if (null != editHref) {
                VAppNetworkConfigurationType vappNet = new VAppNetworkConfigurationType();

                // Use the network name passed on the command line, the same name that will
                // be applied to each vApp Vm child network configuration so they match
                vappNet.setNetworkName(options.networkName);

                // Newly constructed network configuration
                NetworkConfigurationType networkConfiguration = new NetworkConfigurationType();
                ReferenceType networkReference = new ReferenceType();

                // Get the parent network that the VDC refers to
                networkReference.setHref(getParentNetworkHrefFromVdc(vdc));
                networkConfiguration.setParentNetwork(networkReference);

                // hard coded.. 'bridged', 'natRouted' or 'isolated'
                networkConfiguration.setFenceMode("bridged");
                vappNet.setConfiguration(networkConfiguration);

                // Add the newly configured network to the existing vApp configuration
                ncst.getNetworkConfig().add(vappNet);

                // Make the PUT call to update the vApp network configuration
                HttpPut updateVAppNetwork = vcd.put(editHref, options);
                OutputStream os = null;
                ObjectFactory objectFactory = new ObjectFactory();
                JAXBElement<NetworkConfigSectionType> networkConfigSectionType = objectFactory
                        .createNetworkConfigSection(ncst);

                JAXBContext jaxbContexts = null;
                try {
                    jaxbContexts = JAXBContext.newInstance(NetworkConfigSectionType.class);
                } catch (JAXBException ex) {
                    throw new RuntimeException("Problem creating JAXB Context: ", ex);
                }

                try {
                    javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
                    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                    os = new ByteArrayOutputStream();
                    // Marshal the object via JAXB to XML
                    marshaller.marshal(networkConfigSectionType, os);
                } catch (JAXBException e) {
                    throw new RuntimeException("Problem marshalling VirtualHardwareSection", e);
                }

                // Set the Content-Type header for NetworkConfigSection
                ContentType contentType = ContentType
                        .create("application/vnd.vmware.vcloud.networkConfigSection+xml", "ISO-8859-1");
                StringEntity update = new StringEntity(os.toString(), contentType);
                updateVAppNetwork.setEntity(update);

                // Invoke the HttoPut to update the VirtualHardwareSection of the Vm
                HttpResponse response = HttpUtils.httpInvoke(updateVAppNetwork);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
                    TaskType taskType = HttpUtils.unmarshal(response.getEntity(), TaskType.class);
                    return taskType;
                }
            }
        }
    }

    throw new RuntimeException("Problem trying to update vApp " + vApp.getName()
            + " network config section with " + options.networkName + " as the network name");
}

From source file:org.pentaho.platform.web.servlet.AdhocWebService.java

/**
 * TODO sbarkdull, method is poorly named and needs to be refactored, execution of action
 * resource should happen outside the method.
 * //from  w ww.  j  ava 2 s  . c o m
 * @param reportXML
 * @param templatePath
 * @param outputType
 * @param outputStream OutputStream (output parameter) the preview report's output will be written
 * to this stream.
 * @param userSession
 * @param isAjax
 * @throws AdhocWebServiceException
 * @throws IOException
 * @throws PentahoMetadataException
 */
private void createJFreeReportAsStream(final String reportXML, final String templatePath,
        final String outputType, final OutputStream outputStream, final IPentahoSession userSession,
        final String loggingLevel, final boolean wrapWithSoap, final boolean interactive)
        throws AdhocWebServiceException, IOException, PentahoMetadataException {

    if (StringUtil.doesPathContainParentPathSegment(templatePath)) {
        String msg = Messages.getString("AdhocWebService.ERROR_0008_MISSING_OR_INVALID_REPORT_NAME"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }

    Document reportSpecDoc = null;
    try {
        reportSpecDoc = XmlDom4JHelper.getDocFromString(reportXML, new PentahoEntityResolver());
    } catch (XmlParseException e) {
        String msg = Messages.getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    Element mqlNode = (Element) reportSpecDoc.selectSingleNode("/report-spec/query/mql"); //$NON-NLS-1$
    mqlNode.detach();

    Node reportNameNd = reportSpecDoc.selectSingleNode("/report-spec/report-name"); //$NON-NLS-1$
    String reportName = null != reportNameNd ? reportNameNd.getText() : ""; //$NON-NLS-1$
    Node reportDescNd = reportSpecDoc.selectSingleNode("/report-spec/report-desc"); //$NON-NLS-1$
    String reportDesc = reportDescNd.getText();

    String[] outputTypeList = { outputType };

    ISolutionRepository repository = PentahoSystem.get(ISolutionRepository.class, userSession);

    String xactionFilename = userSession.getId() + "_wqr_preview.xaction"; //$NON-NLS-1$

    ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream();
    createJFreeReportDefinitionAsStream(reportXML, templatePath, mqlNode, repository, userSession,
            jfreeOutputStream);

    // create .xaction to run
    ByteArrayOutputStream xactionOutputStream = createMQLReportActionSequenceAsStream(reportName, reportDesc,
            mqlNode, outputTypeList, xactionFilename,
            jfreeOutputStream.toString(LocaleHelper.getSystemEncoding()), /*jfreeReportFileName*/null,
            loggingLevel, userSession);
    SimpleParameterProvider actionSequenceParameterProvider = new SimpleParameterProvider();
    actionSequenceParameterProvider.setParameter("type", outputType); //$NON-NLS-1$
    actionSequenceParameterProvider.setParameter("logging-level", "error"); //$NON-NLS-1$ //$NON-NLS-2$
    actionSequenceParameterProvider.setParameter("level", "error"); //$NON-NLS-1$ //$NON-NLS-2$
    OutputStream out;
    if (interactive) {
        out = new ByteArrayOutputStream();
    } else {
        out = outputStream;
    }

    IRuntimeContext runtimeContext = AdhocWebService.executeActionSequence(
            xactionOutputStream.toString(LocaleHelper.getSystemEncoding()), "preview.xaction", //$NON-NLS-1$
            actionSequenceParameterProvider, userSession, out);

    if (runtimeContext != null) {
        runtimeContext.dispose();
    }
    if (interactive) {
        // handle XML for interactive ad-hoc
        AdhocWebServiceInteract.interactiveOutput(out.toString(), outputStream, userSession);
    }

}

From source file:org.exoplatform.calendar.webui.popup.UIEventForm.java

protected void sendMail(MailService svr, OrganizationService orSvr, CalendarSetting setting, String fromId,
        String toId, CalendarEvent event) throws Exception {
    List<Attachment> atts = getAttachments(null, false);
    DateFormat df = new SimpleDateFormat(setting.getDateFormat() + " " + setting.getTimeFormat());
    User invitor = orSvr.getUserHandler().findUserByName(CalendarUtils.getCurrentUser());
    StringBuffer sbSubject = new StringBuffer("[" + getLabel("invitation") + "] ");
    sbSubject.append(event.getSummary());
    sbSubject.append(" ");
    sbSubject.append(df.format(event.getFromDateTime()));

    StringBuffer sbBody = new StringBuffer();
    sbBody.append(/*from   w ww . j  ava 2s .  c  o m*/
            "<div style=\"margin: 20px auto; padding: 8px; background: rgb(224, 236, 255) none repeat scroll 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 500px;\">");
    sbBody.append(
            "<table style=\"margin: 0px; padding: 0px; border-collapse: collapse; border-spacing: 0px; width: 100%; line-height: 16px;\">");
    sbBody.append("<tbody>");
    sbBody.append("<tr>");
    sbBody.append("<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap; \">"
            + getLabel("fromWho") + ":</td>");
    sbBody.append("<td style=\"padding: 4px;\"> " + invitor.getUserName() + "(" + invitor.getEmail() + ")"
            + " </td>");
    sbBody.append("</tr>");
    //
    sbBody.append("<tr>");
    sbBody.append("<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap;\">"
            + getLabel(UIEventDetailTab.FIELD_MESSAGE) + ":</td>");
    sbBody.append("<td style=\"padding: 4px;\">" + event.getMessage() + "</td>");
    sbBody.append("</tr>");

    sbBody.append("<tr>");
    sbBody.append("<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap;\">"
            + getLabel(UIEventDetailTab.FIELD_EVENT) + ":</td>");
    sbBody.append("<td style=\"padding: 4px;\">" + event.getSummary() + "</td>");
    sbBody.append("</tr>");
    sbBody.append("<tr>");
    sbBody.append("<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap;\">"
            + getLabel(UIEventDetailTab.FIELD_DESCRIPTION) + ":</td>");
    sbBody.append("<td style=\"padding: 4px;\">"
            + (event.getDescription() != null && event.getDescription().trim().length() > 0
                    ? event.getDescription()
                    : " ")
            + "</td>");
    sbBody.append("</tr>");
    sbBody.append("<tr>");
    sbBody.append("<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap;\">"
            + getLabel("when") + ":</td>");
    sbBody.append("<td style=\"padding: 4px;\"> <div>" + getLabel(UIEventDetailTab.FIELD_FROM) + ": "
            + df.format(event.getFromDateTime()) + "</div>");
    sbBody.append("<div>" + getLabel(UIEventDetailTab.FIELD_TO) + ": " + df.format(event.getToDateTime())
            + "</div></td>");
    sbBody.append("</tr>");
    sbBody.append("<tr>");
    sbBody.append("<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap;\">"
            + getLabel(UIEventDetailTab.FIELD_PLACE) + ":</td>");
    sbBody.append("<td style=\"padding: 4px;\">"
            + (event.getLocation() != null && event.getLocation().trim().length() > 0 ? event.getLocation()
                    : " ")
            + "</td>");
    sbBody.append("</tr>");
    sbBody.append("<tr>");
    sbBody.append("<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap;\">"
            + getLabel(FIELD_MEETING) + "</td>");
    //cs-2407
    //cs-764
    toId = toId.replace(CalendarUtils.BREAK_LINE, CalendarUtils.COMMA);
    if (CalendarUtils.isEmpty(getInvitationEmail())) {
        sbBody.append("<td style=\"padding: 4px;\">" + toId + "</td>");
    } else {
        String newInvi = getInvitationEmail().replace(",", ", ");
        sbBody.append("<td style=\"padding: 4px;\">" + toId + ", " + newInvi + "</td>");
    }
    sbBody.append("</tr>");
    if (!atts.isEmpty()) {
        sbBody.append("<tr>");
        sbBody.append(
                "<td style=\"padding: 4px;  text-align: right; vertical-align: top; white-space:nowrap;\">"
                        + getLabel(UIEventDetailTab.FIELD_ATTACHMENTS) + ":</td>");
        StringBuffer sbf = new StringBuffer();
        for (Attachment att : atts) {
            if (sbf.length() > 0)
                sbf.append(",");
            sbf.append(att.getName());
        }
        sbBody.append("<td style=\"padding: 4px;\"> (" + atts.size() + ") " + sbf.toString() + " </td>");
        sbBody.append("</tr>");
    }

    Map<String, String> eXoIdMap = new HashMap<String, String>();

    StringBuffer sbAddress = new StringBuffer();
    if (event.getInvitation() != null) {
        for (String s : event.getInvitation()) {
            s = s.trim();
            if (sbAddress.length() > 0)
                sbAddress.append(",");
            sbAddress.append(s);
            eXoIdMap.put(s, null);
        }
    }

    OrganizationService orgService = CalendarUtils.getOrganizationService();
    StringBuffer sb = new StringBuffer();
    for (String s : toId.split(CalendarUtils.COMMA)) {
        User user = orgService.getUserHandler().findUserByName(s);
        if (user != null) {
            if (!CalendarUtils.isEmpty(sb.toString()))
                sb.append(CalendarUtils.COMMA);
            sb.append(user.getEmail());
            eXoIdMap.put(user.getEmail(), s);
        }
    }

    if (sbAddress.length() > 0 && sb.toString().trim().length() > 0)
        sbAddress.append(",");
    sbAddress.append(sb.toString().trim());

    StringBuffer values = new StringBuffer(fromId);
    User user = orSvr.getUserHandler().findUserByName(fromId);

    values.append(CalendarUtils.SEMICOLON + " ");
    values.append(toId);
    values.append(CalendarUtils.SEMICOLON + " ");
    values.append(event.getCalType());
    values.append(CalendarUtils.SEMICOLON + " ");
    values.append(event.getCalendarId());
    values.append(CalendarUtils.SEMICOLON + " ");
    values.append(event.getId());
    CalendarService calService = CalendarUtils.getCalendarService();
    org.exoplatform.services.mail.MailService mService = getApplicationComponent(
            org.exoplatform.services.mail.impl.MailServiceImpl.class);
    org.exoplatform.services.mail.Attachment attachmentCal = new org.exoplatform.services.mail.Attachment();
    try {
        OutputStream out = calService.getCalendarImportExports(CalendarService.ICALENDAR)
                .exportEventCalendar(fromId, event.getCalendarId(), event.getCalType(), event.getId());
        ByteArrayInputStream is = new ByteArrayInputStream(out.toString().getBytes());
        attachmentCal.setInputStream(is);
        attachmentCal.setName("icalendar.ics");
        attachmentCal.setMimeType("text/calendar");
    } catch (Exception e) {
        attachmentCal = null;
        if (log.isDebugEnabled()) {
            log.debug("Fail to create attachment", e);
        }
        for (String s : sbAddress.toString().split(CalendarUtils.COMMA)) {
            if (CalendarUtils.isEmpty(s))
                continue;
            org.exoplatform.services.mail.Message message = new org.exoplatform.services.mail.Message();
            message.setSubject(sbSubject.toString());
            message.setBody(getBodyMail(sbBody.toString(), eXoIdMap, s, invitor, event));
            message.setTo(s);
            message.setMimeType(Utils.MIMETYPE_TEXTHTML);
            message.setFrom(user.getEmail());
            if (attachmentCal != null) {
                message.addAttachment(attachmentCal);
            }
            if (!atts.isEmpty()) {
                for (Attachment att : atts) {
                    org.exoplatform.services.mail.Attachment attachment = new org.exoplatform.services.mail.Attachment();
                    attachment.setInputStream(att.getInputStream());
                    attachment.setMimeType(att.getMimeType());
                    message.addAttachment(attachment);
                }
            }
            mService.sendMessage(message);
        }
    }
}

From source file:org.kepler.ssh.SshExec.java

public String getwildcardFileListingBBCP(String srcConn, String wildcardPattern) throws ExecException {
    // TODO Auto-generated method stub
    String filePath = "";
    String filePattern = "";
    OutputStream streamOut = new ByteArrayOutputStream();
    OutputStream streamErr = new ByteArrayOutputStream();
    StringBuffer wildcardList = new StringBuffer();
    Vector<String> fileList = new Vector();
    int index = wildcardPattern.lastIndexOf("/");
    int exitCode = 1;

    //extract pattern and directory name from wildcard pattern
    if (index != -1) {
        filePattern = wildcardPattern.substring(index + 1);
        filePath = wildcardPattern.substring(0, index);
    }// ww  w .ja v  a2 s.c om
    System.out.println("parent dir : " + filePath);
    System.out.println("File pattern : " + filePattern);

    try {
        //-Q is used to place file names into quotations
        exitCode = executeCmd("\\ls -Q " + filePath, streamOut, streamErr, srcConn);
    } catch (ExecException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new ExecException("Could not list contents of remote directory " + filePath);
    }

    if (exitCode != 0) {
        throw new ExecException("Failed to execute remote command.");
    }

    //TODO Anand:extract filenames from ls entry
    // the character \n does not separate file names in a few scenarios.
    // To make the extraction more efficient - we are using a loop
    // If possible to get a separating character for ls field names use that instead of the loop 
    // IN THE LOOP: each filename has format "file_name"
    // We extract string in between " " to get the file name 
    String ls_output = streamOut.toString();
    int f_start = 0;
    int f_end = 0;
    while (f_end < ls_output.length()) {
        f_start = ls_output.indexOf("\"");
        ls_output = ls_output.substring(f_start + 1);
        f_end = ls_output.indexOf("\"");
        fileList.add(ls_output.substring(0, f_end));
        ls_output = ls_output.substring(f_end + 1);
    }

    //match filenames to pattern and create a file list
    String pattern = filePattern.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").replaceAll("\\?", ".");
    Pattern p = Pattern.compile(pattern);

    for (String curFile : fileList) {
        System.out.println(":" + curFile + ";");
        curFile = curFile.trim();
        Matcher m = p.matcher(curFile);
        if (m.matches()) {
            wildcardList.append(srcConn);
            wildcardList.append(":\"");
            wildcardList.append(filePath);
            wildcardList.append("/");
            wildcardList.append(curFile);
            wildcardList.append("\"");
            wildcardList.append(" ");
        }
    }
    System.out.println("wild card list formed is : " + wildcardList);

    return wildcardList.toString();
}

From source file:com.att.nsa.mr.client.impl.MRSimplerBatchPublisher.java

private synchronized boolean sendBatch() {
    // it's possible for this call to be made with an empty list. in this case, just return.
    if (fPending.size() < 1) {
        return true;
    }//  w  ww  .  j a v a2s . c o m

    final long nowMs = Clock.now();

    host = this.fHostSelector.selectBaseHost();

    final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"),
            props.getProperty("partition"));

    try {
        /*final String contentType =
           fCompress ?
              MRFormat.CAMBRIA_ZIP.toString () :
              MRFormat.CAMBRIA.toString () 
        ;*/

        final ByteArrayOutputStream baseStream = new ByteArrayOutputStream();
        OutputStream os = baseStream;
        final String contentType = props.getProperty("contenttype");
        if (contentType.equalsIgnoreCase("application/json")) {
            JSONArray jsonArray = new JSONArray();
            for (TimestampedMessage m : fPending) {
                JSONObject jsonObject = new JSONObject(m.fMsg);

                jsonArray.put(jsonObject);

            }
            os.write(jsonArray.toString().getBytes());
            os.close();

        } else if (contentType.equalsIgnoreCase("text/plain")) {
            for (TimestampedMessage m : fPending) {
                os.write(m.fMsg.getBytes());
                os.write('\n');
            }
            os.close();
        } else if (contentType.equalsIgnoreCase("application/cambria")
                || (contentType.equalsIgnoreCase("application/cambria-zip"))) {
            if (contentType.equalsIgnoreCase("application/cambria-zip")) {
                os = new GZIPOutputStream(baseStream);
            }
            for (TimestampedMessage m : fPending) {

                os.write(("" + m.fPartition.length()).getBytes());
                os.write('.');
                os.write(("" + m.fMsg.length()).getBytes());
                os.write('.');
                os.write(m.fPartition.getBytes());
                os.write(m.fMsg.getBytes());
                os.write('\n');
            }
            os.close();
        } else {
            for (TimestampedMessage m : fPending) {
                os.write(m.fMsg.getBytes());

            }
            os.close();
        }

        final long startMs = Clock.now();
        if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) {

            DME2Configue();

            Thread.sleep(5);
            getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: "
                    + (nowMs - fPending.peek().timestamp) + " ms");
            sender.setPayload(os.toString());
            String dmeResponse = sender.sendAndWait(5000L);

            final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + dmeResponse.toString();
            getLog().info(logLine);
            fPending.clear();
            return true;
        }

        if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
            getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
                    + (nowMs - fPending.peek().timestamp) + " ms");
            final JSONObject result = postAuth(httpurl, baseStream.toByteArray(), contentType, authKey,
                    authDate, username, password, protocolFlag);
            //System.out.println(result.getInt("status"));
            //Here we are checking for error response. If HTTP status
            //code is not within the http success response code
            //then we consider this as error and return false
            if (result.getInt("status") < 200 || result.getInt("status") > 299) {
                return false;
            }
            final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
            getLog().info(logLine);
            fPending.clear();
            return true;
        }

        if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) {
            getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
                    + (nowMs - fPending.peek().timestamp) + " ms");
            final JSONObject result = post(httpurl, baseStream.toByteArray(), contentType, username, password,
                    protocolFlag);

            //System.out.println(result.getInt("status"));
            //Here we are checking for error response. If HTTP status
            //code is not within the http success response code
            //then we consider this as error and return false
            if (result.getInt("status") < 200 || result.getInt("status") > 299) {
                return false;
            }
            final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
            getLog().info(logLine);
            fPending.clear();
            return true;
        }
    } catch (IllegalArgumentException x) {
        getLog().warn(x.getMessage(), x);
    } catch (IOException x) {
        getLog().warn(x.getMessage(), x);
    } catch (HttpException x) {
        getLog().warn(x.getMessage(), x);
    } catch (Exception x) {
        getLog().warn(x.getMessage(), x);
    }
    return false;
}

From source file:org.sdm.spa.actors.transport.SrmliteCopier.java

@Override
protected CopyResult copyRemote(ConnectionDetails srcDetails, String srcFile, ConnectionDetails destDetails,
        String destFile, boolean recursive) throws ExecException {
    if (isDebugging)
        log.debug("remote srmlite copy");
    ByteArrayOutputStream cmdStdout = new ByteArrayOutputStream();
    ByteArrayOutputStream cmdStderr = new ByteArrayOutputStream();
    String remoteHostStr = "";
    SshExec sshObjectSrc = null;/*ww w.  jav a 2  s  .  co  m*/
    SshExec sshObjectDest = null;
    // String file_transfer_cmd = null;
    String filehome = null;
    // File single_srcFileObj = null;
    // File mult_srcFileObj = null;
    String[] srcFileList = null;
    String[] srcFile_list = null;
    StringBuffer warn = new StringBuffer(100);
    boolean warn_flag = false;
    // FileWriter fstream;
    StringBuffer cmd = new StringBuffer(100);
    String cmdWithPath = null;
    int exitCode = 0;
    OutputStream streamOut = new ByteArrayOutputStream();
    OutputStream streamErr = new ByteArrayOutputStream();
    StringBuffer xml_file_contents = new StringBuffer();

    String osname = (System.getProperty("os.name")).toLowerCase();
    String cmdFile = "srmlite_" + System.currentTimeMillis() + ".xml";
    String userhome = (System.getProperty("user.home")).toLowerCase();
    String getRemoteHome_Cmd = "echo $HOME";

    // File destfileobj = new File(destFile);
    // File srcFileObj = new File(srcFile);

    if (srcFile.contains(",")) {
        srcFileList = srcFile.split(",");
        srcFile_list = new String[srcFileList.length];
        for (int count = 0; count < srcFileList.length; count++) {
            if ((srcFileList[count].trim()).startsWith("/")) {
                srcFile_list[count] = srcFileList[count].trim();
            } else {
                warn.append(srcFile_list[count].trim() + " ");
                if (!warn_flag)
                    warn_flag = true;
            }
        }
        if (warn_flag) {
            warn.append(" does not contain full path to the source file. Please provide full path. ");
            warn_flag = false;
        }
    } else {
        if (!srcFile.startsWith("/")) {
            throw new SshException(
                    srcFile + "does not contain full path to the file. Please provide full path.");
        }
    }
    sshObjectSrc = new SshExec(srcDetails.getUser(), srcDetails.getHost(), srcDetails.getPort());
    sshObjectDest = new SshExec(destDetails.getUser(), destDetails.getHost(), destDetails.getPort());
    if (srcDetails.isConnectionOrigin()) {
        // Conenct to source by ssh
        System.out.println("***********SRC is connection origin");

        remoteHostStr = destDetails.toString();
        exitCode = sshObjectSrc.executeCmd(getRemoteHome_Cmd, streamOut, streamErr, remoteHostStr);
        filehome = streamOut.toString().trim();
        sshObjectSrc.setTimeout(timeout, false, false);
        sshObjectSrc.setForcedCleanUp(forcedCleanup);
        // srmlite doesn't need a pseudo terminal
        sshObjectSrc.setPseudoTerminal(false);

    } else {
        System.out.println("***********DEST is connection origin");
        remoteHostStr = srcDetails.toString();
        exitCode = sshObjectDest.executeCmd(getRemoteHome_Cmd, streamOut, streamErr, remoteHostStr);
        filehome = streamOut.toString().trim();
        sshObjectDest.setTimeout(timeout, false, false);
        sshObjectDest.setForcedCleanUp(forcedCleanup);
        // srmlite doesn't need a pseudo terminal
        sshObjectDest.setPseudoTerminal(false);
    }

    cmdFile = filehome + "/" + cmdFile;

    if (srcFile.contains(",")) {
        System.out.println("***********Building xml file");
        try {
            // Create xml file
            // fstream = new FileWriter(userhome + File.separatorChar
            // + cmdFile);
            // BufferedWriter out = new BufferedWriter(fstream);

            xml_file_contents.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            xml_file_contents.append("\n");
            xml_file_contents.append("<request>");
            xml_file_contents.append("\n");

            if (srcDetails.isConnectionOrigin()) {
                // Create list of source files to be copied
                for (int i = 0; i < srcFile_list.length; i++) {
                    xml_file_contents.append("<file>");
                    xml_file_contents.append("\n");
                    xml_file_contents.append("<sourceurl>");
                    xml_file_contents.append("file:///");
                    xml_file_contents.append(srcFile_list[i]);
                    xml_file_contents.append("</sourceurl>");
                    xml_file_contents.append("\n");
                    // File fileObj = new File(srcFile_list[i]);
                    if (sshObjectSrc.isRemoteFileDirectory(srcFile_list[i])) {
                        // if the file is a dir
                        xml_file_contents.append("<recursive>");
                        xml_file_contents.append("true");
                        xml_file_contents.append("</recursive>");
                        xml_file_contents.append("\n");
                    }
                    xml_file_contents.append("</file>");
                    xml_file_contents.append("\n");
                }
                xml_file_contents.append("</request>");
                // Close the output stream
                // out.close();
            } else {
                for (int i = 0; i < srcFile_list.length; i++) {
                    xml_file_contents.append("<file>");
                    xml_file_contents.append("\n");
                    xml_file_contents.append("<sourceurl>");
                    if (srmProtocol.equals("")) {
                        xml_file_contents.append("scp://");
                    } else {
                        xml_file_contents.append(srmProtocol);
                        xml_file_contents.append("://");
                    }
                    xml_file_contents.append(srcDetails.toString());
                    xml_file_contents.append("/");
                    xml_file_contents.append(srcFile_list[i]);
                    xml_file_contents.append("</sourceurl>");
                    xml_file_contents.append("\n");
                    if (sshObjectSrc.isRemoteFileDirectory(srcFile_list[i])) {
                        // if the file is a dir
                        xml_file_contents.append("<recursive>");
                        xml_file_contents.append("true");
                        xml_file_contents.append("</recursive>");
                        xml_file_contents.append("\n");
                    }
                    xml_file_contents.append("</file>");
                    xml_file_contents.append("\n");
                }
                xml_file_contents.append("</request>");
                // out.close();
            }
        } catch (Exception e) {// Catch exception if any
            System.err.println("Error creating xml file: " + e.getMessage());
        }

        System.out.println("**************Xml file created...");
        System.out.println("**************Transferring sml file...");
        try {
            String temp_cmd = "echo -e '" + xml_file_contents + "' >> " + cmdFile;
            System.out.println("***************XML command : " + temp_cmd);
            if (srcDetails.isConnectionOrigin())
                exitCode = sshObjectSrc.executeCmd(temp_cmd, streamOut, streamErr, remoteHostStr);
            else
                exitCode = sshObjectDest.executeCmd(temp_cmd, streamOut, streamErr, remoteHostStr);
            if (exitCode != 0)
                throw new Exception("XML file creation failed with exit code : " + exitCode);
        } catch (Exception e) {
            return new CopyResult(1, "Failed to copy XML file to remote source!!!", e.toString());
        }
    } // end of build & transfer xml file
    /*
     * //command format
     * //"<path>/srmlite -s file:////<srcfile> -t scp://user@host/<dest path>"
     */

    if (srcDetails.isConnectionOrigin()) {
        System.out.println("*********************Building srmlite copy command");

        if (srcFile.contains(",")) {// list of files is provided.
            // TODO Anand: Do not use srmlite.bat - this is always a linux
            // machine
            cmd.append("srmlite -f ");
            cmd.append("file:///");
            cmd.append(cmdFile);
            cmd.append(" -td ");
        } else { // single file/directory to be copied
            // TODO Anand: Do not use srmlite.bat - this is always a linux
            // machine
            cmd.append("srmlite -s ");
            cmd.append("\"");
            cmd.append("file:///");
            cmd.append(srcFile);
            cmd.append("\"");
            if (recursive) {
                cmd.append(" -recursive");
            }
            try {
                if (sshObjectDest.isRemoteFileDirectory(destFile)) {
                    // target is a directory
                    cmd.append(" -td ");
                } else {// target is a file
                    cmd.append(" -t ");
                }
            } catch (Exception e) {
                return new CopyResult(1, destFile + " not found!!!", e.toString());
            }
        } // single file else ends

        if (srmProtocol.equals("")) {
            cmd.append("scp://");
        } else {
            cmd.append(srmProtocol);
            cmd.append("://");
        }
        cmd.append(destDetails.toString());
        cmd.append(destFile);
    } else {
        // Anand: destination is selected as origin

        System.out.println("************* Building srmlite command: *****************");

        if (srcFile.contains(",")) {
            // TODO Anand: Add/remove .bat - this is always a linux machine
            cmd.append("srmlite -f ");
            cmd.append("file:///");
            cmd.append(cmdFile);
            cmd.append(" -td ");
        } else {
            // TODO Anand: Add/remove .bat - this is always a linux machine
            cmd.append("srmlite -s ");
            cmd.append("\"");
            if (srmProtocol.equals("")) {
                cmd.append("scp://");
            } else {
                cmd.append(srmProtocol);
                cmd.append("://");
            }
            cmd.append(srcDetails.toString());
            // cmd.append("/");
            cmd.append(srcFile);
            cmd.append("\"");
            if (recursive) // if copying directories
                cmd.append(" -recursive");

            try {
                if (sshObjectDest.isRemoteFileDirectory(destFile)) {
                    // -td is used if target is a directory.
                    cmd.append(" -td ");
                } else {
                    cmd.append(" -t ");
                }
            } catch (Exception e) {
                return new CopyResult(1, destFile + " not found!!!", e.toString());
            }
        }
        cmd.append("file:///");
        cmd.append(destFile);
    }
    if (srcDetails.isConnectionOrigin()) {
        if (protocolPathSrc.equals("")) {
            if (osname.contains("windows")) {
                cmdWithPath = cmd.toString();
            } else {
                cmdWithPath = getCmdWithDefaultPath(cmd);
            }
        } else {
            cmdWithPath = protocolPathSrc + cmd;
        }
    } else {
        if (protocolPathDest.equals("")) {
            if (osname.contains("windows")) {
                cmdWithPath = cmd.toString();
            } else {
                cmdWithPath = getCmdWithDefaultPath(cmd);
            }
        } else {
            cmdWithPath = protocolPathDest + cmd;
        }
    }

    System.out.println("****Srmlite command executed is : " + cmdWithPath);

    try {
        if (srcDetails.isConnectionOrigin())
            exitCode = sshObjectSrc.executeCmd(cmdWithPath, cmdStdout, cmdStderr, remoteHostStr);
        else
            exitCode = sshObjectDest.executeCmd(cmdWithPath, cmdStdout, cmdStderr, remoteHostStr);
    } catch (ExecException e) {
        return new CopyResult(1, e.toString(), "");
    }
    if (isDebugging) {
        log.error("Output on stdout:" + cmdStdout);
        log.error("Output on stderr:" + cmdStderr);
    }
    String message = cmdStderr.toString();
    message = message + " \n\n" + cmdStdout.toString();

    String fileDeleteMsg = "";
    try {
        boolean success = false;
        if (srcDetails.isConnectionOrigin())
            success = sshObjectSrc.deleteFile(cmdFile, false, false);
        else
            success = sshObjectDest.deleteFile(cmdFile, false, false);

        if (success) {
            log.debug("deleted the xml script file " + cmdFile + " created for file copy");
        }
        if (!success) {
            log.warn("Unable to delete the xml script file " + cmdFile + " created for file copy");
            fileDeleteMsg = "Unable to delete the xml script file " + cmdFile + " created for file copy";
        }
    } catch (ExecException e) {
        log.warn(
                "Unable to delete the xml script file " + cmdFile + " created for file copy : " + e.toString());
    }
    return new CopyResult(exitCode, message + fileDeleteMsg, "");
}

From source file:com.att.nsa.mr.client.impl.MRSimplerBatchPublisher.java

public synchronized MRPublisherResponse sendBatchWithResponse() {
    // it's possible for this call to be made with an empty list. in this case, just return.
    if (fPending.size() < 1) {
        pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
        pubResponse.setResponseMessage("No Messages to send");
        return pubResponse;
    }/*ww  w .ja va 2  s.  co  m*/

    final long nowMs = Clock.now();

    host = this.fHostSelector.selectBaseHost();

    final String httpurl = MRConstants.makeUrl(host, fTopic, props.getProperty("Protocol"),
            props.getProperty("partition"));
    OutputStream os = null;
    try {

        final ByteArrayOutputStream baseStream = new ByteArrayOutputStream();
        os = baseStream;
        final String contentType = props.getProperty("contenttype");
        if (contentType.equalsIgnoreCase("application/json")) {
            JSONArray jsonArray = new JSONArray();
            for (TimestampedMessage m : fPending) {
                JSONObject jsonObject = new JSONObject(m.fMsg);

                jsonArray.put(jsonObject);

            }
            os.write(jsonArray.toString().getBytes());
        } else if (contentType.equalsIgnoreCase("text/plain")) {
            for (TimestampedMessage m : fPending) {
                os.write(m.fMsg.getBytes());
                os.write('\n');
            }
        } else if (contentType.equalsIgnoreCase("application/cambria")
                || (contentType.equalsIgnoreCase("application/cambria-zip"))) {
            if (contentType.equalsIgnoreCase("application/cambria-zip")) {
                os = new GZIPOutputStream(baseStream);
            }
            for (TimestampedMessage m : fPending) {

                os.write(("" + m.fPartition.length()).getBytes());
                os.write('.');
                os.write(("" + m.fMsg.length()).getBytes());
                os.write('.');
                os.write(m.fPartition.getBytes());
                os.write(m.fMsg.getBytes());
                os.write('\n');
            }
            os.close();
        } else {
            for (TimestampedMessage m : fPending) {
                os.write(m.fMsg.getBytes());

            }
        }

        final long startMs = Clock.now();
        if (ProtocolTypeConstants.DME2.getValue().equalsIgnoreCase(protocolFlag)) {

            try {
                DME2Configue();

                Thread.sleep(5);
                getLog().info("sending " + fPending.size() + " msgs to " + url + subContextPath + ". Oldest: "
                        + (nowMs - fPending.peek().timestamp) + " ms");
                sender.setPayload(os.toString());

                String dmeResponse = sender.sendAndWait(5000L);
                System.out.println("dmeres->" + dmeResponse);

                pubResponse = createMRPublisherResponse(dmeResponse, pubResponse);

                if (Integer.valueOf(pubResponse.getResponseCode()) < 200
                        || Integer.valueOf(pubResponse.getResponseCode()) > 299) {

                    return pubResponse;
                }
                final String logLine = String.valueOf((Clock.now() - startMs)) + dmeResponse.toString();
                getLog().info(logLine);
                fPending.clear();

            } catch (DME2Exception x) {
                getLog().warn(x.getMessage(), x);
                pubResponse.setResponseCode(x.getErrorCode());
                pubResponse.setResponseMessage(x.getErrorMessage());
            } catch (URISyntaxException x) {

                getLog().warn(x.getMessage(), x);
                pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
                pubResponse.setResponseMessage(x.getMessage());
            } catch (Exception x) {

                pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
                pubResponse.setResponseMessage(x.getMessage());

            }

            return pubResponse;
        }

        if (ProtocolTypeConstants.AUTH_KEY.getValue().equalsIgnoreCase(protocolFlag)) {
            getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
                    + (nowMs - fPending.peek().timestamp) + " ms");
            final String result = postAuthwithResponse(httpurl, baseStream.toByteArray(), contentType, authKey,
                    authDate, username, password, protocolFlag);
            //System.out.println(result.getInt("status"));
            //Here we are checking for error response. If HTTP status
            //code is not within the http success response code
            //then we consider this as error and return false

            pubResponse = createMRPublisherResponse(result, pubResponse);

            if (Integer.valueOf(pubResponse.getResponseCode()) < 200
                    || Integer.valueOf(pubResponse.getResponseCode()) > 299) {

                return pubResponse;
            }

            final String logLine = "MR reply ok (" + (Clock.now() - startMs) + " ms):" + result.toString();
            getLog().info(logLine);
            fPending.clear();
            return pubResponse;
        }

        if (ProtocolTypeConstants.AAF_AUTH.getValue().equalsIgnoreCase(protocolFlag)) {
            getLog().info("sending " + fPending.size() + " msgs to " + httpurl + ". Oldest: "
                    + (nowMs - fPending.peek().timestamp) + " ms");
            final String result = postWithResponse(httpurl, baseStream.toByteArray(), contentType, username,
                    password, protocolFlag);

            //System.out.println(result.getInt("status"));
            //Here we are checking for error response. If HTTP status
            //code is not within the http success response code
            //then we consider this as error and return false
            pubResponse = createMRPublisherResponse(result, pubResponse);

            if (Integer.valueOf(pubResponse.getResponseCode()) < 200
                    || Integer.valueOf(pubResponse.getResponseCode()) > 299) {

                return pubResponse;
            }

            final String logLine = String.valueOf((Clock.now() - startMs));
            getLog().info(logLine);
            fPending.clear();
            return pubResponse;
        }
    } catch (IllegalArgumentException x) {
        getLog().warn(x.getMessage(), x);
        pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
        pubResponse.setResponseMessage(x.getMessage());

    } catch (IOException x) {
        getLog().warn(x.getMessage(), x);
        pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
        pubResponse.setResponseMessage(x.getMessage());

    } catch (HttpException x) {
        getLog().warn(x.getMessage(), x);
        pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_BAD_REQUEST));
        pubResponse.setResponseMessage(x.getMessage());

    } catch (Exception x) {
        getLog().warn(x.getMessage(), x);

        pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
        pubResponse.setResponseMessage(x.getMessage());

    }

    finally {
        if (fPending.size() > 0) {
            getLog().warn("Send failed, " + fPending.size() + " message to send.");
            pubResponse.setPendingMsgs(fPending.size());
        }
        if (os != null) {
            try {
                os.close();
            } catch (Exception x) {
                getLog().warn(x.getMessage(), x);
                pubResponse.setResponseCode(String.valueOf(HttpStatus.SC_INTERNAL_SERVER_ERROR));
                pubResponse.setResponseMessage("Error in closing Output Stream");
            }
        }
    }

    return pubResponse;
}