Example usage for javax.xml.parsers SAXParserFactory newInstance

List of usage examples for javax.xml.parsers SAXParserFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newInstance.

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:de.tudarmstadt.ukp.dkpro.core.io.ancora.AncoraReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {
    Resource res = nextFile();/*from  w  w w.j a va2  s  . c  o  m*/
    initCas(aJCas, res);

    // Set up language
    if (getLanguage() != null) {
        aJCas.setDocumentLanguage(getLanguage());
    }

    // Configure mapping only now, because now the language is set in the CAS
    try {
        posMappingProvider.configure(aJCas.getCas());
    } catch (AnalysisEngineProcessException e1) {
        throw new IOException(e1);
    }

    InputStream is = null;
    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());

        // Create handler
        AncoraHandler handler = new AncoraHandler();
        handler.setJCas(aJCas);
        handler.setLogger(getLogger());

        // Parse XML
        SAXParserFactory pf = SAXParserFactory.newInstance();
        SAXParser parser = pf.newSAXParser();

        InputSource source = new InputSource(is);
        source.setPublicId(res.getLocation());
        source.setSystemId(res.getLocation());
        parser.parse(source, handler);
    } catch (ParserConfigurationException | SAXException e) {
        throw new IOException(e);
    } finally {
        closeQuietly(is);
    }

    if (dropSentencesMissingPosTags) {
        List<FeatureStructure> toRemove = new ArrayList<>();

        // Remove sentences without pos TAGs
        for (Sentence s : select(aJCas, Sentence.class)) {
            boolean remove = false;
            for (Token t : selectCovered(Token.class, s)) {
                if (t.getPos() == null) {
                    toRemove.add(s);
                    remove = true;
                    break;
                }
            }

            if (remove) {
                for (Token t : selectCovered(Token.class, s)) {
                    toRemove.add(t);
                    if (t.getLemma() != null) {
                        toRemove.add(t.getLemma());
                    }
                    if (t.getPos() != null) {
                        toRemove.add(t.getPos());
                    }
                }
            }
        }

        for (FeatureStructure fs : toRemove) {
            aJCas.getCas().removeFsFromIndexes(fs);
        }

        // Remove tokens without pos tags that are located *BETWEEN* sentences!
        toRemove.clear();
        for (Token t : select(aJCas, Token.class)) {
            if (t.getPos() == null) {
                toRemove.add(t);
                if (t.getLemma() != null) {
                    toRemove.add(t.getLemma());
                }
                if (t.getPos() != null) {
                    toRemove.add(t.getPos());
                }
            }
        }

        for (FeatureStructure fs : toRemove) {
            aJCas.getCas().removeFsFromIndexes(fs);
        }
    }
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*********************************
 * //from  www.  java 2s .c o  m
 * Get AlbumArt
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getAlbumArt() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Album Cursor
     */
    albumCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ALBUM_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String albumName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLAlbumArtHandler xmlHandler = new XMLAlbumArtHandler();
    //        XMLGoogleAlbumArtHandler xmlGoogleHandler = new XMLGoogleAlbumArtHandler();

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Looking for missing art...");
    msg.setData(data);
    ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

    /*
     * Loop through the albums
     */
    albumCursor.moveToFirst();
    for (int i = 0; i < albumCursor.getCount(); i++) {
        System.gc();
        /*
         * Get Album Details
         */
        artistName = albumCursor.getString(albumCursor.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
        albumName = albumCursor.getString(albumCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM));

        /*
         * If no Art is available fetch it
         */
        if (getAlbumArtPath(artistName, albumName) == null) {
            Log.i("LastFM", "Album with no Art " + albumName);
            try {
                if ((artistName.equals("<unknown>") && albumName.equals("<unknown>"))) {
                    Log.i("ALBUMART", "Unknown album");
                    albumCursor.moveToNext();
                    continue;
                }
            } catch (Exception e) {
                Log.i("ALBUMART", "Null album or artist");
                albumCursor.moveToNext();
                continue;
            }

            /*
             * Give feedback to the user
             */
            data = new Bundle();
            msg = new Message();
            data.putString("info", albumName);
            msg.setData(data);
            ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

            String albumArtURL = null;
            try {
                /*
                 * Get album URL from Last.FM
                 */
                String artistNameFiltered = filterString(artistName);
                String albumNameFiltered = filterString(albumName);

                if (USE_GOOGLE_IMAGES) {
                    //                    xmlReader.setContentHandler(xmlGoogleHandler);

                    URL googleImagesRequest = new URL(
                            this.GOOGLE_IMAGES_SEARCH_URL + URLEncoder.encode(artistNameFiltered) + "+"
                                    + URLEncoder.encode(albumNameFiltered));
                    //                    Log.i("GOOGLEIMAGES", googleImagesRequest.toString());

                    //                    DefaultHttpClientConnection httpCon = createGoogleImageConnection(
                    //                          googleImagesRequest.toString());
                    /*
                     * retreive URL
                     */
                    BasicHttpParams params = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(params, 10000);
                    DefaultHttpClient httpClient = new DefaultHttpClient();

                    // Get cookies from the login page (not the address same of the form post)
                    HttpGet httpGet = new HttpGet(googleImagesRequest.toString());

                    HttpResponse response;

                    try {
                        /*
                         * Get the page
                         */
                        response = httpClient.execute(httpGet);
                        HttpEntity entity = response.getEntity();
                        BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));

                        /*
                         * Parse 1st existing image on the result page
                         */
                        String line;
                        int idxStart = 0;
                        int idxStop;
                        do {
                            line = in.readLine();
                            if (line != null) {
                                //                           Log.i("GIMAGES", line);
                                if (line.startsWith("<table")) {
                                    boolean found = false;
                                    int tries = 0;
                                    while (!found) {
                                        tries++;
                                        if (tries > 12)
                                            break;
                                        idxStart = line.indexOf("<a href=", idxStart);

                                        if (idxStart == -1) {
                                            line = in.readLine();
                                            if (line == null)
                                                break;
                                            continue;
                                        }

                                        idxStart = line.indexOf("http://", idxStart);
                                        idxStop = line.indexOf("&imgrefurl=", idxStart);
                                        albumArtURL = line.substring(idxStart, idxStop);
                                        Log.i("GIMAGE", line.substring(idxStart, idxStop));

                                        try {
                                            //URL albumArt = new URL(URLEncoder.encode(albumArtURL));
                                            //                                    URL albumArt = new URL(albumArtURL);
                                            //                                    InputStream albumArtURLStream = albumArt.openStream();
                                            //                                    albumArtURLStream.close();
                                            if (albumArtURL != null) {
                                                if (createAlbumArt(artistName, albumName,
                                                        albumArtURL) == null) {
                                                    albumArtURL = null;
                                                    found = false;
                                                    Log.i("GIMAGES", "createAlbumArt FAIL");
                                                } else {
                                                    found = true;
                                                    Log.i("GIMAGES", "createAlbumArt WIN");
                                                }
                                            } else {
                                                albumArtURL = null;
                                                found = false;
                                                Log.i("GIMAGES", "albumArt URL FAIL!");
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                            albumArtURL = null;
                                            found = false;
                                        }
                                    }
                                    break;
                                }
                            }
                        } while (line != null);

                        //                     xmlReader.parse(new InputSource(in));

                        entity.consumeContent();

                        //                     for(int j = 0; j < xmlGoogleHandler.MAX_IMAGES; j++){
                        //                        if(xmlGoogleHandler.albumArtUrl[j] != null){
                        //                           albumArtURL = xmlGoogleHandler.albumArtUrl[j];
                        //                           break;
                        //                        }
                        //                     }

                        /*
                         * No luck with the duck
                         */
                        //                     if(albumArtURL == null){
                        //                        Log.i("GOOGLEIMAGES", "Absolutely no luck");
                        //                        // mark this as a problematic album... 
                        //                        // so we dont refetch it all the time
                        //                         createSmallAlbumArt(artistName, albumName, false);
                        //                        albumCursor.moveToNext();
                        //                        continue;
                        //                     } else {
                        //                        Log.i("GOOGLEIMAGES", albumArtURL);
                        //                     }

                        /*
                         * Clear up the Handler
                         */
                        //                     xmlGoogleHandler.clear();

                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //                  
                    //                  /*
                    //                  * No Album Art available
                    //                  *  1. try going by the album name
                    //                  *  2. get some artist pic and thats it
                    //                  */
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Could not get album art immediately");
                    //                  Log.i("LASTFM", "Trying sole album search");
                    //                  
                    //                  albumArtURL = getAlbumArtByAlbumName(albumName, artistName);
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Trying to get artist Art");
                    //                  albumArtURL = getArtistArt(artistName);
                    //                  }
                    //                  /*
                    //                  * No luck with the duck
                    //                  */
                    //                  if(albumArtURL == null){
                    //                  Log.i("LASTFM", "Absolutely no luck");
                    //                  // mark this as a problematic album... 
                    //                  // so we dont refetch it all the time
                    //                  createSmallAlbumArt(artistName, albumName, false);
                    //                  albumCursor.moveToNext();
                    //                  continue;
                    //                  }
                    //                  }
                }

                /*
                 * If google images failed try last.fm
                 */
                if (albumArtURL == null) {
                    xmlReader.setContentHandler(xmlHandler);

                    URL lastFmApiRequest = new URL(
                            this.LAST_FM_ALBUM_GETINFO_URL + "&artist=" + URLEncoder.encode(artistNameFiltered)
                                    + "&album=" + URLEncoder.encode(albumNameFiltered));
                    try {
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(lastFmApiRequest.openStream()));
                        xmlReader.parse(new InputSource(in));

                        if (xmlHandler.xlargeAlbumArt != null) {
                            albumArtURL = xmlHandler.xlargeAlbumArt;
                        } else if (xmlHandler.largeAlbumArt != null) {
                            albumArtURL = xmlHandler.largeAlbumArt;
                        } else if (xmlHandler.mediumAlbumArt != null) {
                            albumArtURL = xmlHandler.mediumAlbumArt;
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    /*
                     * No Album Art available
                     *  1. try going by the album name
                     *  2. get some artist pic and thats it
                     */
                    if (albumArtURL == null) {
                        Log.i("LASTFM", "Could not get album art immediately");
                        Log.i("LASTFM", "Trying sole album search");

                        albumArtURL = getAlbumArtByAlbumName(albumName, artistName);
                        if (albumArtURL == null) {
                            Log.i("LASTFM", "Trying to get artist Art");
                            albumArtURL = getArtistArt(artistName);
                        }
                        /*
                         * No luck with the duck
                         */
                        if (albumArtURL == null) {
                            Log.i("LASTFM", "Absolutely no luck");
                            // mark this as a problematic album... 
                            // so we dont refetch it all the time
                            createSmallAlbumArt(artistName, albumName, false);
                            albumCursor.moveToNext();
                            continue;
                        }
                    }

                    /* only reaches here if not FAIL */
                    createAlbumArt(artistName, albumName, albumArtURL);

                }

                /*
                 * reset xml handler
                 */
                xmlHandler.smallAlbumArt = null;
                xmlHandler.mediumAlbumArt = null;
                xmlHandler.largeAlbumArt = null;
                xmlHandler.xlargeAlbumArt = null;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
        /*
         * Create small album art
         */
        createSmallAlbumArt(artistName, albumName, true);

        /*
        * Give feedback to the user
        */
        //Bundle data = new Bundle();
        //Message msg = new Message();
        //data.putString("info", "Creating Thumbnail");
        //msg.setData(data);
        //((Filex) context).getAlbumArtHandler.sendMessage(msg);

        albumCursor.moveToNext();
    }

    /*
     * Give feedback to the user
     */
    data = new Bundle();
    msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).getAlbumArtHandler.sendMessage(msg);

    /*
     * Set the last import date on preferences
     */
    //        SharedPreferences settings = ((Filex) this.context).getSharedPreferences(((Filex) this.context).PREFS_NAME, 0);
    //        Editor editor = settings.edit();
    //        editor.putLong("artImportDate", System.currentTimeMillis());
    //        editor.commit();
    RockOnPreferenceManager settings = new RockOnPreferenceManager(
            ((RockPlayer) context).FILEX_PREFERENCES_PATH);
    settings.putLong("artImportDate", System.currentTimeMillis());

    //settings.
    //   long lastAlbumArtImportDate = settings.getLong("artImportDate", 0);
}

From source file:com.xmobileapp.rockplayer.LastFmEventImporter.java

/*********************************
 * //from  w  ww .j  ava  2  s. c o m
 * Get Artist Events
 * @throws SAXException 
 * @throws ParserConfigurationException 
 *
 *********************************/
public void getArtistEvents() throws SAXException, ParserConfigurationException {
    /*
     * Initialize Artist Cursor
     */
    artistCursor = ((RockPlayer) context).contentResolver.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            ((RockPlayer) context).ARTIST_COLS, // we should minimize the number of columns
            null, // all albums 
            null, // parameters to the previous parameter - which is null also 
            null // sort order, SQLite-like
    );

    /*
     * Declare & Initialize some vars
     */
    String artistName = null;
    String artistNameFiltered = null;
    String artistConcertFileName = null;
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    XMLArtistEventHandler xmlHandler = new XMLArtistEventHandler();
    xmlHandler.myLocation = this.myLocation;
    xmlReader.setContentHandler(xmlHandler);

    /*
     * Set Distance Limit
     */
    xmlHandler.MAX_DISTANCE = this.concertRadius;

    /*
     * Loop through the artists
     */
    artistCursor.moveToFirst();
    for (int i = 0; i < artistCursor.getCount(); i++) {
        /*
         * Get artist name
         */
        artistName = artistCursor.getString(artistCursor.getColumnIndex(MediaStore.Audio.Artists.ARTIST));
        if (artistName.equals("<unknown>")) {
            artistCursor.moveToNext();
            continue;
        }
        artistNameFiltered = filterString(artistName);
        artistConcertFileName = ((RockPlayer) context).FILEX_CONCERT_PATH + validateFileName(artistName);

        /*
         * UI feedback
         */
        Bundle data = new Bundle();
        data.putString("info", artistName);
        Message msg = new Message();
        msg.setData(data);
        ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);

        /*
         * If we dont have yet or info is too old, update the concert info of this artist
         */
        if (hasConcertInfo(artistName) == false || concertInfoNeedsUpdate(artistName) == true) {
            Log.i("INET", "Getting concert info from LastFM");
            if (hasConcertInfo(artistName) == false)
                Log.i("INET", "Because there is no concert info yet");
            if (concertInfoNeedsUpdate(artistName) == true)
                Log.i("INET", "Because Info is too old");

            File artistConcertFile = new File(artistConcertFileName);
            if (!artistConcertFile.exists()) {
                try {
                    artistConcertFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            URL lastFmApiRequest;
            try {
                lastFmApiRequest = new URL(
                        this.LAST_FM_API_URL + "&artist=" + URLEncoder.encode(artistNameFiltered));
                BufferedInputStream bufferedURLStream = new BufferedInputStream(lastFmApiRequest.openStream());
                BufferedOutputStream bufferedFileWriter = new BufferedOutputStream(
                        new FileOutputStream(artistConcertFile));

                byte[] buf = new byte[1024];
                int len;
                while ((len = bufferedURLStream.read(buf)) >= 0)
                    bufferedFileWriter.write(buf, 0, len);
                bufferedURLStream.close();
                bufferedFileWriter.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        /*
         * get event list from cached XML files
         */
        File artistConcertFile = new File(artistConcertFileName);
        if (artistConcertFile.exists() && artistConcertFile.length() > 0) {
            try {
                BufferedReader xmlFileReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(artistConcertFile)));
                xmlHandler.resetList();
                xmlHandler.artist = artistName;
                xmlReader.parse(new InputSource(xmlFileReader));
                insertListInListByDate(xmlHandler.artistEventList);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        artistCursor.moveToNext();
    }

    /*
     * Debug
     */
    ArtistEvent artistEventDebug = null;
    if (!artistEventList.isEmpty()) {
        artistEventList.getFirst();
        ListIterator<ArtistEvent> listIterator = artistEventList.listIterator(0);
        for (artistEventDebug = listIterator.next(); listIterator
                .hasNext() == true; artistEventDebug = listIterator.next()) {
            if (artistEventDebug != null)
                Log.i("DBG", artistEventDebug.date + " " + artistEventDebug.city);
            //   Log.i("DBG", artistEventDebug.date+" "+artistEventDebug.city+" "+artistEventDebug.artist);
            else
                Log.i("DBG", "NULL");
        }
    }
    /*
     * Update Adapter
     */
    eventLinkedListAdapter = new EventLinkedListAdapter(context, R.layout.eventlist_item, artistEventList);
    if (eventLinkedListAdapter == null)
        Log.i("NULL", "NULL");
    ((RockPlayer) context).updateEventListHandler.sendEmptyMessage(0);

    /*
     * Give feedback to the user
     */
    Bundle data = new Bundle();
    Message msg = new Message();
    data.putString("info", "Done!");
    msg.setData(data);
    ((RockPlayer) context).analyseConcertInfoHandler.sendMessage(msg);
}

From source file:org.xwiki.contrib.repository.pypi.internal.searching.PypiPackageListIndexUpdateTask.java

protected List<String> parseHtmlPageToPackagenames(InputStream is)
        throws ParserConfigurationException, SAXException, IOException {
    SAXParserFactory parserFactor = SAXParserFactory.newInstance();
    SAXParser parser = parserFactor.newSAXParser();
    PypiPackageListSAXHandler handler = new PypiPackageListSAXHandler();
    parser.parse(is, handler);//from  w w  w  .  ja v  a2 s  . co m
    return handler.getPackageNames();
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml//from w w w  .ja v  a  2  s .  c  o m
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:com.connectsdk.core.upnp.Device.java

public static Device createInstanceFromXML(String url, String searchTarget) {
    Device newDevice = null;/*www .  java 2s .c o m*/
    try {
        newDevice = new Device(url, searchTarget);
    } catch (IOException e) {
        return null;
    }

    final Device device = newDevice;

    DefaultHandler dh = new DefaultHandler() {
        String currentValue = null;
        Icon currentIcon;
        Service currentService;

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            currentValue = new String(ch, start, length);
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (Icon.TAG.equals(qName)) {
                currentIcon = new Icon();
            } else if (Service.TAG.equals(qName)) {
                currentService = new Service();
                currentService.baseURL = device.baseURL;
            }

        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            //               System.out.println("[DEBUG] qName: " + qName + ", currentValue: " + currentValue);
            /* Parse device-specific information */
            if (TAG_DEVICE_TYPE.equals(qName)) {
                device.deviceType = currentValue;
            } else if (TAG_FRIENDLY_NAME.equals(qName)) {
                device.friendlyName = currentValue;
            } else if (TAG_MANUFACTURER.equals(qName)) {
                device.manufacturer = currentValue;
            } else if (TAG_MANUFACTURER_URL.equals(qName)) {
                device.manufacturerURL = currentValue;
            } else if (TAG_MODEL_DESCRIPTION.equals(qName)) {
                device.modelDescription = currentValue;
            } else if (TAG_MODEL_NAME.equals(qName)) {
                device.modelName = currentValue;
            } else if (TAG_MODEL_NUMBER.equals(qName)) {
                device.modelNumber = currentValue;
            } else if (TAG_MODEL_URL.equals(qName)) {
                device.modelURL = currentValue;
            } else if (TAG_SERIAL_NUMBER.equals(qName)) {
                device.serialNumber = currentValue;
            } else if (TAG_UDN.equals(qName)) {
                device.UDN = currentValue;

                //                   device.UUID = Device.parseUUID(currentValue);
            } else if (TAG_UPC.equals(qName)) {
                device.UPC = currentValue;
            }
            /* Parse icon-list information */
            else if (Icon.TAG_MIME_TYPE.equals(qName)) {
                currentIcon.mimetype = currentValue;
            } else if (Icon.TAG_WIDTH.equals(qName)) {
                currentIcon.width = currentValue;
            } else if (Icon.TAG_HEIGHT.equals(qName)) {
                currentIcon.height = currentValue;
            } else if (Icon.TAG_DEPTH.equals(qName)) {
                currentIcon.depth = currentValue;
            } else if (Icon.TAG_URL.equals(qName)) {
                currentIcon.url = currentValue;
            } else if (Icon.TAG.equals(qName)) {
                device.iconList.add(currentIcon);
            }
            /* Parse service-list information */
            else if (Service.TAG_SERVICE_TYPE.equals(qName)) {
                currentService.serviceType = currentValue;
            } else if (Service.TAG_SERVICE_ID.equals(qName)) {
                currentService.serviceId = currentValue;
            } else if (Service.TAG_SCPD_URL.equals(qName)) {
                currentService.SCPDURL = currentValue;
            } else if (Service.TAG_CONTROL_URL.equals(qName)) {
                currentService.controlURL = currentValue;
            } else if (Service.TAG_EVENTSUB_URL.equals(qName)) {
                currentService.eventSubURL = currentValue;
            } else if (Service.TAG.equals(qName)) {
                device.serviceList.add(currentService);
            }
        }
    };

    SAXParserFactory factory = SAXParserFactory.newInstance();

    SAXParser parser;
    try {
        URL mURL = new URL(url);
        URLConnection urlConnection = mURL.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        try {
            parser = factory.newSAXParser();
            parser.parse(in, dh);
        } finally {
            in.close();
        }

        device.headers = urlConnection.getHeaderFields();

        return device;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:net.sbbi.upnp.messages.ActionMessage.java

/**
 * Executes the message and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a response object containing the UPNP parsed response
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 *//*w  w  w  . j  av  a 2s  .  co m*/
public ActionResponse service() throws IOException, UPNPResponseException {
    ActionResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType())
            .append("\">");

    if (serviceAction.getInputActionArguments() != null) {
        // this action requires params so we just set them...
        for (Iterator itr = inputParameters.iterator(); itr.hasNext();) {
            InputParamContainer container = (InputParamContainer) itr.next();
            body.append("<").append(container.name).append(">").append(container.value);
            body.append("</").append(container.name).append(">");
        }
    }
    body.append("</u:").append(serviceAction.getName()).append(">");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    conn.setRequestProperty("SOAPACTION",
            "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\"");
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    out.close();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getActionResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:com.googlecode.l10nmavenplugin.validators.property.HtmlValidator.java

/**
 * Initialize using XML schema/*from w ww  .j  a  va 2s  .  c o  m*/
 * 
 * @param xhtmlSchema
 * @param logger
 */
public HtmlValidator(File xhtmlSchema, L10nValidatorLogger logger, L10nValidator<Property> spellCheckValidator,
        String[] htmlKeys, Formatter formattingParametersExtractor,
        InnerResourcesFormatter innerResourceFormatter) {
    super(logger, htmlKeys);
    this.spellCheckValidator = spellCheckValidator;
    this.formattingParametersExtractor = formattingParametersExtractor;
    this.innerResourceFormatter = innerResourceFormatter;

    try {
        // SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // Need to use XERCES so that XHTML5 schema passes validation
        SchemaFactory factory = new XMLSchemaFactory();
        factory.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING, false);

        Schema schema = null;
        if (xhtmlSchema.exists()) {
            // Load custom schema
            schema = factory.newSchema(xhtmlSchema);
        } else {
            // Try to load a pre-defined schemas from classpath
            URL schemaURL = this.getClass().getClassLoader().getResource(xhtmlSchema.getName());

            if (schemaURL == null) {
                logger.getLogger()
                        .error("Could not load XML schema from file <" + xhtmlSchema.getAbsolutePath()
                                + "> and <" + xhtmlSchema.getName() + "> is not a default schema either ("
                                + Arrays.toString(PREDEFINED_XSD) + "), thus defaulting to "
                                + XHTML1_TRANSITIONAL.getName());
                schemaURL = this.getClass().getClassLoader().getResource(XHTML1_TRANSITIONAL.getName());
            }
            schema = factory.newSchema(schemaURL);
        }
        xhtmlValidator = schema.newValidator();

        // Initialize SAX parser
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        parser = saxParserFactory.newSAXParser();

    } catch (SAXException e) {
        logger.getLogger().error("Could not initialize HtmlValidator", e);

    } catch (ParserConfigurationException e) {
        logger.getLogger().error("Could not initialize HtmlValidator", e);
    }
}

From source file:com.granule.json.utils.XML.java

/**
 * Method to do the transform from an XML input stream to a JSON stream.
 * Neither input nor output streams are closed.  Closure is left up to the caller.
 *
 * @param XMLStream The XML stream to convert to JSON
 * @param JSONStream The stream to write out JSON to.  The contents written to this stream are always in UTF-8 format.
 * @param verbose Flag to denote whether or not to render the JSON text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format.
 *
 * @throws SAXException Thrown if a parse error occurs.
 * @throws IOException Thrown if an IO error occurs.
 */// w w  w.ja v  a2s. c  om
public static void toJson(InputStream XMLStream, OutputStream JSONStream, boolean verbose)
        throws SAXException, IOException {
    if (logger.isLoggable(Level.FINER)) {
        logger.entering(className, "toJson(InputStream, OutputStream)");
    }

    if (XMLStream == null) {
        throw new NullPointerException("XMLStream cannot be null");
    } else if (JSONStream == null) {
        throw new NullPointerException("JSONStream cannot be null");
    } else {

        if (logger.isLoggable(Level.FINEST)) {
            logger.logp(Level.FINEST, className, "transform",
                    "Fetching a SAX parser for use with JSONSAXHandler");
        }

        try {
            /**
             * Get a parser.
             */
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser sParser = factory.newSAXParser();
            XMLReader parser = sParser.getXMLReader();
            JSONSAXHandler jsonHandler = new JSONSAXHandler(JSONStream, verbose);
            parser.setContentHandler(jsonHandler);
            parser.setErrorHandler(jsonHandler);
            InputSource source = new InputSource(new BufferedInputStream(XMLStream));

            if (logger.isLoggable(Level.FINEST)) {
                logger.logp(Level.FINEST, className, "transform", "Parsing the XML content to JSON");
            }

            /** 
             * Parse it.
             */
            source.setEncoding("UTF-8");
            parser.parse(source);
            jsonHandler.flushBuffer();
        } catch (javax.xml.parsers.ParserConfigurationException pce) {
            throw new SAXException("Could not get a parser: " + pce.toString());
        }
    }

    if (logger.isLoggable(Level.FINER)) {
        logger.exiting(className, "toJson(InputStream, OutputStream)");
    }
}

From source file:architecture.common.model.factory.ModelTypeFactory.java

private static List<ModelList> parseLegacyXmlFile(List<ModelList> list) throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> enumeration = cl.getResources(IF_PLUGIN_PATH);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/*from www .  jav  a 2 s  .co m*/
    XMLReader xmlreader = factory.newSAXParser().getXMLReader();
    ImplFactoryParsingHandler handler = new ImplFactoryParsingHandler();
    xmlreader.setContentHandler(handler);
    xmlreader.setDTDHandler(handler);
    xmlreader.setEntityResolver(handler);
    xmlreader.setErrorHandler(handler);
    System.out.println("Model Enum:");
    do {
        if (!enumeration.hasMoreElements())
            break;
        URL url = (URL) enumeration.nextElement();
        System.out.println(" - " + url);
        try {
            xmlreader.parse(new InputSource(url.openStream()));
            ModelList factorylist = new ModelList();
            factorylist.rank = handler.rank;
            factorylist.modelTypes.addAll(handler.getModels());
            list.add(factorylist);
        } catch (Exception exception) {
        }
    } while (true);

    return list;
}