List of usage examples for org.xml.sax InputSource setEncoding
public void setEncoding(String encoding)
From source file:nl.b3p.wms.capabilities.WMSCapabilitiesReader.java
public ServiceProvider getProvider(String location, B3PCredentials credentials, String remoteAddr) throws IOException, SAXException, Exception { ByteArrayOutputStream getCap = getCapabilities(location, credentials, remoteAddr); //String xml = getCapabilities(location, username, password); ByteArrayInputStream in = new ByteArrayInputStream(getCap.toByteArray()); //Nu kan het service provider object gemaakt en gevuld worden serviceProvider = new ServiceProvider(); XMLReader reader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); // niet zinvol met IgnoreEntityResolver hierna // reader.setFeature(VALIDATION_FEATURE, true); // reader.setFeature(SCHEMA_FEATURE, true); IgnoreEntityResolver r = new IgnoreEntityResolver(); reader.setEntityResolver(r);/*from w w w. j a v a 2 s . c o m*/ reader.setContentHandler(s); InputSource is = new InputSource(in); is.setEncoding(KBConfiguration.CHARSET); reader.parse(is); if (serviceProvider == null) { log.error("Host: " + location + " error: No service provider object could be created, unkown reason!"); throw new Exception( "Host: " + location + " error: No service provider object could be created, unkown reason!"); } return serviceProvider; }
From source file:com.kdmanalytics.toif.assimilator.Assimilator.java
/** * Load the kdm file. parse the input file. * //from ww w.j ava2s. c o m * @param xmlFile * the input file * @param out * output stream * @return the xml handler for the kdm data. * @throws IOException * @throws ToifInternalException */ public KdmXmlHandler load(File xmlFile, PipedOutputStream out) throws IOException, RepositoryException, ToifException { RepositoryConnection tempCon = null; KdmXmlHandler kdmXmlHandler = null; PrintWriter pw = null; try { File tempFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "KDMRepository"); deleteDirectory(tempFile); tempFile.deleteOnExit(); Repository tempRepository = new SailRepository(new NativeStore(tempFile)); tempRepository.initialize(); tempCon = tempRepository.getConnection(); /** * The factory used to drive the parsing process. * */ SAXParserFactory factory = null; // Use the default (non-validating) parser factory = SAXParserFactory.newInstance(); SAXParser saxParser; saxParser = factory.newSAXParser(); // Have to parse the file once to determine the maximum id; KdmXmiIdHandler idHandler = new KdmXmiIdHandler(); // Need to set the stream to UTF-8 ti ensure that we correctly // handle // characters in Strings InputStream inputStream = new FileInputStream(xmlFile); InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8"); InputSource inputSource = new InputSource(inputReader); inputSource.setEncoding("UTF-8"); saxParser.parse(inputSource, idHandler); tempCon.setAutoCommit(false); // Control commit for speed pw = new PrintWriter(out); kdmXmlHandler = new KdmXmlHandler(pw, repository, idHandler.getMaxId()); // Parse the input saxParser.parse(xmlFile, kdmXmlHandler); // Commit postLoad data kdmXmlHandler.postLoad(); tempCon.commit(); tempCon.clear(); } catch (ParserConfigurationException | SAXException ex) { final String msg = "Parser exception encountered:"; LOG.error(msg, ex); throw new ToifException(msg, ex); } finally { if (pw != null) { pw.flush(); pw.close(); } if (null != tempCon) { tempCon.close(); } } return kdmXmlHandler; }
From source file:jef.tools.XMLUtils.java
/** * XML/*from w ww .java2 s . com*/ * * @param in * ? * @param charSet * ? * @param ignorComment * * @return Document. DOM * @throws SAXException * ? * @throws IOException * */ public static Document loadDocument(InputStream in, String charSet, boolean ignorComments, boolean namespaceAware) throws SAXException, IOException { DocumentBuilder db = REUSABLE_BUILDER.get().getDocumentBuilder(ignorComments, namespaceAware); InputSource is = null; // ????charset if (charSet == null) {// ?200??? byte[] buf = new byte[200]; PushbackInputStream pin = new PushbackInputStream(in, 200); in = pin; int len = pin.read(buf); if (len > 0) { pin.unread(buf, 0, len); charSet = getCharsetInXml(buf, len); } } if (charSet != null) { is = new InputSource(new XmlFixedReader(new InputStreamReader(in, charSet))); is.setEncoding(charSet); } else { // ? Reader reader = new InputStreamReader(in, "UTF-8");// XML???Reader??Reader?XML? is = new InputSource(new XmlFixedReader(reader)); } Document doc = db.parse(is); doc.setXmlStandalone(true);// True???standalone="no" return doc; }
From source file:com.zoffcc.applications.zanavi.Navit.java
public static void route_online_OSRM(final String addr, float lat_start, float lon_start, boolean start_coords_valid, final double lat_end, final double lon_end, final boolean remember_dest) { // http://router.project-osrm.org/viaroute?loc=46.3456438,17.450&loc=47.34122,17.5332&instructions=false&alt=false if (!start_coords_valid) { location_coords cur_target = new location_coords(); try {/* w w w . j av a 2 s . co m*/ geo_coord tmp = get_current_vehicle_position(); cur_target.lat = tmp.Latitude; cur_target.lon = tmp.Longitude; } catch (Exception e) { } try { lat_start = (float) cur_target.lat; lon_start = (float) cur_target.lon; } catch (Exception e) { e.printStackTrace(); Log.e("Navit", "problem with location!"); } } final String request_url = String.format(Locale.US, "http://router.project-osrm.org/viaroute?loc=%4.6f,%4.6f&loc=%4.6f,%4.6f&instructions=true&alt=false", lat_start, lon_start, lat_end, lon_end); // StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); // StrictMode.setThreadPolicy(policy); try { // System.out.println("XML:S:001 url=" + request_url); final URL url = new URL(request_url); // System.out.println("XML:S:002"); // SAXParserFactory factory = SAXParserFactory.newInstance(); // System.out.println("XML:S:003"); // SAXParser parser = factory.newSAXParser(); // System.out.println("XML:S:004"); // XMLReader xmlreader = parser.getXMLReader(); // System.out.println("XML:S:005"); // xmlreader.setContentHandler(new ZANaviXMLHandler()); // System.out.println("XML:S:006"); final Thread add_to_route = new Thread() { @Override public void run() { try { // -------------- // -------------- // -------------- // ------- allow this HTTPS cert --- // -------------- // -------------- // -------------- // X509HostnameVerifier hnv = new X509HostnameVerifier() // { // // @Override // public void verify(String hostname, SSLSocket arg1) throws IOException // { // Log.d("SSL", "DANGER !!! trusted hostname=" + hostname + " DANGER !!!"); // } // // @Override // public void verify(String hostname, X509Certificate cert) throws SSLException // { // Log.d("SSL", "DANGER !!! trusted hostname=" + hostname + " DANGER !!!"); // } // // @Override // public void verify(String hostname, String[] cns, String[] subjectAlts) throws SSLException // { // Log.d("SSL", "DANGER !!! trusted hostname=" + hostname + " DANGER !!!"); // } // // @Override // public boolean verify(String hostname, SSLSession session) // { // Log.d("SSL", "DANGER !!! trusted hostname=" + hostname + " DANGER !!!"); // return true; // } // }; // // SSLContext context = SSLContext.getInstance("TLS"); // context.init(null, new X509TrustManager[] { new X509TrustManager() // { // public java.security.cert.X509Certificate[] getAcceptedIssuers() // { // return new java.security.cert.X509Certificate[0]; // } // // @Override // public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException // { // } // // @Override // public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException // { // } // } }, new SecureRandom()); // javax.net.ssl.SSLSocketFactory sslf = context.getSocketFactory(); // // HostnameVerifier hnv_default = HttpsURLConnection.getDefaultHostnameVerifier(); // javax.net.ssl.SSLSocketFactory sslf_default = HttpsURLConnection.getDefaultSSLSocketFactory(); // HttpsURLConnection.setDefaultHostnameVerifier(hnv); // HttpsURLConnection.setDefaultSSLSocketFactory(sslf); // // DefaultHttpClient client = new DefaultHttpClient(); // // SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); // SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("https", socketFactory, 443)); // ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(client.getParams(), registry); // DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams()); // // socketFactory.setHostnameVerifier(hnv); // // HttpGet get_request = new HttpGet(request_url); // HttpResponse http_response = httpClient.execute(get_request); // HttpEntity responseEntity = http_response.getEntity(); // // HttpsURLConnection.setDefaultHostnameVerifier(hnv_default); // HttpsURLConnection.setDefaultSSLSocketFactory(sslf_default); // -------------- // -------------- // -------------- // ------- allow this HTTPS cert --- // -------------- // -------------- // -------------- InputSource is = new InputSource(); is.setEncoding("utf-8"); // is.setByteStream(responseEntity.getContent()); is.setByteStream(url.openStream()); // System.out.println("XML:S:007"); String response = slurp(is.getByteStream(), 16384); // response = response.replaceAll("&", "&"); // System.out.println("XML:S:007.a res=" + response); final JSONObject obj = new JSONObject(response); // System.out.println(person.getInt("id")); final String route_geometry = obj.getString("route_geometry"); final JSONArray route_instructions_array = obj.getJSONArray("route_instructions"); int loop_i = 0; JSONArray instruction; int[] instruction_pos = new int[route_instructions_array.length()]; for (loop_i = 0; loop_i < route_instructions_array.length(); loop_i++) { instruction = (JSONArray) route_instructions_array.get(loop_i); instruction_pos[loop_i] = Integer.parseInt(instruction.get(3).toString()); // System.out.println("XML:instr. pos=" + instruction_pos[loop_i]); } // System.out.println("XML:S:009 o=" + route_geometry); List<geo_coord> gc_list = decode_function(route_geometry, 6); if (gc_list.size() < 2) { // no real route found!! (only 1 point) } else { Message msg = new Message(); Bundle b = new Bundle(); int loop = 0; geo_coord cur = new geo_coord(); geo_coord old = new geo_coord(); geo_coord corr = new geo_coord(); cur.Latitude = gc_list.get(loop).Latitude; cur.Longitude = gc_list.get(loop).Longitude; int first_found = 1; if (gc_list.size() > 2) { int instr_count = 1; for (loop = 1; loop < gc_list.size(); loop++) { old.Latitude = cur.Latitude; old.Longitude = cur.Longitude; cur.Latitude = gc_list.get(loop).Latitude; cur.Longitude = gc_list.get(loop).Longitude; if ((instruction_pos[instr_count] == loop) || (loop == (gc_list.size() - 1))) { if (loop == (gc_list.size() - 1)) { corr = cur; } else { corr = get_point_on_line(old, cur, 70); } // -- add waypoint -- // b.putInt("Callback", 55548); // b.putString("lat", "" + corr.Latitude); // b.putString("lon", "" + corr.Longitude); // b.putString("q", " "); // msg.setData(b); try { // NavitGraphics.callback_handler.sendMessage(msg); if (first_found == 1) { first_found = 0; NavitGraphics.CallbackMessageChannel(55503, corr.Latitude + "#" + corr.Longitude + "#" + ""); // System.out.println("XML:rR:" + loop + " " + corr.Latitude + " " + corr.Longitude); } else { NavitGraphics.CallbackMessageChannel(55548, corr.Latitude + "#" + corr.Longitude + "#" + ""); // System.out.println("XML:rw:" + loop + " " + corr.Latitude + " " + corr.Longitude); } // Thread.sleep(25); } catch (Exception e) { e.printStackTrace(); } // -- add waypoint -- instr_count++; } } } if (remember_dest) { try { Navit.remember_destination(addr, "" + lat_end, "" + lon_end); // save points write_map_points(); } catch (Exception e) { e.printStackTrace(); } } b.putInt("Callback", 55599); msg.setData(b); try { // System.out.println("XML:calc:"); Thread.sleep(10); NavitGraphics.callback_handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e2) { e2.printStackTrace(); } } }; add_to_route.start(); // convert to coords ------------- // convert to coords ------------- } catch (Exception e) { // System.out.println("XML:S:EEE"); e.printStackTrace(); } }
From source file:net.stuxcrystal.simpledev.configuration.parser.generators.xml.XMLParser.java
/** * Converts a InputStream to a input source. * @param stream The stream that contains the file. * @return The InputSource for XML./* ww w . jav a 2s .c o m*/ * @throws UnsupportedEncodingException If there is a computer without UTF-8 let me know. */ private static InputSource toSource(InputStream stream) throws UnsupportedEncodingException { Reader reader = new InputStreamReader(stream, "UTF-8"); InputSource source = new InputSource(reader); source.setEncoding("UTF-8"); return source; }
From source file:org.adl.parsers.dom.ADLDOMParser.java
/** * Sets up the file source for the test subject file. * * @param iFileName file to setup input source for. * * @return InputSource// www . java 2 s .co m */ private InputSource setupFileSource(String iFileName) { log.debug("setupFileSource()"); String msgText; boolean defaultEncoding = true; String encoding = null; PushbackInputStream inputStream; FileInputStream inFile; try { File xmlFile = new File(iFileName); log.debug(xmlFile.getAbsolutePath()); if (xmlFile.isFile()) { InputSource is = null; defaultEncoding = true; if (xmlFile.length() > 1) { inFile = new FileInputStream(xmlFile); inputStream = new PushbackInputStream(inFile, 4); // Reads the initial 4 bytes of the file to check for a Byte // Order Mark and determine the encoding byte bom[] = new byte[4]; int n, pushBack; n = inputStream.read(bom, 0, bom.length); // UTF-8 Encoded if ((bom[0] == (byte) 0xEF) && (bom[1] == (byte) 0xBB) && (bom[2] == (byte) 0xBF)) { encoding = "UTF-8"; defaultEncoding = false; pushBack = n - 3; } // UTF-16 Big Endian Encoded else if ((bom[0] == (byte) 0xFE) && (bom[1] == (byte) 0xFF)) { encoding = "UTF-16BE"; defaultEncoding = false; pushBack = n - 2; } // UTF-16 Little Endian Encoded else if ((bom[0] == (byte) 0xFF) && (bom[1] == (byte) 0xFE)) { encoding = "UTF-16LE"; defaultEncoding = false; pushBack = n - 2; } // Default encoding else { // Unicode BOM mark not found, unread all bytes pushBack = n; } // Place any non-BOM bytes back into the stream if (pushBack > 0) { inputStream.unread(bom, (n - pushBack), pushBack); } if (defaultEncoding == true) { //Reads in ASCII file. FileReader fr = new FileReader(xmlFile); is = new InputSource(fr); } // Reads the file in the determined encoding else { //Creates a buffer with the size of the xml encoded file BufferedReader inStream = new BufferedReader(new InputStreamReader(inputStream, encoding)); StringBuffer dataString = new StringBuffer(); String s = ""; //Builds the encoded file to be parsed while ((s = inStream.readLine()) != null) { dataString.append(s); } inStream.close(); inputStream.close(); inFile.close(); is = new InputSource(new StringReader(dataString.toString())); is.setEncoding(encoding); } } return is; } else if ((iFileName.length() > 6) && (iFileName.substring(0, 5).equals("http:") || iFileName.substring(0, 6).equals("https:"))) { URL xmlURL = new URL(iFileName); InputStream xmlIS = xmlURL.openStream(); InputSource is = new InputSource(xmlIS); return is; } else { msgText = "XML File: " + iFileName + " is not a file or URL"; log.error(msgText); } } catch (NullPointerException npe) { msgText = "Null pointer exception" + npe; log.error(msgText); } catch (SecurityException se) { msgText = "Security Exception" + se; log.error(msgText); } catch (FileNotFoundException fnfe) { msgText = "File Not Found Exception" + fnfe; log.error(msgText); } catch (Exception e) { msgText = "General Exception" + e; log.error(msgText); } log.debug("setUpFileSource()"); return new InputSource(); }
From source file:org.ajax4jsf.webapp.FilterServletResponseWrapper.java
/** * @return/*from www .j a v a 2 s .c o m*/ * @throws RuntimeException */ public InputSource getContentAsInputSource() throws RuntimeException { // Create InputSource InputSource inputSource = null; String encoding = this.getCharacterEncoding(); if (isUseWriter()) { inputSource = new InputSource(getContentAsReader()); } else if (isUseStream()) { inputSource = new InputSource(getContentAsStream()); if (encoding != null) inputSource.setEncoding(encoding); } else { if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.NO_WRITER_CALLED_INFO)); } return null; } return inputSource; }
From source file:org.apache.axis.SOAPPart.java
/** * Get the contents of this Part (not the MIME headers!), as a * SOAPEnvelope. This will force a complete parse of the * message./*from ww w .jav a 2 s . c o m*/ * * @return a <code>SOAPEnvelope</code> containing the message content * @throws AxisFault if the envelope could not be constructed */ public SOAPEnvelope getAsSOAPEnvelope() throws AxisFault { if (log.isDebugEnabled()) { log.debug("Enter: SOAPPart::getAsSOAPEnvelope()"); log.debug(Messages.getMessage("currForm", formNames[currentForm])); } if (currentForm == FORM_SOAPENVELOPE) return (SOAPEnvelope) currentMessage; if (currentForm == FORM_BODYINSTREAM) { InputStreamBody bodyEl = new InputStreamBody((InputStream) currentMessage); SOAPEnvelope env = new SOAPEnvelope(); env.setOwnerDocument(this); env.addBodyElement(bodyEl); setCurrentForm(env, FORM_SOAPENVELOPE); return env; } InputSource is; if (currentForm == FORM_INPUTSTREAM) { is = new InputSource((InputStream) currentMessage); String encoding = XMLUtils.getEncoding(msgObject, null, null); if (encoding != null) { currentEncoding = encoding; is.setEncoding(currentEncoding); } } else { is = new InputSource(new StringReader(getAsString())); } DeserializationContext dser = new DeserializationContext(is, getMessage().getMessageContext(), getMessage().getMessageType()); dser.getEnvelope().setOwnerDocument(this); // This may throw a SAXException try { dser.parse(); } catch (SAXException e) { Exception real = e.getException(); if (real == null) real = e; throw AxisFault.makeFault(real); } SOAPEnvelope nse = dser.getEnvelope(); if (currentMessageAsEnvelope != null) { //Need to synchronize back processed header info. Vector newHeaders = nse.getHeaders(); Vector oldHeaders = currentMessageAsEnvelope.getHeaders(); if (null != newHeaders && null != oldHeaders) { Iterator ohi = oldHeaders.iterator(); Iterator nhi = newHeaders.iterator(); while (ohi.hasNext() && nhi.hasNext()) { SOAPHeaderElement nhe = (SOAPHeaderElement) nhi.next(); SOAPHeaderElement ohe = (SOAPHeaderElement) ohi.next(); if (ohe.isProcessed()) nhe.setProcessed(true); } } } setCurrentForm(nse, FORM_SOAPENVELOPE); log.debug("Exit: SOAPPart::getAsSOAPEnvelope"); SOAPEnvelope env = (SOAPEnvelope) currentMessage; env.setOwnerDocument(this); return env; }
From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java
protected Element createChildFromXmlFragmentOrText(Document doc, Input input, String localElementName, String errorMessage, String elementOrText) throws IOException, ParserConfigurationException, XmlSignatureException { String ending = localElementName + ">"; Element child;//from w w w .ja va2s. com if (elementOrText.startsWith("<") && elementOrText.endsWith(ending)) { try { // assume xml InputSource source = new InputSource(new StringReader(elementOrText)); source.setEncoding("UTF-8"); Document parsedDoc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(source); replacePrefixes(parsedDoc, input); child = (Element) doc.adoptNode(parsedDoc.getDocumentElement()); // check for correct namespace String ns = findNamespace(input.getMessage()); if (!ns.equals(child.getNamespaceURI())) { throw new XmlSignatureException(String.format( "The XAdES confguration is invalid. The root element '%s' of the provided XML fragment '%s' has the invalid namespace '%s'. The correct namespace is '%s'.", child.getLocalName(), elementOrText, child.getNamespaceURI(), ns)); } } catch (SAXException e) { throw new XmlSignatureException( String.format(errorMessage, elementOrText, localElementName, namespace), e); } } else { child = createElement(localElementName, doc, input); child.setTextContent(elementOrText); } return child; }
From source file:org.apache.marmotta.ucuenca.wk.provider.gs.GoogleScholarPageProvider.java
@Override public List<String> parseResponse(String resource, String requestUrl, Model triples, InputStream input, String contentType) throws DataRetrievalException { log.debug("Request Successful to {0}", requestUrl); final GSXMLHandler gsXMLHandler = new GSXMLHandler(); gsXMLHandler.clearGSresultList();/*from w w w .j a v a 2s . c o m*/ try { XMLReader xr = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser"); xr.setContentHandler(gsXMLHandler); InputSource gsxml = new InputSource(input); gsxml.setEncoding("iso-8859-1"); xr.parse(gsxml); final Set<GSresult> gsresultlist = gsXMLHandler.getGSresultList(); Gson gson = new Gson(); JsonArray json = new JsonArray(); for (GSresult d : gsresultlist) { json.add(gson.toJsonTree(d).getAsJsonObject()); } JSONtoRDF parser = new JSONtoRDF(resource, GoogleScholarProvider.MAPPINGSCHEMA, json, triples); try { parser.parse(); } catch (Exception e) { throw new DataRetrievalException("I/O exception while retrieving resource: " + requestUrl, e); } } catch (SAXException | IOException e) { throw new DataRetrievalException("I/O exception while retrieving resource: " + requestUrl, e); } // try { // List<String> candidates = new ArrayList<String>(); // ValueFactory factory = ValueFactoryImpl.getInstance(); // final Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(input); // for(Element element: queryElements(doc, "/result/hits/hit/info/url")) { // String candidate = element.getText(); // triples.add(factory.createStatement(factory.createURI( resource ), FOAF.member, factory.createURI( candidate ) )); // candidates.add(candidate); // } // ClientConfiguration conf = new ClientConfiguration(); // LDClient ldClient = new LDClient(conf); // if(!candidates.isEmpty()) { // Model candidateModel = null; // for(String author: candidates) { // ClientResponse response = ldClient.retrieveResource(author); // Model authorModel = response.getData(); // if(candidateModel == null) { // candidateModel = authorModel; // } else { // candidateModel.addAll(authorModel); // } // } // triples.addAll(candidateModel); // } // }catch (IOException e) { // throw new DataRetrievalException("I/O error while parsing HTML response", e); // }catch (JDOMException e) { // throw new DataRetrievalException("could not parse XML response. It is not in proper XML format", e); // } return Collections.emptyList(); }