Example usage for org.jdom2.output XMLOutputter XMLOutputter

List of usage examples for org.jdom2.output XMLOutputter XMLOutputter

Introduction

In this page you can find the example usage for org.jdom2.output XMLOutputter XMLOutputter.

Prototype

public XMLOutputter(XMLOutputProcessor processor) 

Source Link

Document

This will create an XMLOutputter with the specified XMLOutputProcessor.

Usage

From source file:Frames.CrExperience3.java

private void jButton24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton24ActionPerformed
    // TODO add your handling code here:
    if (!jTextField1.isEnabled() && go == 1) {
        int option = JOptionPane.showConfirmDialog(rootPane, "Voulez-vous enregistr ?");
        if (option == 0) {
            try {

                Element configs = new Element("config");
                Element emplacement = new Element("emplacement");
                configs.addContent(emplacement);
                Element emplacementQuestion = new Element("EmplacementQuestion");
                emplacementQuestion.setText("" + position);
                emplacement.addContent(emplacementQuestion);
                Element font = new Element("fons");
                font.setText(jComboBox3.getSelectedItem().toString());
                emplacement.addContent(font);
                Element couleur = new Element("couleur");
                couleur.setText(jButton10.getForeground().getRed() + "/" + jButton10.getForeground().getGreen()
                        + "/" + jButton10.getForeground().getBlue());

                Element taille = new Element("taille");
                taille.setText(jComboBox4.getSelectedItem().toString());

                emplacement.addContent(couleur);
                emplacement.addContent(taille);
                if (jToggleButton1.isSelected()) {
                    Element ecran = new Element("ecran");
                    Element couleur2 = new Element("couleur");
                    couleur2.setText(jButton12.getForeground().getRed() + "/"
                            + jButton12.getForeground().getGreen() + "/" + jButton12.getForeground().getBlue());

                    ecran.addContent(couleur2);
                    if (jRadioButton12.isSelected()) {
                        Attribute type = new Attribute("type", "fixe");
                        ecran.setAttribute(type);
                        Element fixe = new Element("fixe");
                        fixe.setText(textField1.getText());
                        ecran.addContent(fixe);

                    } else if (jRadioButton13.isSelected()) {
                        Attribute type = new Attribute("type", "aleatoire");
                        ecran.setAttribute(type);
                        Element aleatoire = new Element("aleatoire");
                        Element de = new Element("de");
                        de.setText(textField2.getText());
                        Element a = new Element("a");
                        a.setText(textField3.getText());
                        aleatoire.addContent(de);
                        aleatoire.addContent(a);
                        ecran.addContent(aleatoire);
                    }//w  w  w  .j  ava2 s .co  m

                    configs.addContent(ecran);
                }
                Element consigne = new Element("consigne");
                Element text = new Element("text");
                text.setText(jTextArea3.getText());
                consigne.addContent(text);
                Element font2 = new Element("fons");
                font2.setText(jComboBox1.getSelectedItem().toString());
                consigne.addContent(font2);
                Element couleur3 = new Element("couleur");
                couleur3.setText(jButton13.getForeground().getRed() + "/" + jButton13.getForeground().getGreen()
                        + "/" + jButton13.getForeground().getBlue());

                consigne.addContent(couleur3);
                Element taille1 = new Element("taille");
                taille1.setText(jComboBox2.getSelectedItem().toString());
                consigne.addContent(taille1);
                configs.addContent(consigne);
                experience.addContent(configs);

                //On utilise ici un affichage classique avec getPrettyFormat()
                XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
                //Remarquez qu'il suffit simplement de crer une instance de FileOutputStream
                //avec en argument le nom du fichier pour effectuer la srialisation.

                sortie.output(document, new FileOutputStream("Exp3/Experiences.xml"));
                jTextArea2.setText("");

                this.setVisible(false);
                CrExperience1 cr = new CrExperience1();
                cr.setVisible(true);
                cr.setLocationRelativeTo(null);
            } catch (java.io.IOException e) {
            }

        }

        else {

        }
    } else {
        JOptionPane.showMessageDialog(rootPane,
                "Entrez un ID et veuillez le vrfifier SVP! ou Remplissez bien le formulaire !");
    }
}

From source file:Frames.CrExperience3.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:

    if (!jTextField1.isEnabled() && go == 1) {
        int option = JOptionPane.showConfirmDialog(rootPane, "Voulez-vous enregistr ?");
        if (option == 0) {
            try {

                Element configs = new Element("config");
                Element emplacement = new Element("emplacement");
                configs.addContent(emplacement);
                Element emplacementQuestion = new Element("EmplacementQuestion");
                emplacementQuestion.setText("" + position);
                emplacement.addContent(emplacementQuestion);
                Element font = new Element("fons");
                font.setText(jComboBox3.getSelectedItem().toString());
                emplacement.addContent(font);
                Element couleur = new Element("couleur");
                couleur.setText(jButton10.getForeground().getRed() + "/" + jButton10.getForeground().getGreen()
                        + "/" + jButton10.getForeground().getBlue());

                Element taille = new Element("taille");
                taille.setText(jComboBox4.getSelectedItem().toString());

                emplacement.addContent(couleur);
                emplacement.addContent(taille);
                if (jToggleButton1.isSelected()) {
                    Element ecran = new Element("ecran");
                    Element couleur2 = new Element("couleur");
                    couleur2.setText(jButton12.getForeground().getRed() + "/"
                            + jButton12.getForeground().getGreen() + "/" + jButton12.getForeground().getBlue());

                    ecran.addContent(couleur2);
                    if (jRadioButton12.isSelected()) {
                        Attribute type = new Attribute("type", "fixe");
                        ecran.setAttribute(type);
                        Element fixe = new Element("fixe");
                        fixe.setText(textField1.getText());
                        ecran.addContent(fixe);

                    } else if (jRadioButton13.isSelected()) {
                        Attribute type = new Attribute("type", "aleatoire");
                        ecran.setAttribute(type);
                        Element aleatoire = new Element("aleatoire");
                        Element de = new Element("de");
                        de.setText(textField2.getText());
                        Element a = new Element("a");
                        a.setText(textField3.getText());
                        aleatoire.addContent(de);
                        aleatoire.addContent(a);
                        ecran.addContent(aleatoire);
                    }/*from   ww  w. j  a  v a  2 s.c  om*/

                    configs.addContent(ecran);
                }
                Element consigne = new Element("consigne");
                Element text = new Element("text");
                text.setText(jTextArea3.getText());
                consigne.addContent(text);
                Element font2 = new Element("fons");
                font2.setText(jComboBox1.getSelectedItem().toString());
                consigne.addContent(font2);
                Element couleur3 = new Element("couleur");
                couleur3.setText(jButton13.getForeground().getRed() + "/" + jButton13.getForeground().getGreen()
                        + "/" + jButton13.getForeground().getBlue());

                consigne.addContent(couleur3);
                Element taille1 = new Element("taille");
                taille1.setText(jComboBox2.getSelectedItem().toString());
                consigne.addContent(taille1);
                configs.addContent(consigne);
                experience.addContent(configs);

                //On utilise ici un affichage classique avec getPrettyFormat()
                XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
                //Remarquez qu'il suffit simplement de crer une instance de FileOutputStream
                //avec en argument le nom du fichier pour effectuer la srialisation.

                sortie.output(document, new FileOutputStream("Exp3/Experiences.xml"));
                jTextArea2.setText("");

                this.setVisible(false);
                CrExperience1 cr = new CrExperience1();
                cr.setVisible(true);
                cr.setLocationRelativeTo(null);
            } catch (java.io.IOException e) {
            }

        }

        else {

        }
    } else {
        JOptionPane.showMessageDialog(rootPane,
                "Entrez un ID et veuillez le vrfifier SVP! ou Remplissez bien le formulaire !");
    }
}

From source file:gestetu05.GestionnaireUtilisateur.java

synchronized void enregistreXML(String fichier) {
    try {//from ww w  . java  2s .  c  o  m
        //On utilise ici un affichage classique avec getPrettyFormat()
        XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
        //Remarquez qu'il suffit simplement de crer une instance de FileOutputStream
        //avec en argument le nom du fichier pour effectuer la srialisation.
        sortie.output(document, new FileOutputStream(fichier));
    } catch (java.io.IOException e) {
    }
}

From source file:hintahaku.Asetukset.java

private static void tallenna() {
    Element juuri = new Element("asetukset");
    juuri.setAttribute("info", "Hintahaku-asetukset");
    juuri.setAttribute("pvm", new SimpleDateFormat("d.M.y H:mm:ss").format(Calendar.getInstance().getTime()));

    if (suodatintiedosto != null) {
        juuri.addContent(new Element("suodatintiedosto").setText(suodatintiedosto.toString()));
    }//w w w .java2s  .co m
    if (viimeisinSuodatinKansio != null) {
        juuri.addContent(new Element("viimeisinSuodatinKansio").setText(viimeisinSuodatinKansio.toString()));
    }
    if (viimeisinKokoonpanoKansio != null) {
        juuri.addContent(
                new Element("viimeisinKokoonpanoKansio").setText(viimeisinKokoonpanoKansio.toString()));
    }

    Document xml = new Document(juuri);
    try (BufferedWriter writer = Files.newBufferedWriter(tiedosto)) {
        new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
    } catch (IOException ex) {
    }
}

From source file:hintahaku.HintahakuFrame.java

private void tallenna(Path tallennettava) {
    Element juuri = new Element("kokoonpano");
    juuri.setAttribute("info", "Tallennettu Hintahaku-kokoonpano");
    juuri.setAttribute("pvm", new SimpleDateFormat("d.M.y H:mm:ss").format(Calendar.getInstance().getTime()));

    for (KokoonpanoTuote tuote : Kokoonpano.getTuotteet()) {
        Element tuoteEl = new Element("tuote");
        tuoteEl.addContent(new Element("url").setText(tuote.getUrl()));
        tuoteEl.addContent(new Element("mr").setText(Integer.toString(tuote.getMaara())));
        juuri.addContent(tuoteEl);//from w w w  .j  a  v  a 2s . c  om
    }

    org.jdom2.Document xml = new org.jdom2.Document(juuri);
    try (BufferedWriter writer = Files.newBufferedWriter(tallennettava)) {
        new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Tiedoston tallentaminen eponnistui!", "Virhe!",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    Kokoonpano.setTiedosto(tallennettava);
    jLabel11.setText("Avattu: " + tallennettava.getFileName().toString());
    jButton7.setEnabled(false);
}

From source file:hintahaku.HintahakuFrame.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    //Avaa//from  www . j av a2s  .  c  o  m
    Path viimeisin = Asetukset.getViimeisinKokoonpanoKansio();
    JFileChooser valitsin = new JFileChooser(viimeisin == null ? null : viimeisin.toFile());
    valitsin.setFileFilter(new FileNameExtensionFilter("Kokoonpanot (xml)", "xml"));
    int valinta = valitsin.showOpenDialog(rootPane);
    if (valinta != JFileChooser.APPROVE_OPTION) {
        return;
    }
    Path avattava = valitsin.getSelectedFile().toPath();
    Asetukset.setViimeisinKokoonpanoKansio(avattava.getParent());

    org.jdom2.Document xml;
    try (BufferedReader reader = Files.newBufferedReader(avattava)) {
        xml = new SAXBuilder().build(reader);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Tiedoston avaaminen eponnistui!", "Virhe!",
                JOptionPane.ERROR_MESSAGE);
        return;
    } catch (JDOMException ex) {
        JOptionPane.showMessageDialog(null, "Avattu tiedosto ei ole kokoonpano!", "Virhe!",
                JOptionPane.ERROR_MESSAGE);
        return;
    }
    Element juuri = xml.getRootElement();
    if (!"Tallennettu Hintahaku-kokoonpano".equals(juuri.getAttributeValue("info"))) {
        JOptionPane.showMessageDialog(null, "Avattu tiedosto ei ole kokoonpano!", "Virhe!",
                JOptionPane.ERROR_MESSAGE);
        return;
    }

    String vanhaTeksti = jLabel11.getText();
    jLabel11.setText("Haetaan kokoonpanon hintatietoja...");
    new SwingWorker<List<RaakaTuote>, Void>() {

        @Override
        protected List<RaakaTuote> doInBackground() throws Exception {
            List<RaakaTuote> lista = new ArrayList<>();
            Pattern urlPattern = Pattern.compile("http://hinta\\.fi/\\d+");
            for (Element tuoteEl : juuri.getChildren()) {
                String url = tuoteEl.getChildText("url");
                int maara = Integer.parseInt(tuoteEl.getChildText("mr"));
                if (!urlPattern.matcher(url).matches() || maara <= 0) {
                    throw new KokoonpanoTiedostoException();
                }

                Document dok;
                try {
                    dok = Jsoup.connect(url).userAgent(USERAGENT).get();
                } catch (HttpStatusException ex) { //Tuotetta ei ole en olemassa
                    dok = null;
                }
                lista.add(new RaakaTuote(url, dok, maara));
            }
            return lista;
        }

        @Override
        protected void done() {
            List<RaakaTuote> lista;
            try {
                lista = get();
            } catch (InterruptedException ex) {
                JOptionPane.showMessageDialog(null, "Tuntematon virhe!", "Virhe!", JOptionPane.ERROR_MESSAGE);
                jLabel11.setText(vanhaTeksti);
                return;
            } catch (ExecutionException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof IOException) {
                    JOptionPane.showMessageDialog(null, "Ohjelma ei saa yhteytt hinta.fi-palvelimeen!",
                            "Virhe!", JOptionPane.ERROR_MESSAGE);
                } else if (cause instanceof NumberFormatException
                        || cause instanceof KokoonpanoTiedostoException) {
                    JOptionPane.showMessageDialog(null, "Avattu tiedosto on virheellinen!", "Virhe!",
                            JOptionPane.ERROR_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(null, "Tuntematon virhe!", "Virhe!",
                            JOptionPane.ERROR_MESSAGE);
                }
                jLabel11.setText(vanhaTeksti);
                return;
            }

            List<KokoonpanoTuote> lisattavat = new ArrayList<>();
            for (RaakaTuote raakaTuote : lista) {
                if (raakaTuote.dok == null) {
                    Object[] napit = { "Poista tuote", "l nyt" };
                    int valinta = JOptionPane.showOptionDialog(null,
                            "<html>Tuotetta ei lydy en hinta.fi:st:<br><b>" + raakaTuote.url
                                    + "</b><br><br>Haluatko poistaa tuotteen tiedostosta, vai jtt sen vain nyttmtt kokoonpanossa? (Tallentaminen poistaa silti.)",
                            "Varmistus", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, napit,
                            napit[1]);
                    if (valinta == JOptionPane.YES_OPTION) {
                        Iterator<Element> xmlIter = juuri.getChildren().iterator();
                        while (xmlIter.hasNext()) {
                            Element tuoteEl = xmlIter.next();
                            if (raakaTuote.url.equals(tuoteEl.getChildText("url"))) {
                                xmlIter.remove();
                                break;
                            }
                        }
                        try (BufferedWriter writer = Files.newBufferedWriter(avattava)) {
                            new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null,
                                    "Tuotteen poistaminen eponnistui, joten se jtetn tiedostoon!",
                                    "Virhe!", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } else {
                    Tuote tuote = new Tuote(raakaTuote.url, raakaTuote.dok);
                    if (tuote.getParasHinta() == null) {
                        Object[] napit = { "Poista tuote", "Jt kokoonpanoon" };
                        int valinta = JOptionPane.showOptionDialog(null,
                                "<html>Tuotetta ei ole saatavilla en yhdesskn kaupassa:<br><b>"
                                        + tuote.getNimi()
                                        + "</b><br><br>Haluatko poistaa tuotteen tiedostosta?",
                                "Varmistus", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null,
                                napit, napit[1]);
                        if (valinta == JOptionPane.YES_OPTION) {
                            Iterator<Element> xmlIter = juuri.getChildren().iterator();
                            while (xmlIter.hasNext()) {
                                Element tuoteEl = xmlIter.next();
                                if (tuote.getUrl().equals(tuoteEl.getChildText("url"))) {
                                    xmlIter.remove();
                                    break;
                                }
                            }
                            try (BufferedWriter writer = Files.newBufferedWriter(avattava)) {
                                new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
                                continue; //Keskeytetn tuotteen lisminen
                            } catch (IOException ex) {
                                JOptionPane.showMessageDialog(null,
                                        "Tuotteen poistaminen eponnistui, joten se jtetn tiedostoon!",
                                        "Virhe!", JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    }

                    lisattavat.add(new KokoonpanoTuote(tuote, raakaTuote.maara));
                }
            }

            Kokoonpano.tyhjennaJaLisaaMonta(lisattavat);
            Kokoonpano.setTiedosto(avattava);
            paivitaKokoonpanonTulos();
            paivitaLisattyMaara();
            jLabel11.setText("Avattu: " + avattava.getFileName().toString());
            jButton7.setEnabled(false);
        }
    }.execute();
}

From source file:hintahaku.Suodattimet.java

public static void tallennaNimella(Path tiedosto) throws IOException {
    Element juuri = new Element("suodattimet");
    juuri.setAttribute("info", "Hintahaku-suodattimet");
    juuri.setAttribute("pvm", new SimpleDateFormat("d.M.y H:mm:ss").format(Calendar.getInstance().getTime()));

    for (Kauppa kauppa : kaupatEventList) {
        Element kauppaxml = new Element("kauppa");
        kauppaxml.addContent(new Element("nimi").setText(kauppa.getKaupanNimi()));
        kauppaxml.addContent(new Element("voiNoutaa").setText(Boolean.toString(kauppa.isVoiNoutaa())));
        kauppaxml.addContent(new Element("suodataPois").setText(Boolean.toString(kauppa.isSuodataPois())));
        juuri.addContent(kauppaxml);//from w w  w . j  av a  2  s . c  om
    }

    Document xml = new Document(juuri);
    try (BufferedWriter writer = Files.newBufferedWriter(tiedosto)) {
        new XMLOutputter(Format.getPrettyFormat()).output(xml, writer);
    }

    Suodattimet.tiedosto = tiedosto;
}

From source file:io.LoadSave.java

License:Open Source License

/**
 * Saves the current status to a .oger file
 *//*  w w w.j  a v  a  2s  .c o m*/
public static void save() {
    // get the selected file
    File file = IODialog.showSaveDialog(".oger", true);
    // not canceled
    if (file != null) {
        DefaultTreeModel treeModel = RoomTreeModel.getInstance();
        ParticipantTableModel participantModel = ParticipantTableModel.getInstance();

        // Create the XML root Element
        Element root = new Element("root");

        // Create a JDOM Document based on the root Element
        Document document = new Document(root);

        List<Participant> participants = participantModel.getParticipants();

        // Participants
        Element allParticipantsElement = new Element("allParticipants");

        for (Participant p : participants) {
            Element participantElement = new Element("participant");

            Attribute firstNameAttribute = new Attribute("firstName", p.getFirstName());
            participantElement.setAttribute(firstNameAttribute);

            Attribute lastNameAttribute = new Attribute("lastName", p.getLastName());
            participantElement.setAttribute(lastNameAttribute);

            Attribute mailAttribute = new Attribute("mail", p.geteMailAdress());
            participantElement.setAttribute(mailAttribute);

            Attribute groupAttribute = new Attribute("group", Integer.toString(p.getGroupNumber()));
            participantElement.setAttribute(groupAttribute);

            allParticipantsElement.addContent(participantElement);
        }
        root.addContent(allParticipantsElement);

        // Slots with reviews
        Element allSlotsElement = new Element("Slots");

        // all slots
        SlotNode currentSlotNode;
        RoomNode currentRoomNode;
        DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) treeModel.getRoot();

        DateFormat dateFormatter = new SimpleDateFormat("dd.MM.yy");
        DateFormat beginFormatter = new SimpleDateFormat("HH:mm");
        DateFormat endFormatter = new SimpleDateFormat("HH:mm");
        ;

        for (Enumeration<SlotNode> enumSlots = rootNode.children(); enumSlots.hasMoreElements();) {
            currentSlotNode = (SlotNode) enumSlots.nextElement();
            Slot currentSlot = (Slot) currentSlotNode.getUserObject();

            Element slotElement = new Element("Slot");

            String date = dateFormatter.format(currentSlot.getDate().getTime());
            Attribute dateAttribute = new Attribute("Date", date);
            slotElement.setAttribute(dateAttribute);

            String begin = beginFormatter.format(currentSlot.getBeginTime().getTime());
            Attribute beginAttribute = new Attribute("Begin", begin);
            slotElement.setAttribute(beginAttribute);

            String end = endFormatter.format(currentSlot.getEndTime().getTime());
            Attribute endAttribute = new Attribute("End", end);
            slotElement.setAttribute(endAttribute);

            // all rooms
            Element allRoomsElement = new Element("AllRooms");

            for (Enumeration<RoomNode> enumRooms = currentSlotNode.children(); enumRooms.hasMoreElements();) {
                currentRoomNode = (RoomNode) enumRooms.nextElement();
                Room currentRoom = (Room) currentRoomNode.getUserObject();

                Element roomElement = new Element("Room");

                Attribute beamerAttribute;
                if (currentRoom.hasBeamer()) {
                    beamerAttribute = new Attribute("Beamer", "true");
                } else {
                    beamerAttribute = new Attribute("Beamer", "false");
                }
                roomElement.setAttribute(beamerAttribute);

                Attribute idAttribute = new Attribute("ID", currentRoom.getRoomID());
                roomElement.setAttribute(idAttribute);

                String beginRoom = beginFormatter.format(currentRoom.getBeginTime().getTime());
                Attribute beginRoomAttribute = new Attribute("Begin", beginRoom);
                roomElement.setAttribute(beginRoomAttribute);

                String endRoom = endFormatter.format(currentRoom.getEndTime().getTime());
                Attribute endRoomAttribute = new Attribute("End", endRoom);
                roomElement.setAttribute(endRoomAttribute);

                allRoomsElement.addContent(roomElement);

            }
            slotElement.addContent(allRoomsElement);

            allSlotsElement.addContent(slotElement);

        }

        root.addContent(allSlotsElement);

        try {
            // output
            XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
            xmlOutputter.output(document, new FileOutputStream(file));
            Main.setSaved(true);
        } catch (java.io.IOException e) {
            JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
        }
    }
}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

public Response execute(RequestBuilder b) {
    try {//  w ww .ja  va2  s. c o m

        String method = b.getMethod();
        Preconditions.checkArgument(!Strings.isNullOrEmpty(method), "method argument must be passed");

        String url = null;

        Response resp;
        String format = b.getParams().getOrDefault("format", "xml");
        b = b.param("format", format);
        if (!b.hasBody()) {

            url = formatUrl(b.getParams(), format);
            FormEncodingBuilder fb = new FormEncodingBuilder().add("session_id", getAuthToken());
            for (Map.Entry<String, String> entry : b.getParams().entrySet()) {
                if (!entry.getValue().equals("format")) {
                    fb = fb.add(entry.getKey(), entry.getValue());
                }
            }
            resp = getClient().newCall(new Request.Builder().url(getUrl()).post(fb.build()).build()).execute();
        } else if (b.getXmlBody().isPresent()) {
            b = b.param("format", "xml");
            url = formatUrl(b.getParams(), "xml");
            String bodyAsString = new XMLOutputter(Format.getRawFormat()).outputString(b.getXmlBody().get());
            final MediaType XML = MediaType.parse("text/xml");

            resp = getClient().newCall(new Request.Builder().url(url)
                    .post(RequestBody.create(XML, bodyAsString)).header("Content-Type", "text/xml").build())
                    .execute();
        } else if (b.getJsonBody().isPresent()) {
            b = b.param("format", "json");
            url = formatUrl(b.getParams(), "json");
            String bodyAsString = mapper.writeValueAsString(b.getJsonBody().get());

            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            resp = getClient().newCall(new Request.Builder().url(url).post(

                    RequestBody.create(JSON, bodyAsString)).header("Content-Type", "application/json").build())
                    .execute();
        } else {
            throw new UnsupportedOperationException("body type not supported");
        }
        // the A10 API rather stupidly uses 200 responses even when there is
        // an error
        if (!resp.isSuccessful()) {
            logger.warn("response code={}", resp.code());
        }

        return resp;

    } catch (IOException e) {
        throw new ElbException(e);
    }
}

From source file:io.smartspaces.master.server.services.internal.support.JdomMasterDomainModelCreator.java

License:Apache License

/**
 * Create a description of the entire space domain.
 *
 * @param activityRepository/*from w  w w  .  j av  a 2 s. co m*/
 *          the repository for activity entities
 * @param controllerRepository
 *          the repository for controller entities
 * @param resourceRepository
 *          the repository for resources
 * @param automationRepository
 *          the repository for automation entities
 *
 * @return the XML description
 */
public String newModel(ActivityRepository activityRepository, SpaceControllerRepository controllerRepository,
        ResourceRepository resourceRepository, AutomationRepository automationRepository) {

    try {
        Element rootElement = new Element(ELEMENT_NAME_DESCRIPTION_ROOT_ELEMENT);
        Document document = new Document(rootElement);

        rootElement.addContent(newSpaceControllerEntries(controllerRepository));
        rootElement.addContent(newActivityEntries(activityRepository));
        rootElement.addContent(newLiveActivityEntries(activityRepository));
        rootElement.addContent(newLiveActivityGroupEntries(activityRepository));
        rootElement.addContent(newSpaceEntries(activityRepository));
        rootElement.addContent(newResourceEntries(resourceRepository));
        rootElement.addContent(newNamedScriptEntries(automationRepository));

        StringWriter out = new StringWriter();

        Format format = Format.getPrettyFormat();
        XMLOutputter outputter = new XMLOutputter(format);
        outputter.output(document, out);

        return out.toString();
    } catch (IOException e) {
        throw new SmartSpacesException("Could not create domain model", e);
    }
}