Example usage for javax.xml.parsers ParserConfigurationException printStackTrace

List of usage examples for javax.xml.parsers ParserConfigurationException printStackTrace

Introduction

In this page you can find the example usage for javax.xml.parsers ParserConfigurationException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.google.ytd.SubmitActivity.java

private String gdataUpload(File file, String uploadUrl, int start, int end) throws IOException {
    int chunk = end - start + 1;
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    FileInputStream fileStream = new FileInputStream(file);

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    // some mobile proxies do not support PUT, using X-HTTP-Method-Override to get around this problem
    if (isFirstRequest()) {
        Log.d(LOG_TAG, String.format("Uploaded %d bytes so far, using POST method.", (int) totalBytesUploaded));
        urlConnection.setRequestMethod("POST");
    } else {/*from  w w w .j a va 2 s  . c  o m*/
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("X-HTTP-Method-Override", "PUT");
        Log.d(LOG_TAG,
                String.format("Uploaded %d bytes so far, using POST with X-HTTP-Method-Override PUT method.",
                        (int) totalBytesUploaded));
    }
    urlConnection.setDoOutput(true);
    urlConnection.setFixedLengthStreamingMode(chunk);
    urlConnection.setRequestProperty("Content-Type", "video/3gpp");
    urlConnection.setRequestProperty("Content-Range",
            String.format("bytes %d-%d/%d", start, end, file.length()));
    Log.d(LOG_TAG, urlConnection.getRequestProperty("Content-Range"));

    OutputStream outStreamWriter = urlConnection.getOutputStream();

    fileStream.skip(start);

    int bytesRead;
    int totalRead = 0;
    while ((bytesRead = fileStream.read(buffer, 0, bufferSize)) != -1) {
        outStreamWriter.write(buffer, 0, bytesRead);
        totalRead += bytesRead;
        this.totalBytesUploaded += bytesRead;

        double percent = (totalBytesUploaded / currentFileSize) * 99;

        /*
        Log.d(LOG_TAG, String.format(
        "fileSize=%f totalBytesUploaded=%f percent=%f", currentFileSize,
        totalBytesUploaded, percent));
        */

        dialog.setProgress((int) percent);

        if (totalRead == (end - start + 1)) {
            break;
        }
    }

    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();

    Log.d(LOG_TAG, "responseCode=" + responseCode);
    Log.d(LOG_TAG, "responseMessage=" + urlConnection.getResponseMessage());

    try {
        if (responseCode == 201) {
            String videoId = parseVideoId(urlConnection.getInputStream());

            String latLng = null;
            if (this.videoLocation != null) {
                latLng = String.format("lat=%f lng=%f", this.videoLocation.getLatitude(),
                        this.videoLocation.getLongitude());
            }

            submitToYtdDomain(this.ytdDomain, this.assignmentId, videoId, this.youTubeName,
                    SubmitActivity.this.clientLoginToken, getTitleText(), getDescriptionText(), this.dateTaken,
                    latLng, this.tags);
            dialog.setProgress(100);
            return videoId;
        } else if (responseCode == 200) {
            Set<String> keySet = urlConnection.getHeaderFields().keySet();
            String keys = urlConnection.getHeaderFields().keySet().toString();
            Log.d(LOG_TAG, String.format("Headers keys %s.", keys));
            for (String key : keySet) {
                Log.d(LOG_TAG,
                        String.format("Header key %s value %s.", key, urlConnection.getHeaderField(key)));
            }
            Log.w(LOG_TAG, "Received 200 response during resumable uploading");
            throw new IOException(String.format("Unexpected response code : responseCode=%d responseMessage=%s",
                    responseCode, urlConnection.getResponseMessage()));
        } else {
            if ((responseCode + "").startsWith("5")) {
                String error = String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage());
                Log.w(LOG_TAG, error);
                // TODO - this exception will trigger retry mechanism to kick in
                // TODO - even though it should not, consider introducing a new type so
                // TODO - resume does not kick in upon 5xx
                throw new IOException(error);
            } else if (responseCode == 308) {
                // OK, the chunk completed succesfully 
                Log.d(LOG_TAG, String.format("responseCode=%d responseMessage=%s", responseCode,
                        urlConnection.getResponseMessage()));
            } else {
                // TODO - this case is not handled properly yet
                Log.w(LOG_TAG, String.format("Unexpected return code : %d %s while uploading :%s", responseCode,
                        urlConnection.getResponseMessage(), uploadUrl));
            }
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java

private NodeList identifyMessageType(String message) {
    DocumentBuilder db = null;/* w  w  w  .  j a v  a 2 s .  c  o  m*/
    try {
        db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(message));

    org.w3c.dom.Document doc = null;
    try {
        doc = db.parse(is);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    NodeList nodeList = doc.getElementsByTagName("transition");
    return nodeList;
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

private void loadEarthquakeData() {
    String URL = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_week_age.kml";
    String content = "";
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet httpGet = new HttpGet(URL);
    List<QuakeData> quakes = null;
    try {/*ww  w .  j a  v a2  s  .  c om*/
        HttpResponse res = httpClient.execute(httpGet);

        quakes = new ArrayList<QuakeData>();
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        dBuilder = dbFactory.newDocumentBuilder();
        Document dom = dBuilder.parse(res.getEntity().getContent());
        Element doc = dom.getDocumentElement();
        NodeList elems = doc.getElementsByTagName("Placemark");
        for (int i = 0; i < elems.getLength(); i++) {
            Element elem = (Element) elems.item(i);
            // Collect the data from the XML text
            String name = getElementTextValue(elem, "name");
            String description = getElementTextValue(elem, "description");
            Element lookAtElement = (Element) elem.getElementsByTagName("LookAt").item(0);
            String latitude = getElementTextValue(lookAtElement, "latitude");
            String longitude = getElementTextValue(lookAtElement, "longitude");
            Element iconStyleElement = (Element) elem.getElementsByTagName("IconStyle").item(0);
            String colorPlusAlpha = getElementTextValue(iconStyleElement, "color");
            String color = colorPlusAlpha.substring(2);

            QuakeData quakeData = new QuakeData();
            quakeData.setName(name);
            quakeData.setSummary(description);
            quakeData.setLat(Double.valueOf(latitude));
            quakeData.setLon(Double.valueOf(longitude));
            quakeData.setColor(color);
            quakeData.setMagnitude(Float.parseFloat(name.substring(2, name.indexOf(" ", 2))));

            quakes.add(quakeData);
        }
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    this.quakes = quakes;
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapterInbound.java

public CoTAdapterInbound(AdapterDefinition adapterDefinition, String guid)
        throws ConfigurationException, ComponentException {
    super(adapterDefinition);

    this.guid = guid;

    messageParser = new MessageParser(this);
    saxFactory = SAXParserFactory.newInstance();
    try {/*from   w  w w .  j  a  va 2 s. c  o  m*/
        saxParser = saxFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        saxParser = null;
        log.error(e);
        log.error(e.getStackTrace());

    } catch (SAXException e) {
        e.printStackTrace();
        saxParser = null;
        log.error(e);
        log.error(e.getStackTrace());
    }

}

From source file:org.opencastproject.analytics.impl.AnalyticsServiceImpl.java

/**
 * Gets the number of times an episode was watched and for how long in
 * intervals over a time range./* ww  w .ja  va 2  s .c o m*/
 * 
 * @param id
 *            The unique id of the episode to get the statistics for.
 * @param start
 *            The start of the period to investigate in the form
 *            YYYYMMDDHHMM e.g. 201212312359.
 * @param end
 *            The end of the period to investigate in the form YYYYMMDDHHMM
 *            e.g. 201212312359.
 * @param intervalString
 *            The number of seconds to break up the views and durations into
 *            from start time to end time.
 * @return An xml representation of all of these intervals between start and
 *         end.
 * @throws TrustedHttpClientException
 *             Thrown if rest calls cannot be made. Thrown if it cannot
 *             query a rest endpoint.
 */
public ViewCollection getViews(String id, String start, String end, String intervalString)
        throws TrustedHttpClientException {
    if (canAnalyzeEpisode(id)) {

        long limit = DEFAULT_LIMIT;
        long interval = Long.parseLong(intervalString);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        Date startDate = new Date();
        Date endDate = new Date();
        try {
            startDate = dateFormat.parse(start);
            endDate = dateFormat.parse(end);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        ViewCollection viewCollection = new ViewCollection();
        viewCollection.setLimit(limit);
        viewCollection.setFrom(startDate);
        viewCollection.setTo(endDate);
        viewCollection.setInterval(interval);

        long intervalCount = 0;
        Date intervalStart;
        Date intervalEnd;
        HttpGet getInterval;
        HttpResponse response;
        Boolean foundViews = false;

        do {
            foundViews = false;
            // Get the start and end of the interval
            intervalStart = new Date(startDate.getTime() + interval * secondsToMilliseconds * intervalCount);
            intervalEnd = new Date(
                    startDate.getTime() + interval * secondsToMilliseconds * (intervalCount + 1));
            String uri = UrlSupport.concat(engageURL, "/usertracking/report.xml");
            uri += "?from=" + dateFormat.format(intervalStart);
            uri += "&to=" + dateFormat.format(intervalEnd);
            uri += "&limit=" + limit;
            getInterval = new HttpGet(uri);
            response = client.execute(getInterval);

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder;
            try {
                dBuilder = dbFactory.newDocumentBuilder();
                Document document = dBuilder.parse(response.getEntity().getContent());
                document.getDocumentElement().normalize();
                NodeList reports = document.getChildNodes();
                ViewItem viewItem = new ViewItem();
                for (int i = 0; i < reports.getLength(); i++) {
                    Node report = reports.item(i);
                    NodeList reportItems = report.getChildNodes();
                    for (int j = 0; j < reportItems.getLength(); j++) {
                        Node reportItem = reportItems.item(j);
                        if (reportItem.getNodeType() == Node.ELEMENT_NODE) {
                            Element eElement = (Element) reportItem;
                            String tagID = getTagValue(EPISODE_ID_TAG_NAME, eElement);
                            if (id.equals(tagID)) {
                                viewItem.setId(getTagValue(EPISODE_ID_TAG_NAME, eElement));
                                viewItem.setViews(getTagValue(VIEWS_XML_TAG, eElement));
                                viewItem.setPlayed(getTagValue(PLAYED_XML_TAG, eElement));
                                viewItem.setStart(dateFormat.format(intervalStart));
                                viewItem.setEnd(dateFormat.format(intervalEnd));
                                viewCollection.add(viewItem);
                                viewCollection.setViews(viewCollection.getViews()
                                        + Integer.parseInt(getTagValue(VIEWS_XML_TAG, eElement)));
                                viewCollection.setPlayed(viewCollection.getPlayed()
                                        + Integer.parseInt(getTagValue(PLAYED_XML_TAG, eElement)));
                                viewCollection.setTotal(viewCollection.getTotal() + 1);
                                foundViews = true;
                            }

                        }
                    }
                }
                // Handle the case where there is no data for this episode during this interval. 
                if (!foundViews) {
                    viewItem.setId(id);
                    viewItem.setViews("0");
                    viewItem.setPlayed("0");
                    viewItem.setStart(dateFormat.format(intervalStart));
                    viewItem.setEnd(dateFormat.format(intervalEnd));
                    viewCollection.add(viewItem);
                }
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e1) {
                e1.printStackTrace();
            }
            intervalCount++;
        } while (intervalStart.before(endDate) && intervalEnd.before(endDate));
        return viewCollection;
    } else {
        return new ViewCollection();
    }
}

From source file:org.gege.caldavsyncadapter.caldav.entities.CalendarEvent.java

public boolean setICSasMultiStatus(String stringMultiStatus) {
    boolean Result = false;
    String ics = "";
    MultiStatus multistatus;/*www . j  a  va 2 s.  c o m*/
    ArrayList<Response> responselist;
    Response response;
    PropStat propstat;
    Prop prop;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        MultiStatusHandler contentHandler = new MultiStatusHandler();
        reader.setContentHandler(contentHandler);
        reader.parse(new InputSource(new StringReader(stringMultiStatus)));

        multistatus = contentHandler.mMultiStatus;
        if (multistatus != null) {
            responselist = multistatus.ResponseList;
            if (responselist.size() == 1) {
                response = responselist.get(0);
                //HINT: bugfix for google calendar
                if (response.href.equals(this.getUri().getPath().replace("@", "%40"))) {
                    propstat = response.propstat;
                    if (propstat.status.contains("200 OK")) {
                        prop = propstat.prop;
                        ics = prop.calendardata;
                        this.setETag(prop.getetag);
                        Result = true;
                    }
                }
            }
        }
    } catch (ParserConfigurationException e1) {
        e1.printStackTrace();
    } catch (SAXException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.stringIcs = ics;
    return Result;
}

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

/**
 * @param condition//from  w w w  . j a  v  a2s  . c  o m
 * @param formId
 * @return
 */
public FormConfigElement getNodeTypeConfigForm(String condition, String formId) {
    String formIdXpath = (formId.equals("default")) ? "not(@id)" : "@id='" + formId + "'";
    Element formElem = XmlUtils.findFirstElement(
            "config[@evaluator='node-type' and @condition='" + condition + "']/forms/form[" + formIdXpath + "]",
            (Element) configDocument.getFirstChild());
    if (formElem != null) {
        FormElementReader formElementReader = new FormElementReader();
        try {
            return (FormConfigElement) formElementReader.parse(convert(formElem));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

/**
 * @param condition//from ww  w. java  2 s.c o m
 * @param formId
 * @return
 */
public FormConfigElement getAspectConfigForm(String condition, String formId) {
    String formIdXpath = (formId.equals("default")) ? "not(@id)" : "@id='" + formId + "'";
    Element formElem = XmlUtils.findFirstElement(
            "config[@evaluator='aspect' and @condition='" + condition + "']/forms/form[" + formIdXpath + "]",
            (Element) configDocument.getFirstChild());
    if (formElem != null) {
        FormElementReader formElementReader = new FormElementReader();
        try {
            return (FormConfigElement) formElementReader.parse(convert(formElem));
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        }
    } else {
        return null;
    }
}

From source file:mk.finki.ranggo.aggregator.ContentsAggregatorImpl.java

public void aggregateTest() throws ContentsAggregatorException {
    final int CONTENT_COUNT = 20;

    String[] articles = new String[CONTENT_COUNT];
    String[] titles = new String[CONTENT_COUNT];
    String[] timestamps = new String[CONTENT_COUNT];

    int counter = 0;

    //populating content information

    articles[counter] = "http://nymag.com/daily/intelligencer/2015/09/frank-rich-in-praise-of-donald-trump.html";
    titles[counter] = "The Importance of Donald Trump";
    timestamps[counter] = "Sun, 20 Sep 2015 21:00:00 GMT";
    counter++;/*from   w w  w  .  j  av  a  2s.c  om*/

    articles[counter] = "https://www.washingtonpost.com/opinions/what-americans-think-should-be-done-on-illegal-immigration/2015/10/11/4f6f6df6-6ed7-11e5-9bfe-e59f5e244f92_story.html";
    titles[counter] = "What Americans think should be done on illegal immigration";
    timestamps[counter] = "Sun, 11 Oct 2015 00:00:00 GMT";
    counter++;

    articles[counter] = "http://thinkprogress.org/politics/2015/11/22/3724879/donald-trump-black-lives-matter-protester-beating/";
    titles[counter] = "Donald Trump: My Fans Were Right To Beat Up Black Protester";
    timestamps[counter] = "Sun, 22 Nov 2015 09:30:00 GMT";
    counter++;

    articles[counter] = "http://edition.cnn.com/2015/12/11/politics/donald-trump-ted-cruz-iowa-ethanol/";
    titles[counter] = "Donald Trump launches first attacks against Ted Cruz";
    timestamps[counter] = "Fri, 11 Dec 2015 00:00:00 GMT";
    counter++;

    articles[counter] = "http://edition.cnn.com/2015/12/18/politics/donald-trump-praises-defends-vladimir-putin/";
    titles[counter] = "Donald Trump lavishes praise on 'leader' Putin";
    timestamps[counter] = "Fri, 18 Dec 2015 15:19:00 GMT";
    counter++;

    articles[counter] = "http://www.cbsnews.com/news/donald-trump-compares-bill-clinton-to-bill-cosby/";
    titles[counter] = "Donald Trump compares Bill Clinton to Bill Cosby";
    timestamps[counter] = "Wed, 06 Jan 2016 08:56:00 GMT";
    counter++;

    articles[counter] = "http://www.sbnation.com/lookit/2016/1/28/10858584/australian-open-video-roger-federer-novak-djokovic-point";
    titles[counter] = "Roger Federer wins mind-boggling point against Novak Djokovic in ridiculous rally";
    timestamps[counter] = "Thu, 28 Jan 2016 09:47:00 GMT";
    counter++;

    articles[counter] = "http://www.theguardian.com/sport/2016/jan/31/novak-djokovic-andy-murray-australian-open-final";
    titles[counter] = "Novak Djokovic beats Andy Murray to win the 2016 Australian Open final";
    timestamps[counter] = "Sun, 31 Jan 2016 11:37:00 GMT";
    counter++;

    articles[counter] = "https://www.washingtonpost.com/politics/a-sigh-of-relief-in-swinging-northern-virginia-when-trump-fell-short-in-iowa/2016/02/02/1f48fb36-c9d3-11e5-a7b2-5a2f824b02c9_story.html";
    titles[counter] = "A sigh of relief in Northern Virginia as Trump falls short in Iowa";
    timestamps[counter] = "Tue, 2 Feb 2016 00:00:00 GMT";
    counter++;

    articles[counter] = "http://www.ibtimes.com/angelina-jolie-brad-pitt-divorce-angie-insanely-jealous-over-selena-gomez-cheating-2312126";
    titles[counter] = "Angelina Jolie And Brad Pitt To Divorce? Angie Is 'Insanely Jealous' Over Selena Gomez Cheating Rumors: Report";
    timestamps[counter] = "Wed, 17 Feb 2016 13:07:00 GMT";
    counter++;

    articles[counter] = "http://www.nytimes.com/2016/02/24/us/politics/nevada-caucus-gop.html";
    titles[counter] = "Donald Trump Wins Nevada Caucuses, Collecting Third Straight Victory";
    timestamps[counter] = "Tue, 23 Feb 2016 00:00:00 GMT";
    counter++;

    articles[counter] = "http://www.nytimes.com/politics/first-draft/2016/03/16/donald-trump-warns-of-riots-if-party-blocks-him-at-convention/";
    titles[counter] = "Donald Trump Warns of 'Riots' if Party Blocks Him at Convention";
    timestamps[counter] = "Wed, 16 Mar 2016 15:15:00 GMT";
    counter++;

    articles[counter] = "https://www.washingtonpost.com/blogs/post-partisan/wp/2016/03/23/ted-cruzs-harebrained-harmful-policy-towards-american-muslims/";
    titles[counter] = "Ted Cruz's harebrained, harmful policy toward American Muslims";
    timestamps[counter] = "Wed, 23 Mar 2016 00:00:00 GMT";
    counter++;

    articles[counter] = "http://espn.go.com/tennis/story/_/id/15079824/miami-open-rafael-nadal-roger-federer-host-questions-answer";
    titles[counter] = "Rafael Nadal, Roger Federer among top stars with questions to answer";
    timestamps[counter] = "Mon, 28 Mar 2016 00:00:00 GMT";
    counter++;

    articles[counter] = "http://www.houstonchronicle.com/sports/article/Feliciano-Lopez-glad-he-plays-in-tennis-era-of-7235565.php";
    titles[counter] = "Feliciano Lopez glad he plays in tennis era of Novak Djokovic & Co.";
    timestamps[counter] = "Thu, 07 Apr 2016 00:00:00 GMT";
    counter++;

    articles[counter] = "http://www.vanityfair.com/hollywood/2016/04/brad-pitt-and-angelina-jolie-london-mansion";
    titles[counter] = "Brad Pitt and Angelina Jolie's $21,000/Month London Mansion Is an Inspiration to All Business Travelers";
    timestamps[counter] = "Fri, 22 Apr 2016 10:38:00 GMT";
    counter++;

    articles[counter] = "https://www.washingtonpost.com/news/the-fix/wp/2016/04/26/how-donald-trump-is-dominating-the-i-95-primary/";
    titles[counter] = "How Donald Trump dominated Tuesday's primaries";
    timestamps[counter] = "Tue, 26 Apr 2016 00:00:00 GMT";
    counter++;

    articles[counter] = "http://www.inquisitr.com/3042986/johnny-depp-was-under-medical-care-after-filming/";
    titles[counter] = "Johnny Depp Was Under Medical Care After Filming";
    timestamps[counter] = "Thu, 28 Apr 2016 00:00:00 GMT";
    counter++;

    articles[counter] = "https://www.washingtonpost.com/news/the-fix/wp/2016/04/29/the-gop-is-running-on-empty-so-why-are-people-debating-whether-to-stop-for-gas/";
    titles[counter] = "Mitt Romney's chief strategist says Donald Trump is 'uniquely unqualified' to be president";
    timestamps[counter] = "Fri, 29 Apr 2016 09:53:00 GMT";
    counter++;

    articles[counter] = "http://www.mirror.co.uk/3am/celebrity-news/kirk-norcross-gets-arrested-dangerous-7864035";
    titles[counter] = "Kirk Norcross 'gets ARRESTED for dangerous driving' hours after Snapchatting behind the wheel";
    timestamps[counter] = "Fri, 29 Apr 2016 17:43:00 GMT";
    counter++; //= CONTENT_COUNT

    //end populating content information

    for (int i = 0; i < CONTENT_COUNT; i++) {
        try {
            System.out.println("Pred da procesira");
            this.processStatic(articles[i], titles[i], timestamps[i]);
        } catch (ParserConfigurationException exception) {
            exception.printStackTrace();
        } //these exceptions should be logged - only a single link fails  
        catch (SAXException exception) {
            exception.printStackTrace();
        } catch (XPathExpressionException exception) {
            exception.printStackTrace();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

From source file:cl.utfsm.cdbChecker.CDBChecker.java

/******************************************************************
 * This method finds files in "Components" and "Containers" 
 * directories and sub-directories. It then extracts "implLang" 
 * properties, and compares. Error messages are displayed if
 * Components.xml's implLang and Containers.xml's implLang
 * don't match./*from   w ww .  ja v  a2s . c o  m*/
 * Returns 'true' if error is found, false otherwise
 * added by panta@naoj 2009/10/05 
 *****************************************************************/
protected boolean checkImplLangMatch(File compFolder, File contFolder) {

    File[] files = compFolder.listFiles();

    search: for (int x = 0; x < files.length; x++) {

        if (foundErr) {
            break search;
        }

        if (files[x].isDirectory()) {
            if (!files[x].getName().equals("CVS")) {
                checkImplLangMatch(files[x], contFolder); //recursive call
            }
        } else {
            //only process .xml files
            String ext = "";

            int iExt = files[x].getName().lastIndexOf(".");
            ext = files[x].getName().substring(iExt + 1, files[x].getName().length());

            if (!ext.equals("xml")) {
                continue;
            }
            //System.out.println("\nChecking.. " + files[x]);
            DocumentBuilderFactory dbfComp = DocumentBuilderFactory.newInstance();
            DocumentBuilder dbComp = null;
            try {
                dbComp = dbfComp.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
            Document docComp = null;
            try {
                docComp = dbComp.parse(files[x]);
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            docComp.getDocumentElement().normalize();
            NodeList compNodeList = docComp.getElementsByTagName("Component");

            //modify bhola.panta@naoj 2010-03-15
            if (compNodeList.getLength() == 1) { //only the variant where a single component is configured in its own file
                String compName = ((Element) compNodeList.item(0)).getAttribute("Name");
                //add bhola.panta@naoj 2010-03-03
                //fileName and "Name" property must match
                if (!compName.equals("*") && !files[x].getName().equals("Components.xml")) {
                    //must support hierarchical component names (separated by "/") 
                    if (!checkHierarchical(files[x], compName)) {
                        if (!(compName + ".xml").equals(files[x].getName())) {
                            System.out.print("\nMismatch between component name and XML file name.");
                            System.out.print("\nComponent File: " + files[x]);
                            System.out.print("\nComponent name: '" + compName + "'");
                            System.out.print("\nFile name: '" + files[x].getName() + "'");
                            foundErr = true;
                            break search;
                        }
                    }
                }
            }

            if (compNodeList.getLength() == 0) {
                compNodeList = docComp.getElementsByTagName("_");
                if (compNodeList.getLength() == 0) {
                    continue;
                }
            }

            //this part extracts "implLang" for each component
            for (int j = 0; j < compNodeList.getLength(); j++) {

                Element elm = (Element) compNodeList.item(j);
                String compName = null;
                String implLang = null;
                String tempContainersFolder = null;

                compName = elm.getAttribute("Name");
                implLang = elm.getAttribute("ImplLang");
                //System.out.println("\ncompName being checked: " + compName );

                if (compName.equals("*")) { //--> dynamic component
                    if (implLang.equals("") || implLang.equals("*")) {
                        continue;
                    }
                    //some dynamic components may not have predefined Containers
                    if (elm.getAttribute("Container").equals("") || elm.getAttribute("Container").equals("*")) {
                        continue;
                    }
                }
                //add bhola.panta@naoj 2011/07/21
                //component does have a name, but container is dynamic (?), that is, "*"
                else if (elm.getAttribute("Container").equals("*")) {
                    continue;
                } else {//actually, ImpLang field in the CDB is mandatory since ACS 8
                    if (implLang.equals("")) {
                        System.out.println("\nFile being checked: " + files[x]);
                        System.out.print("\n'ImplLang' missing for component: " + compName);
                        foundErr = true;
                        break search;
                    }
                }

                //go get containers at the "Container" location
                tempContainersFolder = containersFolder + File.separator + elm.getAttribute("Container");

                //open the container file and have a look
                DocumentBuilderFactory dbfCont = DocumentBuilderFactory.newInstance();
                DocumentBuilder dbCont = null;
                try {
                    dbCont = dbfCont.newDocumentBuilder();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                }
                Document docCont = null;
                try {
                    //System.out.println("\ntempContainersFolder " + tempContainersFolder);
                    File contFile = new File(tempContainersFolder + File.separator
                            + new File(tempContainersFolder).getName() + ".xml");
                    //System.out.println("\ncontainerFile " + contFile);
                    if (contFile.exists()) {
                        docCont = dbCont.parse(contFile);

                        docCont.getDocumentElement().normalize();

                        NodeList contNodeList = docCont.getElementsByTagName("Container");

                        //Go through Container files and check ImplLang
                        for (int k = 0; k < contNodeList.getLength(); k++) {
                            Element elmCont = (Element) contNodeList.item(k);
                            //check if Component ImplLang and Container ImplLang match
                            if (implLang.equals(elmCont.getAttribute("ImplLang"))) {
                            } else {
                                System.out.println("\nComponent File being checked: " + files[x]);
                                System.out.println("Container File being checked: " + contFile);
                                System.out
                                        .println("'ImplLang' does not match for component: " + compName + ".");
                                foundErr = true;
                                break search;
                            }
                        } //Container for loop
                    } else {
                        System.out.print("\nComponent File being checked: " + files[x]);
                        System.out.print("\nMissing Container " + new File(tempContainersFolder));
                        System.out.println("");
                        foundErr = true;
                        break search;
                    }
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } //Component for loop
        } //is a file (not dir)
    } //all files for loop

    return foundErr;
}