Example usage for javax.xml.bind Marshaller setProperty

List of usage examples for javax.xml.bind Marshaller setProperty

Introduction

In this page you can find the example usage for javax.xml.bind Marshaller setProperty.

Prototype

public void setProperty(String name, Object value) throws PropertyException;

Source Link

Document

Set the particular property in the underlying implementation of Marshaller .

Usage

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

/**
 * This method is to configure NAT and Firewall Rules to the EdgeGateway
 * /*  ww w. ja  v  a2  s .com*/
 * @param networkHref
 *            the href to the network on which nat rules to be applied
 * @param serviceConfHref
 *            the href to the service configure action of gateway
 * @return
 */
private void configureRules(String networkHref, String serviceConfHref) {
    // NAT Rules
    NatServiceType natService = new NatServiceType();

    // To Enable the service using this flag
    natService.setIsEnabled(Boolean.TRUE);

    // Configuring Destination nat
    NatRuleType dnatRule = new NatRuleType();

    // Setting Rule type Destination Nat DNAT
    dnatRule.setRuleType("DNAT");
    dnatRule.setIsEnabled(Boolean.TRUE);
    GatewayNatRuleType dgatewayNat = new GatewayNatRuleType();
    ReferenceType refd = new ReferenceType();
    refd.setHref(networkHref);

    // Network on which nat rules to be applied
    dgatewayNat.setInterface(refd);

    // Setting Original IP
    dgatewayNat.setOriginalIp(options.externalIp);
    dgatewayNat.setOriginalPort("any");

    dgatewayNat.setTranslatedIp(options.internalIp);

    // To allow all ports and all protocols
    // dgatewayNat.setTranslatedPort("any");
    // dgatewayNat.setProtocol("Any");

    // To allow only https use Port 443 and TCP protocol
    dgatewayNat.setTranslatedPort("any");
    dgatewayNat.setProtocol("TCP");

    // To allow only ssh use Port 22 and TCP protocol
    // dgatewayNat.setTranslatedPort("22");
    // dgatewayNat.setProtocol("TCP");
    // Setting Destination IP
    dnatRule.setGatewayNatRule(dgatewayNat);
    natService.getNatRule().add(dnatRule);

    // Configuring Source nat
    NatRuleType snatRule = new NatRuleType();

    // Setting Rule type Source Nat SNAT
    snatRule.setRuleType("SNAT");
    snatRule.setIsEnabled(Boolean.TRUE);
    GatewayNatRuleType sgatewayNat = new GatewayNatRuleType();
    //ReferenceType refd = new ReferenceType();
    //refd.setHref(networkHref);

    // Network on which nat rules to be applied
    sgatewayNat.setInterface(refd);

    // Setting Original IP
    sgatewayNat.setOriginalIp(options.internalIp);
    //sgatewayNat.setOriginalPort("any");

    sgatewayNat.setTranslatedIp(options.externalIp);

    // Setting Source IP
    snatRule.setGatewayNatRule(sgatewayNat);
    natService.getNatRule().add(snatRule);

    // Firewall Rules
    FirewallServiceType firewallService = new FirewallServiceType();

    // Enable or disable the service using this flag
    firewallService.setIsEnabled(Boolean.TRUE);

    // Default action of the firewall set to drop
    firewallService.setDefaultAction("drop");

    // Flag to enable logging for default action
    firewallService.setLogDefaultAction(Boolean.FALSE);

    // Firewall Rule settings
    FirewallRuleType firewallInRule = new FirewallRuleType();
    firewallInRule.setIsEnabled(Boolean.TRUE);
    firewallInRule.setMatchOnTranslate(Boolean.FALSE);
    firewallInRule.setDescription("Allow incoming https access");
    firewallInRule.setPolicy("allow");
    FirewallRuleProtocols firewallProtocol = new FirewallRuleProtocols();
    firewallProtocol.setAny(Boolean.TRUE);
    firewallInRule.setProtocols(firewallProtocol);
    firewallInRule.setDestinationPortRange("any");
    firewallInRule.setDestinationIp(options.externalIp);
    firewallInRule.setSourcePortRange("Any");
    firewallInRule.setSourceIp("external");
    firewallInRule.setEnableLogging(Boolean.FALSE);
    firewallService.getFirewallRule().add(firewallInRule);

    // To create the HttpPost request Body
    ObjectFactory objectFactory = new ObjectFactory();
    GatewayFeaturesType gatewayFeatures = new GatewayFeaturesType();
    JAXBElement<NetworkServiceType> serviceType = objectFactory.createNetworkService(natService);
    JAXBElement<NetworkServiceType> firewallserviceType = objectFactory.createNetworkService(firewallService);
    gatewayFeatures.getNetworkService().add(serviceType);
    gatewayFeatures.getNetworkService().add(firewallserviceType);
    JAXBContext jaxbContexts = null;

    try {
        jaxbContexts = JAXBContext.newInstance(GatewayFeaturesType.class);
    } catch (JAXBException ex) {
        ex.printStackTrace();
    }

    OutputStream os = null;
    JAXBElement<GatewayFeaturesType> gateway_Features = objectFactory
            .createEdgeGatewayServiceConfiguration(gatewayFeatures);

    try {
        javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        os = new ByteArrayOutputStream();

        // Marshal the JAXB class to XML
        marshaller.marshal(gateway_Features, os);
    } catch (JAXBException e) {
        e.printStackTrace();
    }

    HttpPost httpPost = vcd.post(serviceConfHref, options);
    ContentType contentType = ContentType.create(SampleConstants.CONTENT_TYPE_EDGE_GATEWAY, "ISO-8859-1");
    StringEntity rules = new StringEntity(os.toString(), contentType);
    httpPost.setEntity(rules);
    InputStream is = null;

    // Invoking api to add rules to gateway
    HttpResponse response = HttpUtils.httpInvoke(httpPost);

    // Make sure the response code is 202 ACCEPTED
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
        // System.out.println("ResponseCode : " + response.getStatusLine().getStatusCode());
        System.out.println("\nRequest To update Gateway initiated sucessfully");
        System.out.print("\nUpdating EdgeGateways to add NAT and Firewall Rules...");
        taskStatus(response);
    }
}

From source file:io.fabric8.cxf.endpoint.ManagedApi.java

@ManagedOperation(description = "get xml payload from json payload", currencyTimeLimit = 60)
public String jsonToXml(String jsonText, String pojoType) {
    ObjectMapper objectMapper = new ObjectMapper();
    StringWriter sw = new StringWriter();
    try {/*from w  ww . j  av  a2 s  . c  o m*/
        Object pojo = objectMapper.readValue(jsonText, findClass(pojoType));
        JAXBContext jc = JAXBContext.newInstance(findClass(pojoType));
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(pojo, sw);
    } catch (Exception e) {
        LOG.log(Level.WARNING, "jsonToXml failed.", e);
    }

    return sw.toString();
}

From source file:org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository.java

/**
 * Causes the dataPointMap to be persisted to a file
 * @param file file definition to persist the data set to
 * @return true if dataPointMap persisted correctly, false if not
 *///from w w w.j a va 2 s .co m
public boolean persist() {
    File currentArchiveFile = null;
    File tmpCurrentArchiveFile = null;
    Resource tmpResource = null;

    if (!persistHistoricData) {
        LOG.debug("not persisting data as persistHistoricData=false");
        return false;
    }

    if (archiveFileName == null || archiveFileDirectoryLocation == null) {
        LOG.error("cannot save historical data to file as incorrect file location:"
                + " archiveFileDirectoryLocation=" + archiveFileDirectoryLocation + " archiveFileName="
                + archiveFileName);
        return false;
    }

    // set the date on which this file was persisted
    datePersisted = new Date();

    // used to get file name suffix
    SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormatString);

    // persist data to temporary file <archiveFileName.tmp>
    String tmpArchiveFileName = archiveFileName + ".tmp";
    String tmpArchiveFileLocation = archiveFileDirectoryLocation + File.separator + tmpArchiveFileName;
    LOG.debug("historical data will be written to temporary file :" + tmpArchiveFileLocation);

    try {
        tmpResource = resourceLoader.getResource(tmpArchiveFileLocation);
        tmpCurrentArchiveFile = new File(tmpResource.getURL().getFile());
    } catch (IOException e) {
        LOG.error("cannot save historical data to file at archiveFileLocation='" + tmpArchiveFileLocation
                + "' due to error:", e);
        return false;
    }

    LOG.debug(
            "persisting historical data to temporary file location:" + tmpCurrentArchiveFile.getAbsolutePath());

    // marshal the data
    PrintWriter writer = null;
    boolean marshalledCorrectly = false;
    try {
        // create  directory if doesn't exist
        File directory = new File(tmpCurrentArchiveFile.getParentFile().getAbsolutePath());
        directory.mkdirs();
        // create file if doesn't exist
        writer = new PrintWriter(tmpCurrentArchiveFile, "UTF-8");
        writer.close();

        // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix
        // need to provide bundles class loader
        ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader();
        JAXBContext jaxbContext = JAXBContext.newInstance(
                "org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator", cl);

        //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator");

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        // TODO CHANGE output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        // marshal this Data Repository
        jaxbMarshaller.marshal(this, tmpCurrentArchiveFile);

        marshalledCorrectly = true;
    } catch (JAXBException e) {
        LOG.error("problem marshalling file: ", e);
    } catch (Exception e) {
        LOG.error("problem marshalling file: ", e);
    } finally {
        if (writer != null)
            writer.close();
    }
    if (marshalledCorrectly == false)
        return false;

    // marshaling succeeded so rename tmp file
    String archiveFileLocation = archiveFileDirectoryLocation + File.separator + archiveFileName;
    LOG.info("historical data will be written to:" + archiveFileLocation);

    Resource resource = resourceLoader.getResource(archiveFileLocation);

    if (resource.exists()) {
        String oldArchiveFileName = archiveFileName + "." + dateFormatter.format(datePersisted);
        String oldArchiveFileLocation = archiveFileDirectoryLocation + File.separator + oldArchiveFileName;
        LOG.info("previous historical file at archiveFileLocation='" + archiveFileLocation
                + "' exists so being renamed to " + oldArchiveFileLocation);
        Resource oldresource = resourceLoader.getResource(oldArchiveFileLocation);
        try {
            currentArchiveFile = new File(resource.getURL().getFile());
            File oldArchiveFile = new File(oldresource.getURL().getFile());
            // rename current archive file to old archive file name
            if (!currentArchiveFile.renameTo(oldArchiveFile)) {
                throw new IOException("cannot rename current archive file:"
                        + currentArchiveFile.getAbsolutePath() + " to " + oldArchiveFile.getAbsolutePath());
            }
            // rename temporary archive file to current archive file name
            if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) {
                throw new IOException("cannot rename temporary current archive file:"
                        + tmpCurrentArchiveFile.getAbsolutePath() + " to "
                        + currentArchiveFile.getAbsolutePath());
            }
        } catch (IOException e) {
            LOG.error("Problem archiving old persistance file", e);
        }
        // remove excess files
        try {
            Resource directoryResource = resourceLoader.getResource(archiveFileDirectoryLocation);
            File archiveFolder = new File(directoryResource.getURL().getFile());
            File[] listOfFiles = archiveFolder.listFiles();

            String filename;
            //this will sort earliest to latest date
            TreeMap<Date, File> sortedFiles = new TreeMap<Date, File>();

            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    filename = listOfFiles[i].getName();
                    if ((!filename.equals(archiveFileName)) && (!filename.equals(tmpArchiveFileName))
                            && (filename.startsWith(archiveFileName))) {
                        String beforeTimeString = archiveFileName + ".";
                        String timeSuffix = filename.substring(beforeTimeString.length());
                        if (!"".equals(timeSuffix)) {
                            Date fileCreatedate = null;
                            try {
                                fileCreatedate = dateFormatter.parse(timeSuffix);
                            } catch (ParseException e) {
                                LOG.debug("cant parse file name suffix to time for filename:" + filename, e);
                            }
                            if (fileCreatedate != null) {
                                sortedFiles.put(fileCreatedate, listOfFiles[i]);
                            }
                        }
                    }
                }
            }

            while (sortedFiles.size() > archiveFileMaxNumber) {
                File removeFile = sortedFiles.remove(sortedFiles.firstKey());
                LOG.debug("deleting archive file:'" + removeFile.getName()
                        + "' so that number of archive files <=" + archiveFileMaxNumber);
                removeFile.delete();
            }
            for (File archivedFile : sortedFiles.values()) {
                LOG.debug("not deleting archive file:'" + archivedFile.getName()
                        + "' so that number of archive files <=" + archiveFileMaxNumber);
            }

            return true;
        } catch (IOException e) {
            LOG.error("Problem removing old persistance files", e);
        }
    } else {
        // if resource doesn't exist just rename the new tmp file to the archive file name
        try {
            currentArchiveFile = new File(resource.getURL().getFile());
            // rename temporary archive file to current archive file name
            if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) {
                throw new IOException("cannot rename temporary current archive file:"
                        + tmpCurrentArchiveFile.getAbsolutePath() + " to "
                        + currentArchiveFile.getAbsolutePath());
            }
            return true;
        } catch (IOException e) {
            LOG.error("cannot rename temporary current archive ", e);
        }
    }

    return false;

}

From source file:com.aionemu.gameserver.dataholders.SpawnsData2.java

public synchronized boolean saveSpawn(Player admin, VisibleObject visibleObject, boolean delete)
        throws IOException {
    SpawnTemplate spawn = visibleObject.getSpawn();
    Spawn oldGroup = DataManager.SPAWNS_DATA2.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId());

    File xml = new File("./data/static_data/spawns/" + getRelativePath(visibleObject));
    SpawnsData2 data = null;//w  w w .  j a va 2  s  . c  o  m
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = null;
    JAXBContext jc = null;
    boolean addGroup = false;

    try {
        schema = sf.newSchema(new File("./data/static_data/spawns/spawns.xsd"));
        jc = JAXBContext.newInstance(SpawnsData2.class);
    } catch (Exception e) {
        // ignore, if schemas are wrong then we even could not call the command;
    }

    FileInputStream fin = null;
    if (xml.exists()) {
        try {
            fin = new FileInputStream(xml);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            unmarshaller.setSchema(schema);
            data = (SpawnsData2) unmarshaller.unmarshal(fin);
        } catch (Exception e) {
            log.error(e.getMessage());
            PacketSendUtility.sendMessage(admin, "Could not load old XML file!");
            return false;
        } finally {
            if (fin != null) {
                fin.close();
            }
        }
    }

    if (oldGroup == null || oldGroup.isCustom()) {
        if (data == null) {
            data = new SpawnsData2();
        }

        oldGroup = data.getSpawnsForNpc(visibleObject.getWorldId(), spawn.getNpcId());
        if (oldGroup == null) {
            oldGroup = new Spawn(spawn.getNpcId(), spawn.getRespawnTime(), spawn.getHandlerType());
            addGroup = true;
        }
    } else {
        if (data == null) {
            data = DataManager.SPAWNS_DATA2;
        }
        // only remove from memory, will be added back later
        allSpawnMaps.get(visibleObject.getWorldId()).remove(spawn.getNpcId());
        addGroup = true;
    }

    SpawnSpotTemplate spot = new SpawnSpotTemplate(visibleObject.getX(), visibleObject.getY(),
            visibleObject.getZ(), visibleObject.getHeading(), visibleObject.getSpawn().getRandomWalk(),
            visibleObject.getSpawn().getWalkerId(), visibleObject.getSpawn().getWalkerIndex());
    boolean changeX = visibleObject.getX() != spawn.getX();
    boolean changeY = visibleObject.getY() != spawn.getY();
    boolean changeZ = visibleObject.getZ() != spawn.getZ();
    boolean changeH = visibleObject.getHeading() != spawn.getHeading();
    if (changeH && visibleObject instanceof Npc) {
        Npc npc = (Npc) visibleObject;
        if (!npc.isAtSpawnLocation() || !npc.isInState(CreatureState.NPC_IDLE) || changeX || changeY
                || changeZ) {
            // if H changed, XSD validation fails, because it may be negative; thus, reset it back
            visibleObject.setXYZH(null, null, null, spawn.getHeading());
            changeH = false;
        }
    }

    SpawnSpotTemplate oldSpot = null;
    for (SpawnSpotTemplate s : oldGroup.getSpawnSpotTemplates()) {
        if (s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ()
                && s.getHeading() == spot.getHeading()) {
            if (delete || !StringUtils.equals(s.getWalkerId(), spot.getWalkerId())) {
                oldSpot = s;
                break;
            } else {
                return false; // nothing to change
            }
        } else if (changeX && s.getY() == spot.getY() && s.getZ() == spot.getZ()
                && s.getHeading() == spot.getHeading()
                || changeY && s.getX() == spot.getX() && s.getZ() == spot.getZ()
                        && s.getHeading() == spot.getHeading()
                || changeZ && s.getX() == spot.getX() && s.getY() == spot.getY()
                        && s.getHeading() == spot.getHeading()
                || changeH && s.getX() == spot.getX() && s.getY() == spot.getY() && s.getZ() == spot.getZ()) {
            oldSpot = s;
            break;
        }
    }

    if (oldSpot != null) {
        oldGroup.getSpawnSpotTemplates().remove(oldSpot);
    }
    if (!delete) {
        oldGroup.addSpawnSpot(spot);
    }
    oldGroup.setCustom(true);

    SpawnMap map = null;
    if (data.templates == null) {
        data.templates = new ArrayList<SpawnMap>();
        map = new SpawnMap(spawn.getWorldId());
        data.templates.add(map);
    } else {
        map = data.templates.get(0);
    }

    if (addGroup) {
        map.addSpawns(oldGroup);
    }

    FileOutputStream fos = null;
    try {
        xml.getParentFile().mkdir();
        fos = new FileOutputStream(xml);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(data, fos);
        DataManager.SPAWNS_DATA2.templates = data.templates;
        DataManager.SPAWNS_DATA2.afterUnmarshal(null, null);
        DataManager.SPAWNS_DATA2.clearTemplates();
        data.clearTemplates();
    } catch (Exception e) {
        log.error(e.getMessage());
        PacketSendUtility.sendMessage(admin, "Could not save XML file!");
        return false;
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
    return true;
}

From source file:com.intuit.tank.service.impl.v1.script.ScriptServiceV1.java

/**
 * @{inheritDoc//from  ww w .ja va2 s .  c  o  m
 */
@Override
public Response downloadScript(Integer id) {
    ResponseBuilder responseBuilder = Response.ok();
    ScriptDao dao = new ScriptDao();
    final Script script = dao.findById(id);
    if (script != null) {
        String filename = script.getName() + "_TS.xml";
        responseBuilder.header("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        responseBuilder.cacheControl(ResponseUtil.getNoStoreCacheControl());
        final ScriptTO scriptTO = ScriptServiceUtil.scriptToTransferObject(script);
        StreamingOutput so = new StreamingOutput() {
            public void write(OutputStream outputStream) {
                // Get the object of DataInputStream
                try {
                    JAXBContext ctx = JAXBContext.newInstance(ScriptTO.class.getPackage().getName());
                    Marshaller marshaller = ctx.createMarshaller();
                    marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
                    marshaller.marshal(scriptTO, outputStream);
                } catch (Exception e) {
                    LOG.error("Error streaming file: " + e.toString(), e);
                    throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
                } finally {
                }
            }
        };
        responseBuilder.type(MediaType.APPLICATION_OCTET_STREAM_TYPE).entity(so);
    } else {
        responseBuilder = Response.noContent().status(Status.NOT_FOUND);
    }

    // add jobId to response
    return responseBuilder.build();
}

From source file:alter.vitro.vgw.service.VitroGatewayService.java

public void registerOnDemand(int modeFlag) throws Exception {
    if (!getUseIdas()) // send through pipe to the amethyst activeMQ
    {//from   w  w  w.  j a va  2s  .  com
        registerSOSpipe.run();
    }

    //Scan controlled WSI and associated resources

    CGateway myGateway = new CGateway();
    myGateway.setId(getAssignedGatewayUniqueIdFromReg());
    myGateway.setName("");
    myGateway.setDescription("");

    // The code for acquiring GW description is in the createWSIDescr() method
    CGatewayWithSmartDevices gwWithNodeDescriptorList = myDCon.createWSIDescr(myGateway);
    logger.debug("nodeDescriptorList = {}", gwWithNodeDescriptorList.getSmartDevVec());
    List<CSmartDevice> alterNodeDescriptorsList = gwWithNodeDescriptorList.getSmartDevVec();
    ResourceAvailabilityService.getInstance().updateCachedNodeList(alterNodeDescriptorsList,
            ResourceAvailabilityService.SUBSEQUENT_DISCOVERY);
    // PREPARE TO SEND THE MESSAGE!
    JAXBContext jaxbContext = Utils.getJAXBContext();
    Marshaller mar = jaxbContext.createMarshaller();
    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    // new new
    for (CSmartDevice alterNodeDescriptor : alterNodeDescriptorsList) {

        RegisterSensor registerSensor = sensorMLMessageAdapter.getRegisterSensorMessage(alterNodeDescriptor,
                gwWithNodeDescriptorList.getGateway());
        if (!getUseIdas()) // send through pipe to the amethyst activeMQ
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mar.marshal(registerSensor, baos);
            String requestXML = baos.toString(HTTP.UTF_8);
            registerSOSpipe.sendText(requestXML);
        } else {
            RegisterSensorResponse registerSensorResponse = idas.registerSensor(registerSensor);
            String assignedSensorId = registerSensorResponse.getAssignedSensorId();
            // DEBUG
            System.out.println("Registered Sensor with id: " + assignedSensorId);
            //Register assigned sensor id to associate subsequent observation to the correct node
            //TODO: understand if persistence is needed
            idasNodeMapping.put(alterNodeDescriptor.getId(), assignedSensorId);
        }
    }
    // end of --> new new
    /*
    //Register available resources on the external middleware (here the end user / VSP app)
    List<RegisterSensor> registerSensorList = sensorMLMessageAdapter.getRegisterSensorMessage(gwWithNodeDescriptorList);
    // PREPARE TO SEND THE MESSAGE!
    JAXBContext jaxbContext = Utils.getJAXBContext();
    Marshaller mar = jaxbContext.createMarshaller();
    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    for (RegisterSensor registerSensor : registerSensorList) {
            
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
            
    mar.marshal(registerSensor, baos);
    String requestXML = baos.toString(HTTP.UTF_8);
            
    if(!getUseIdas()) // send through pipe to the amethyst activeMQ
    {
        registerSOSpipe.sendText(requestXML);
    }
    else
    {
        IdasProxy IdasPrx = new IdasProxyImpl(getDVNSUrl());
        this.setIdas(IdasPrx);
        RegisterSensorResponse registerSensorResponse = idas.registerSensor(registerSensor);
        String assignedSensorId = registerSensorResponse.getAssignedSensorId();
        // DEBUG
        System.out.println("Registered Sensor with id: " + assignedSensorId);
        idasNodeMapping.put(, assignedSensorId);
    }
    }
      */

    // This closes the pipe for sending registering messages
    if (!getUseIdas()) // send through pipe to the amethyst activeMQ
    {
        registerSOSpipe.stop();
    }
    // SEND TO VSP a confirmation message of nodes/enabled disabled
    // IF VSP was already running and had a cache for this VGW, that this message will be ignored
    // But If VSP was restarted while the VGW was running, then this message will be used to update the VSP!!!
    // send ONLY if you have previously received some request from the VSP
    // which means ONLY if this is NOT the registerOnDemand call in the init(). Otherwise the VGW spoils the cache in the VSP with all nodes set as enabled
    if (modeFlag == POST_INIT_FLAG && isGwWasInitiated()) {
        String msgCurrentEnabledStatusFromCache = ResourceAvailabilityService.getInstance()
                .createSynchConfirmationForVSPFromCurrentStatus_VGWInitiated();
        if (msgCurrentEnabledStatusFromCache != null && !msgCurrentEnabledStatusFromCache.isEmpty()) {
            StringBuilder toAddHeaderBld = new StringBuilder();
            // based on a UserNodeResponse structure we should have a queryId (which here is the messageType again, as src which should be the VSPCore, and a body)
            toAddHeaderBld.append(UserNodeResponse.COMMAND_TYPE_ENABLENODES_RESP);
            toAddHeaderBld.append(UserNodeResponse.headerSpliter);
            toAddHeaderBld
                    .append(VitroGatewayService.getVitroGatewayService().getAssignedGatewayUniqueIdFromReg());

            toAddHeaderBld.append(UserNodeResponse.headerSpliter);
            toAddHeaderBld.append(msgCurrentEnabledStatusFromCache);
            msgCurrentEnabledStatusFromCache = toAddHeaderBld.toString();
            SimpleQueryHandler.getInstance().sendResponse(msgCurrentEnabledStatusFromCache);
        }
    }
}

From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

/**
 * Writes XML RepositoryItems as a RepositoryItemList. Ignores any other
 * type of RepositoryItem.s//from w  w  w  .  j  av  a 2  s.  c o  m
 */
void writeRepositoryItems(List<?> eos) throws IOException, RegistryException, ObjectNotFoundException {
    ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null);
    ServletOutputStream sout = response.getOutputStream();
    boolean doCommit = false;
    try {
        RepositoryItemListType ebRepositoryItemListType = bu.lcmFac.createRepositoryItemListType();

        Iterator<?> iter = eos.iterator();
        while (iter.hasNext()) {
            ExtrinsicObjectType eo = (ExtrinsicObjectType) iter.next();
            String id = eo.getId();

            RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context,
                    id);

            if (ri == null) {
                throw new ObjectNotFoundException(id,
                        ServerResourceBundle.getInstance().getString("message.repositoryItem"));
            } else {
                if (eo.getMimeType().equals("text/xml")) {
                    DataHandler dataHandler = ri.getDataHandler();
                    InputStream fStream = dataHandler.getInputStream();

                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setNamespaceAware(true);
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document document = builder.parse(fStream);
                    Element rootElement = document.getDocumentElement();

                    ebRepositoryItemListType.getAny().add(rootElement);
                }
            }
        }
        // javax.xml.bind.Marshaller marshaller =
        // bu.lcmFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        JAXBElement<RepositoryItemListType> ebRepositoryItemList = bu.lcmFac
                .createRepositoryItemList(ebRepositoryItemListType);
        marshaller.marshal(ebRepositoryItemList, sout);
        doCommit = true;

    } catch (JAXBException e) {
        throw new RegistryException(e);
    } catch (ParserConfigurationException e) {
        throw new RegistryException(e);
    } catch (SAXException e) {
        throw new RegistryException(e);
    } finally {
        if (sout != null) {
            sout.close();
            sout = null;
        }
        try {
            closeContext(context, doCommit);
        } catch (Exception ex) {
            log.error(ex, ex);
        }
    }
}

From source file:it.cnr.icar.eric.server.interfaces.soap.RegistrySAMLServlet.java

/**
 * This method is a copy of the respective method from RegistrySOAPServlet.
 * The SAML-based Servlet returns X.509 certificate base SOAP messages.
 * //from w  w w .j a v  a 2 s  .  c  o m
 */

private SOAPMessage createResponseSOAPMessage(Object obj) {

    SOAPMessage msg = null;

    try {
        RegistryResponseType ebRegistryResponseType = null;

        if (obj instanceof it.cnr.icar.eric.server.interfaces.Response) {
            Response r = (Response) obj;
            ebRegistryResponseType = r.getMessage();

        } else if (obj instanceof java.lang.Throwable) {
            Throwable t = (Throwable) obj;
            ebRegistryResponseType = it.cnr.icar.eric.server.common.Utility.getInstance()
                    .createRegistryResponseFromThrowable(t, "RegistrySOAPServlet", "Unknown");
        }

        // Now add resp to SOAPMessage
        StringWriter sw = new StringWriter();
        // javax.xml.bind.Marshaller marshaller =
        // bu.rsFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        if (ebRegistryResponseType.getClass() == RegistryResponseType.class) {
            // if ComplexType is explicit, wrap it into Element
            // only RegistryResponeType is explicit -> equal test instead of
            // isinstance
            JAXBElement<RegistryResponseType> ebRegistryResponse = bu.rsFac
                    .createRegistryResponse(ebRegistryResponseType);
            marshaller.marshal(ebRegistryResponse, sw);

        } else {
            // if ComplexType is anonymous, it can be marshalled directly
            marshaller.marshal(ebRegistryResponseType, sw);
        }

        // Now get the RegistryResponse as a String
        String respStr = sw.toString();

        // Use Unicode (utf-8) to getBytes (server and client). Rely on
        // platform default encoding is not safe.
        InputStream soapStream = it.cnr.icar.eric.server.common.Utility.getInstance()
                .createSOAPStreamFromRequestStream(new ByteArrayInputStream(respStr.getBytes("utf-8")));

        boolean signRequired = Boolean
                .valueOf(RegistryProperties.getInstance().getProperty("eric.interfaces.soap.signedResponse"))
                .booleanValue();

        msg = it.cnr.icar.eric.server.common.Utility.getInstance().createSOAPMessageFromSOAPStream(soapStream);

        if (signRequired) {

            AuthenticationServiceImpl auService = AuthenticationServiceImpl.getInstance();
            PrivateKey privateKey = auService.getPrivateKey(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR,
                    AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);
            java.security.cert.Certificate[] certs = auService
                    .getCertificateChain(AuthenticationServiceImpl.ALIAS_REGISTRY_OPERATOR);

            CredentialInfo credentialInfo = new CredentialInfo(null, (X509Certificate) certs[0], certs,
                    privateKey, null);

            SOAPPart sp = msg.getSOAPPart();
            SOAPEnvelope se = sp.getEnvelope();

            WSS4JSecurityUtilSAML.signSOAPEnvelopeOnServerBST(se, credentialInfo);

        }

        // msg.writeTo(new FileOutputStream(new
        // File("signedResponse.xml")));
        soapStream.close();
    } catch (IOException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (SOAPException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (javax.xml.bind.JAXBException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (ParseException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    } catch (RegistryException e) {
        log.warn(e, e);
        // otherwise ignore the problem updating part of the message
    }

    return msg;
}

From source file:at.gv.egovernment.moa.id.protocols.stork2.MandateRetrievalRequest.java

private PersonalAttribute marshallComplexAttribute(PersonalAttribute currentAttribute, Object obj) { // TODO refactor
    StringWriter stringWriter = new StringWriter();
    try {//from   w  ww.j a v a  2  s. c om
        if (obj instanceof MandateContentType) {
            final Marshaller marshaller = JAXBContext.newInstance(MandateContentType.class).createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(new JAXBElement<MandateContentType>(
                    new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()),
                    MandateContentType.class, null, (MandateContentType) obj), stringWriter);
        } else if (obj instanceof MandateType) {
            final Marshaller marshaller = JAXBContext.newInstance(MandateType.class).createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(new JAXBElement<MandateType>(
                    new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()),
                    MandateType.class, null, (MandateType) obj), stringWriter);
        } else if (obj instanceof RepresentationPersonType) {
            final Marshaller marshaller = JAXBContext.newInstance(RepresentationPersonType.class)
                    .createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(
                    new JAXBElement<RepresentationPersonType>(
                            new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()),
                            RepresentationPersonType.class, null, (RepresentationPersonType) obj),
                    stringWriter);
        }

    } catch (Exception ex) {
        Logger.error("Could not marshall atrribute: " + currentAttribute.getName() + ", " + ex.getMessage());
        return new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(),
                new ArrayList<String>(), AttributeStatusType.NOT_AVAILABLE.value());
    }
    ArrayList<String> value = new ArrayList<String>();
    value.add(stringWriter.toString());

    PersonalAttribute personalAttribute = new PersonalAttribute(currentAttribute.getName(),
            currentAttribute.isRequired(), value, AttributeStatusType.AVAILABLE.value());
    return personalAttribute;
}

From source file:gov.va.isaac.config.profiles.UserProfile.java

protected void store(File fileToWrite) throws IOException {
    try {/*from w  ww. j  av  a2 s. c om*/
        JAXBContext jaxbContext = JAXBContext.newInstance(UserProfile.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(this, fileToWrite);
    } catch (Exception e) {
        throw new IOException("Problem storings UserProfile to " + fileToWrite.getAbsolutePath(), e);
    }
}