Example usage for org.jdom2.input SAXBuilder SAXBuilder

List of usage examples for org.jdom2.input SAXBuilder SAXBuilder

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder SAXBuilder.

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:de.knewcleus.openradar.gui.flightplan.FlightPlanExchangeManager.java

License:Open Source License

private void loadUpdatesFromServer() {
    // collect the active contacts in range
    StringBuilder callSignList = new StringBuilder();
    for (GuiRadarContact contact : radarContactController.getContactListCopy()) {
        // we must send all because server releases contacts that are out of range
        if (callSignList.length() > 0) {
            callSignList.append(",");
        }//from ww  w.  j av  a  2  s.  c o m
        callSignList.append(contact.getCallSign().trim());
    }
    log.trace("Flightplan: " + data.getCallSign() + " Going to request updates for: " + callSignList);
    // send the list to the server to request updated flightplans

    //        if (callSignList.length() > 0) {

    try {
        StringBuilder result = new StringBuilder();
        String line = null;
        URL url;
        if (initial) {
            url = new URL(baseUrl + "/getAllFlightplans");
            initial = false;
        } else {
            url = new URL(baseUrl + "/getFlightplans");
        }

        String frequency = "000.00";
        if (!master.getRadioManager().getModels().isEmpty()) {
            frequency = master.getRadioManager().getModels().get("COM0").getSelectedItem().getFrequency();
        }

        String parameters = "user=" + URLEncoder.encode(data.getFpServerUser(), "UTF-8") + "&password="
                + URLEncoder.encode(data.getFpServerPassword(), "UTF-8") + "&username="
                + URLEncoder.encode("John Doe", "UTF-8") // todo
                + "&atc=" + URLEncoder.encode(data.getCallSign(), "UTF-8") + "&airport="
                + URLEncoder.encode(data.getAirportCode(), "UTF-8") + "&lon="
                + Double.toString(data.getAirportPosition().getX()) + "&lat="
                + Double.toString(data.getAirportPosition().getY()) + "&frequency=" + frequency
                + "&xmlVersion=1.0" + "&contacts=" + URLEncoder.encode(callSignList.toString(), "UTF-8");

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestProperty("Accept-Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        con.setRequestProperty("User-Agent", "OpenRadar");
        DataOutputStream dos = new DataOutputStream(con.getOutputStream());
        dos.write(parameters.getBytes("UTF-8"));
        dos.flush();
        dos.close();

        // parse response

        int responseCode = con.getResponseCode();
        if (responseCode == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            line = reader.readLine();
            while (line != null) {
                result.append(line).append("\n");
                line = reader.readLine();
            }
            reader.close();

            try {
                Document document = new SAXBuilder().build(new StringReader(result.toString().trim()));
                // String version = document.getRootElement().getAttributeValue("version");

                Element eAtcsInRange = document.getRootElement().getChild("atcsInRange");
                if (eAtcsInRange != null) {
                    List<FpAtc> activeAtcs = FpXml_1_0.parseAtcs(eAtcsInRange);
                    master.getRadarContactManager().setActiveAtcs(activeAtcs);
                }

                List<Element> eFlightPlans = document.getRootElement().getChildren("flightplan");
                for (Element eFp : eFlightPlans) {
                    String callsign = FpXml_1_0.getCallSign(eFp);
                    GuiRadarContact c = radarContactController.getContactFor(callsign);
                    if (c != null) {
                        radarContactController.updateFlightPlan(c, FpXml_1_0.parseXml(data, c, eFp));
                    }
                    log.info("Got FP update for: " + callsign);
                }
                connectedToServer = true;
            } catch (IOException e) {
                log.error("Error while parsing flightplan!", e);
            }

        } else {
            log.warn("Flightplan: " + data.getCallSign()
                    + " Failed to retrieve flightplan updates! (got response code " + responseCode + " from "
                    + url.toString() + ")...");
            connectedToServer = false;
        }
    } catch (ConnectException e) {
        log.error("Problem to connect to fpserver: " + e.getMessage());
    } catch (Exception e) {
        log.error("Problem to parse updated flightplans!", e);
    }
    //   } // callsignlist.length>0
}

From source file:de.knewcleus.openradar.gui.flightplan.lenny64.Lenny64FlightplanServerConnector.java

License:Open Source License

public List<FlightPlanData> checkForFlightplan(AirportData data, GuiRadarContact contact) {

    String callsign = contact.getCallSign();
    // http://lenny64.free.fr/dev2014_01_13.php5?getFlightplans&callsign=
    // http://flightgear-atc.alwaysdata.net/dev2014_01_13.php5
    String baseUrl = data.getLenny64Url();
    List<FlightPlanData> result = new ArrayList<FlightPlanData>();

    log.warn("Flightplan: " + data.getCallSign() + " Going to download existing flightplans for " + callsign
            + " from " + baseUrl);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {//  w  ww.j  ava 2  s.co m
        StringBuilder answer = new StringBuilder();
        String line = null;

        String parameters = "callsign=" + URLEncoder.encode(callsign, "UTF-8") //"&airport=*"// +
                                                                               // URLEncoder.encode(data.getAirportCode(),
                                                                               // "UTF-8")
                + "&date=" + URLEncoder.encode(sdf.format(new Date()), "UTF-8");
        URL url = new URL(baseUrl + "?getFlightplans&" + parameters);

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setRequestProperty("Accept-Charset", "UTF-8");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        con.setRequestProperty("User-Agent", "OpenRadar");
        DataOutputStream dos = new DataOutputStream(con.getOutputStream());
        // dos.write(parameters.getBytes("UTF-8"));
        dos.flush();
        dos.close();

        // parse response

        int responseCode = con.getResponseCode();
        if (responseCode == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            line = reader.readLine();
            while (line != null) {
                answer.append(line).append("\n");
                line = reader.readLine();
            }
            reader.close();

            try {
                Document document = new SAXBuilder().build(new StringReader(answer.toString().trim()));
                // String version = document.getRootElement().getAttributeValue("version");

                result = Lenny64XmlParser.parse(data, contact, document);

            } catch (IOException e) {
                log.error("Error while parsing flightplan from lenny64!", e);
                result = new ArrayList<FlightPlanData>();
            }

        } else {
            log.warn("Flightplan: " + data.getCallSign()
                    + " Failed to retrieve flightplan from lenny64! (got response code " + responseCode
                    + " from " + url.toString() + ")...");
        }
    } catch (ConnectException e) {
        log.error("Problem to connect to lenny64 server: " + e.getMessage());
    } catch (Exception e) {
        log.error("Problem to parse updated lenny63 flightplans!", e);
    }

    return result;
}

From source file:de.knewcleus.openradar.view.groundnet.GroundnetReader.java

License:Open Source License

private void readGroundnetXml() {

    SAXBuilder builder = new SAXBuilder();
    InputStream xmlInputStream = null;

    try {/*from   w ww. j  a v  a 2 s  .c  o m*/
        xmlInputStream = getZipArchiveFileInputStream("data/airports.zip", airportCode);

        Document document = (Document) builder.build(xmlInputStream);
        Element rootNode = document.getRootElement();

        // read parking list
        List<Element> list = rootNode.getChild("parkingList").getChildren("Parking");
        for (Element p : list) {
            String index = p.getAttributeValue("index");
            String type = p.getAttributeValue("type");
            String name = p.getAttributeValue("name");
            String number = p.getAttributeValue("number");
            String lat = p.getAttributeValue("lat");
            String lon = p.getAttributeValue("lon");
            String heading = p.getAttributeValue("heading");
            String radius = p.getAttributeValue("radius");
            String airlineCodes = p.getAttributeValue("airlineCodes");
            ParkPos pos = new ParkPos(index, type, name, number, lat, lon, heading, radius, airlineCodes);
            parkPosList.add(pos);
            mapTaxiPoints.put(index, pos);
        }

        // read nodes
        list = rootNode.getChild("TaxiNodes").getChildren("node");
        for (Element p : list) {
            String index = p.getAttributeValue("index");
            String lat = p.getAttributeValue("lat");
            String lon = p.getAttributeValue("lon");
            boolean isOnRunway = !"0".equals(p.getAttributeValue("isOnRunway"));
            String holdPointType = p.getAttributeValue("holdPointType");
            TaxiPoint point = new TaxiPoint(index, lat, lon, isOnRunway, holdPointType);
            mapTaxiPoints.put(index, point);
        }
        // read segments
        list = rootNode.getChild("TaxiWaySegments").getChildren("arc");
        for (Element a : list) {
            String beginPoint = a.getAttributeValue("begin");
            String endPoint = a.getAttributeValue("end");
            boolean isPushBackRoute = !"0".equals(a.getAttributeValue("isPushBackRoute"));
            String name = a.getAttributeValue("name");
            TaxiWaySegment seg = new TaxiWaySegment(name, mapTaxiPoints.get(beginPoint),
                    mapTaxiPoints.get(endPoint), isPushBackRoute);
            taxiwaySegmentList.add(seg);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        if (xmlInputStream != null) {
            try {
                xmlInputStream.close();
                zipArchive.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:de.knewcleus.openradar.view.stdroutes.StdRouteReader.java

License:Open Source License

private void readRouteXml() {

    SAXBuilder builder = new SAXBuilder();
    InputStream xmlInputStream = null;

    File dir = new File("data/routes/" + data.getAirportCode());
    if (!dir.exists() || !dir.isDirectory()) {
        return;//from  w  w w.ja va2 s  . c  o m
    }

    List<File> files = new ArrayList<File>(Arrays.asList(dir.listFiles()));

    data.getNavaidDB().clearAddPoints();

    while (files.size() > 0) {
        File file = files.remove(0);
        try {
            if (!file.getName().endsWith(".xml"))
                continue;
            // todo read all files
            xmlInputStream = new FileInputStream(file);

            Document document = (Document) builder.build(xmlInputStream);
            Element rootNode = document.getRootElement();

            //                String orFilename = "data/routes/" + data.getAirportCode() + "/" + file.getName().substring(0, file.getName().indexOf(".xml")) + ".or.xml";
            if ("ProceduresDB".equalsIgnoreCase(rootNode.getName())) {// && !(new File(orFilename).exists())) {
                // if converted file does not exist, convert it now.
                // deactivated for now convertProcedureDbFile(orFilename, rootNode);
            } else {
                // read or file
                List<Element> list = rootNode.getChildren("addPoint");
                for (Element eAddPoint : list) {
                    String code = eAddPoint.getAttributeValue("code");
                    String sPoint = eAddPoint.getAttributeValue("point");
                    try {
                        Point2D point = StdRoute.getPoint(data, mapViewAdapter, sPoint, null);
                        data.getNavaidDB().addPoint(code, point);
                    } catch (Exception e) {
                        log.error("Problem to parse file " + file.getAbsolutePath() + ", addPoint: " + code
                                + ": " + sPoint + ", Error:" + e.getMessage());
                    }
                }
                List<Element> includeList = rootNode.getChildren("include");
                for (Element eInclude : includeList) {
                    String fileName = eInclude.getAttributeValue("file");
                    files.add(new File(file.getAbsolutePath().substring(0,
                            file.getAbsolutePath().lastIndexOf(File.separator) + 1) + fileName));
                }
                // routes
                list = rootNode.getChildren("route");
                for (Element eRoute : list) {
                    String name = eRoute.getAttributeValue("name");
                    String displayMode = eRoute.getAttributeValue("displayMode");
                    String zoomMin = eRoute.getAttributeValue("zoomMin");
                    String zoomMax = eRoute.getAttributeValue("zoomMax");
                    String stroke = eRoute.getAttributeValue("stroke");
                    String lineWidth = eRoute.getAttributeValue("lineWidth");
                    String color = eRoute.getAttributeValue("color");
                    List<Element> sublist = eRoute.getChildren();
                    AStdRouteElement previous = null;
                    StdRoute route = new StdRoute(data, mapViewAdapter, name, displayMode, zoomMin, zoomMax,
                            stroke, lineWidth, color);
                    for (Element element : sublist) {
                        try {
                            if (element.getName().equalsIgnoreCase("activeLandingRunways")) {
                                route.setActiveLandingRunways(element.getText());
                            } else if (element.getName().equalsIgnoreCase("activeStartRunways")) {
                                route.setActiveStartingRunways(element.getText());
                            } else if (element.getName().equalsIgnoreCase("navaids")) {
                                color = element.getAttributeValue("color");
                                route.setNavaids(element.getText(), color);
                            } else if (element.getName().equalsIgnoreCase("include")) {
                                String routeName = element.getAttributeValue("routeName");
                                route.includeRoute(stdRoutes, routeName);
                            } else if (element.getName().equalsIgnoreCase("line")) {
                                String start = element.getAttributeValue("start");
                                String end = element.getAttributeValue("end");
                                String angle = element.getAttributeValue("angle");
                                String length = element.getAttributeValue("length");
                                String startOffset = element.getAttributeValue("startOffset");
                                String endOffset = element.getAttributeValue("endOffset");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                String text = element.getAttributeValue("text");
                                StdRouteLine line = new StdRouteLine(route, mapViewAdapter, previous, start,
                                        end, angle, length, startOffset, endOffset, stroke, lineWidth, arrows,
                                        color, text);
                                previous = line;
                                route.addElement(line);
                            } else if (element.getName().equalsIgnoreCase("bow")) {
                                String center = element.getAttributeValue("center");
                                String radius = element.getAttributeValue("radius");
                                String startAngle = element.getAttributeValue("startAngle");
                                String extentAngle = element.getAttributeValue("extentAngle");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                String text = element.getAttributeValue("text");
                                StdRouteBow bow = new StdRouteBow(route, mapViewAdapter, previous, center,
                                        radius, startAngle, extentAngle, stroke, lineWidth, color, arrows,
                                        text);
                                previous = bow;
                                route.addElement(bow);
                            } else if (element.getName().equalsIgnoreCase("curve")) {
                                String start = element.getAttributeValue("start");
                                String end = element.getAttributeValue("end");
                                String controlPoint = element.getAttributeValue("controlPoint");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                StdRouteCurve bow = new StdRouteCurve(route, mapViewAdapter, previous, start,
                                        end, controlPoint, stroke, lineWidth, color, arrows);
                                previous = bow;
                                route.addElement(bow);
                            } else if (element.getName().equalsIgnoreCase("intercept")) {
                                String start = element.getAttributeValue("start");
                                String startOffset = element.getAttributeValue("startOffset");
                                String startHeading = element.getAttributeValue("startHeading");
                                String startTurn = element.getAttributeValue("startTurn");
                                String radius = element.getAttributeValue("radius");
                                String speed = element.getAttributeValue("speed");
                                String end = element.getAttributeValue("end");
                                String radial = element.getAttributeValue("radial");
                                String endHeading = element.getAttributeValue("endHeading");
                                String direction = element.getAttributeValue("direction");
                                String endOffset = element.getAttributeValue("endOffset");
                                String text = element.getAttributeValue("text");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                String arrows = element.getAttributeValue("arrows");
                                color = element.getAttributeValue("color");
                                StdRouteIntercept intercept = new StdRouteIntercept(route, mapViewAdapter,
                                        previous, start, startOffset, startHeading, startTurn, radius, speed,
                                        end, radial, endHeading, direction, endOffset, stroke, lineWidth,
                                        arrows, color, text);
                                previous = intercept;
                                route.addElement(intercept);
                            } else if (element.getName().equalsIgnoreCase("loop")) {
                                String navpoint = element.getAttributeValue("navpoint");
                                String inboundHeading = element.getAttributeValue("inboundHeading");
                                String length = element.getAttributeValue("length");
                                String width = element.getAttributeValue("width");
                                String right = element.getAttributeValue("right");
                                String arrows = element.getAttributeValue("arrows");
                                String minHeight = element.getAttributeValue("minHeight");
                                String maxHeight = element.getAttributeValue("maxHeight");
                                String misapHeight = element.getAttributeValue("misapHeight");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                color = element.getAttributeValue("color");
                                StdRouteLoop ellipse = new StdRouteLoop(route, mapViewAdapter, previous,
                                        navpoint, inboundHeading, length, width, right, arrows, minHeight,
                                        maxHeight, misapHeight, stroke, lineWidth, color);
                                previous = ellipse;
                                route.addElement(ellipse);
                            } else if (element.getName().equalsIgnoreCase("multiPointLine")) {
                                String close = element.getAttributeValue("close");
                                stroke = element.getAttributeValue("stroke");
                                lineWidth = element.getAttributeValue("lineWidth");
                                color = element.getAttributeValue("color");
                                List<String> points = new ArrayList<String>();
                                List<Element> pointList = element.getChildren("point");
                                for (Element ePoint : pointList) {
                                    points.add(ePoint.getTextTrim());
                                }
                                StdRouteMultipointLine line = new StdRouteMultipointLine(route, mapViewAdapter,
                                        previous, points, close, stroke, lineWidth, color);
                                previous = line;
                                route.addElement(line);
                            } else if (element.getName().equalsIgnoreCase("text")) {
                                String position = element.getAttributeValue("position");
                                String angle = element.getAttributeValue("angle");
                                String alignHeading = element.getAttributeValue("alignHeading");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                boolean clickable = "true".equals(element.getAttributeValue("clickable"));
                                String sText = element.getAttributeValue("text");
                                StdRouteText text = new StdRouteText(route, mapViewAdapter, previous, position,
                                        angle, alignHeading, font, fontSize, color, clickable, sText);
                                previous = text;
                                route.addElement(text);
                            } else if (element.getName().equalsIgnoreCase("screenText")) {
                                String position = element.getAttributeValue("screenPos");
                                String angle = element.getAttributeValue("angle");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                String sText = element.getAttributeValue("text");
                                StdRouteScreenText text = new StdRouteScreenText(route, mapViewAdapter,
                                        previous, position, angle, font, fontSize, color, sText);
                                previous = text;
                                route.addElement(text);
                            } else if (element.getName().equalsIgnoreCase("minAlt")) {
                                String position = element.getAttributeValue("position");
                                String value = element.getAttributeValue("value");
                                String font = element.getAttributeValue("font");
                                String fontSize = element.getAttributeValue("fontSize");
                                color = element.getAttributeValue("color");
                                StdRouteMinAltitude minAlt = new StdRouteMinAltitude(route, mapViewAdapter,
                                        previous, position, value, font, fontSize, color);
                                previous = minAlt;
                                route.addElement(minAlt);
                            }

                        } catch (Exception e) {
                            log.error("Problem to parse file " + file.getAbsolutePath() + ", Route: "
                                    + route.getName() + ", Error:" + e.getMessage(), e);
                            break;
                        }
                    }
                    stdRoutes.add(route);
                }
            }

        } catch (Exception e) {
            log.error("Problem to parse file " + file.getAbsolutePath() + ", Error:" + e.getMessage());

        } finally {
            if (xmlInputStream != null) {
                try {
                    xmlInputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }
    data.getNavaidDB().setStdRoutes(stdRoutes);
}

From source file:de.nava.informa.parsers.FeedParser.java

License:Open Source License

/**
 * Parse feed from input source with base location set and create channel.
 *
 * @param cBuilder     specific channel builder to use.
 * @param inpSource    input source of data.
 * @param baseLocation base location of feed.
 * @return parsed channel.// ww w  . j  av  a 2 s.co m
 * @throws IOException    if IO errors occur.
 * @throws ParseException if parsing is not possible.
 */
public static ChannelIF parse(ChannelBuilderIF cBuilder, InputSource inpSource, URL baseLocation)
        throws IOException, ParseException {
    // document reading without validation
    SAXBuilder saxBuilder = new SAXBuilder();

    // turn off DTD loading
    saxBuilder.setEntityResolver(new NoOpEntityResolver());

    try {
        Document doc = saxBuilder.build(inpSource);
        ChannelIF channel = parse(cBuilder, doc);
        channel.setLocation(baseLocation);
        return channel;
    } catch (JDOMException e) {
        throw new ParseException("Problem parsing " + inpSource + ": " + e);
    }
}

From source file:de.openVJJ.basic.ProjectConf.java

License:Open Source License

public static void load(String fileName) {

    try {//from w w w  .  ja  v  a 2  s. c o  m
        Document document = new SAXBuilder().build(fileName);
        Element rootElement = document.getRootElement();
        if (rootElement.getName() != ROOT_ELEMET_NAME) {
            System.err.println("is not an Open-VJJ 2 Project");
            return;
        }
        //         Element gpuElement = rootElement.getChild(GPU_ELEMENT_NAME);
        //         if(gpuElement != null){
        //            Attribute gpuActiv = gpuElement.getAttribute(GPU_ACTIV_ATTRIBUTE_NAME);
        //            if(gpuActiv != null){
        //               useGPU = gpuActiv.getBooleanValue();
        //            }
        //         }
        Element baseModuleElement = rootElement.getChild(ELEMET_NAME_BASE_MODULE);
        baseModule = new Module();
        baseModule.setBaseModule(true);
        baseModule.setConfig(baseModuleElement);
        if (projectFrame != null) {
            projectFrame.dispose();
        }
        openFrame();
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.openVJJ.InputComponents.java

License:Open Source License

public static void load(String fileName) {
    try {//  ww  w. j ava2s  .co m
        Document document = new SAXBuilder().build(fileName);
        Element rootElement = document.getRootElement();
        if (rootElement.getName() != ROOT_ELEMET_NAME) {
            System.err.println("is notan Open-VJJ Project");
            return;
        }
        Element gpuElement = rootElement.getChild(GPU_ELEMENT_NAME);
        if (gpuElement != null) {
            Attribute gpuActiv = gpuElement.getAttribute(GPU_ACTIV_ATTRIBUTE_NAME);
            if (gpuActiv != null) {
                useGPU = gpuActiv.getBooleanValue();
            }
        }
        removeAll();
        Element components = rootElement.getChild(COMPONENTS_ELEMENT_NAME);
        List<Element> elements = components.getChildren(COMPONENT_ELEMENT_NAME);
        for (Element rootComponente : elements) {
            addComponent((ImagePublisher) loadComponent(rootComponente));
        }
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:de.qucosa.dissemination.epicur.servlet.EpicurDisseminationServlet.java

License:Apache License

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    URI metsDocumentUri;//from  w  w  w  . jav  a  2s. c  o m
    boolean transferUrlPidencode;
    String transferUrlPattern;
    String frontpageUrlPattern;
    Map<String, String> agentNameSubstitutions;
    try {
        String reqParameter = req.getParameter(REQUEST_PARAM_METS_URL);
        if (reqParameter == null || reqParameter.isEmpty()) {
            resp.sendError(SC_BAD_REQUEST, "Missing parameter '" + REQUEST_PARAM_METS_URL + "'");
            return;
        }
        metsDocumentUri = URI.create(reqParameter);

        ServletConfig config = getServletConfig();

        transferUrlPattern = getParameterValue(config, PARAM_TRANSFER_URL_PATTERN);
        frontpageUrlPattern = getParameterValue(config, PARAM_FRONTPAGE_URL_PATTERN);
        transferUrlPidencode = isParameterSet(config, PARAM_TRANSFER_URL_PIDENCODE);

        agentNameSubstitutions = decodeSubstitutions(getParameterValue(config, PARAM_AGENT_NAME_SUBSTITUTIONS));

    } catch (Exception e) {
        log.error(e.getMessage());
        resp.sendError(SC_INTERNAL_SERVER_ERROR);
        return;
    }

    try (CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet(metsDocumentUri))) {
        if (httpResponse.getStatusLine().getStatusCode() != SC_OK) {
            resp.sendError(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
            return;
        }
        Document metsDocument = new SAXBuilder().build(httpResponse.getEntity().getContent());

        EpicurBuilder epicurBuilder = new EpicurBuilder().encodePid(transferUrlPidencode)
                .agentNameSubstitutions(agentNameSubstitutions).frontpageUrlPattern(frontpageUrlPattern)
                .mets(metsDocument).transferUrlPattern(transferUrlPattern).updateStatus(UpdateStatus.urn_new);
        Epicur epicur = epicurBuilder.build();

        StringWriter stringWriter = new StringWriter();

        Marshaller marshaller = marshallerPool.borrowObject();
        marshaller.marshal(epicur, stringWriter);
        marshallerPool.returnObject(marshaller);

        resp.setCharacterEncoding(Charset.defaultCharset().name());
        resp.setContentType("application/xml");
        resp.getOutputStream().print(stringWriter.toString());

    } catch (Exception e) {
        log.error("Error while writing XML content: " + e.getMessage());
        if (!resp.isCommitted()) {
            resp.sendError(SC_INTERNAL_SERVER_ERROR);
        } else {
            log.warn("Response already committed. Cannot send error code.");
        }
    }
}

From source file:de.rallye.api.LandingPage.java

License:Open Source License

@GET
@Produces("image/png")
@Path("timetable/{groupsCode}")
public StreamingOutput getTimeTable(@PathParam("groupsCode") final String groupsCode) {

    StreamingOutput stream = new StreamingOutput() {
        @Override/*from w ww . ja  va2 s  . c om*/
        public void write(OutputStream os) throws IOException, WebApplicationException {
            try {
                Document doc = new SAXBuilder()
                        .build(StadtRallye.class.getResourceAsStream("timetable/stundenplan.xml"));
                replaceKgRooms(doc, groupsCode);
                Source xmlFile = new JDOMSource(doc);
                final JDOMResult htmlResult = new JDOMResult();
                Transformer transformer = TransformerFactory.newInstance().newTransformer(
                        new StreamSource(StadtRallye.class.getResourceAsStream("timetable/stundenplan.xsl")));
                transformer.transform(xmlFile, htmlResult);

                PipedInputStream svgIn = new PipedInputStream();
                final PipedOutputStream svgOut = new PipedOutputStream(svgIn);

                new Thread(new Runnable() {
                    public void run() {

                        XMLOutputter xmlOutputter = new XMLOutputter();
                        try {
                            xmlOutputter.output(htmlResult.getDocument(), svgOut);
                            svgOut.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                // Create a PNG transcoder
                PNGTranscoder t = new PNGTranscoder();

                // Create the transcoder input.
                //String svgURI = new File(args[0]).toURL().toString();
                TranscoderInput input = new TranscoderInput(svgIn);

                // Create the transcoder output.
                TranscoderOutput output = new TranscoderOutput(os);

                SVGConverter x;

                // Save the image.
                t.transcode(input, output);
                svgIn.close();

                // Flush and close the stream.
                os.flush();
                os.close();

            } catch (JDOMException e) {
                e.printStackTrace();
            } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (TranscoderException e) {
                e.printStackTrace();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    };
    return stream;

    //return StadtRallye.class.getResourceAsStream("timetable/stundenplan.xml");
}

From source file:de.rallye.api.LandingPage.java

License:Open Source License

@GET
@Produces("text/calendar")
@Path("timetable/{groupsCode}.ics")
@Template(name = "/calendar")
public List<Event> getCalendar(@PathParam("groupsCode") String groupsCode) throws JDOMException, IOException {
    try {/*from  w w  w. j  a v  a 2s  . c o m*/
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));

        Document doc = new SAXBuilder()
                .build(StadtRallye.class.getResourceAsStream("timetable/stundenplan.xml"));
        replaceKgRooms(doc, groupsCode);

        List<Event> result = new ArrayList<>();

        List<Element> days = doc.getRootElement().getChild("days").getChildren("day");
        for (Element day : days) {
            String dateStr = formatDate(day.getChildText("heading"));

            List<Element> events = day.getChild("events").getChildren("event");
            for (int i = 0; i < events.size(); i++) {
                Element event = events.get(i);

                if (event.getChildText("type").equals("spacer"))
                    continue;

                Time startT = Time.fromString(event.getChildText("starttime"));
                String start = startT.toString();

                Time endT = new Time(20, 200);
                if (i < events.size() - 1) {
                    Element next = events.get(i + 1);
                    String endStr = next.getChildText("starttime");
                    endT = Time.fromString(endStr);

                    endT = endT.subtractMinutes(10);
                } else {
                    float dur = Float.parseFloat(event.getChildText("duration")) * 55;
                    endT = startT.addMinutes((int) dur);
                }

                String title = event.getChildText("title");
                String titleR = title.replace("&amp;", "&");

                Event e = new Event(year + dateStr + "T" + start + "00",
                        year + dateStr + "T" + endT.toString() + "00", titleR, event.getChildText("location"));
                result.add(e);
            }
        }

        return result;
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    return null;
}