Example usage for org.xml.sax InputSource getByteStream

List of usage examples for org.xml.sax InputSource getByteStream

Introduction

In this page you can find the example usage for org.xml.sax InputSource getByteStream.

Prototype

public InputStream getByteStream() 

Source Link

Document

Get the byte stream for this input source.

Usage

From source file:de.ii.xtraplatform.ogc.api.wfs.parser.WFSCapabilitiesParser.java

public void parse(InputSource is) {

    SMInputCursor root = null;/*from w ww.  j  a va  2 s. c o m*/

    try {
        root = staxFactory.rootElementCursor(is.getByteStream()).advance();

        if (checkForExceptionReport(root)) {
            return;
        }

        parseNamespaces(root);

        analyzer.analyzeVersion(root.getAttrValue(OWS.getWord(OWS.VOCABULARY.VERSION)));

        SMInputCursor capabilitiesChild = root.childElementCursor().advance();

        while (capabilitiesChild.readerAccessible()) {

            switch (OWS.findKey(capabilitiesChild.getLocalName())) {
            case SERVICE_IDENTIFICATION:
                parseServiceIdentification(capabilitiesChild);
                break;
            case SERVICE_PROVIDER:
                parseServiceProvider(capabilitiesChild);
                break;
            case OPERATIONS_METADATA:
                parseOperationsMetadata(capabilitiesChild);
                break;
            case FEATURE_TYPE_LIST:
                parseFeatureTypeList(capabilitiesChild);
                break;
            }

            capabilitiesChild = capabilitiesChild.advance();
        }
    } catch (XMLStreamException ex) {
        // TODO: move to analyzer for XtraProxy
        //LOGGER.error(FrameworkMessages.ERROR_PARSING_WFS_CAPABILITIES);
        //throw new ParseError(FrameworkMessages.ERROR_PARSING_WFS_CAPABILITIES);

        analyzer.analyzeFailed(ex);
    } finally {
        if (root != null) {
            try {
                root.getStreamReader().closeCompletely();
            } catch (XMLStreamException ex) {
                // ignore
            }
        }
    }
}

From source file:de.ii.xtraplatform.feature.provider.wfs.WFSCapabilitiesParser.java

public void parse(InputSource is) {

    SMInputCursor root = null;/*from  w  w  w .j  a  v a 2s.  c o m*/

    try {
        root = staxFactory.rootElementCursor(is.getByteStream()).advance();

        if (checkForExceptionReport(root)) {
            return;
        }

        parseNamespaces(root);

        metadataConsumer.analyzeVersion(root.getAttrValue(OWS.getWord(OWS.VOCABULARY.VERSION)));

        SMInputCursor capabilitiesChild = root.childElementCursor().advance();

        while (capabilitiesChild.readerAccessible()) {

            switch (OWS.findKey(capabilitiesChild.getLocalName())) {
            case SERVICE_IDENTIFICATION:
                parseServiceIdentification(capabilitiesChild);
                break;
            case SERVICE_PROVIDER:
                parseServiceProvider(capabilitiesChild);
                break;
            case OPERATIONS_METADATA:
                parseOperationsMetadata(capabilitiesChild);
                break;
            case FEATURE_TYPE_LIST:
                parseFeatureTypeList(capabilitiesChild);
                break;
            }

            capabilitiesChild = capabilitiesChild.advance();
        }
    } catch (XMLStreamException ex) {
        // TODO: move to analyzer for XtraProxy
        //LOGGER.error(FrameworkMessages.ERROR_PARSING_WFS_CAPABILITIES);
        //throw new ParseError(FrameworkMessages.ERROR_PARSING_WFS_CAPABILITIES);

        metadataConsumer.analyzeFailed(ex);
    } finally {
        if (root != null) {
            try {
                root.getStreamReader().closeCompletely();
            } catch (XMLStreamException ex) {
                // ignore
            }
        }
    }
}

From source file:com.atlassian.jira.bc.dataimport.DefaultDataImportService.java

private void closeInputSource(InputSource is) {
    if (is != null) {
        IOUtils.closeQuietly(is.getByteStream());
        IOUtils.closeQuietly(is.getCharacterStream());
    }//w  w  w. ja v  a2s  .c  o m
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

private void createProximityAlertSetupDialog() {
    final Dialog dialog = dialogInterface.getDialog(getActivity(), R.layout.dialog_proximity_alert_create,
            R.string.create_proximity_alert);

    Button setProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_create_alert_watcher_button);
    Button stopCurrentProximityAlertWatcherButton = (Button) dialog
            .findViewById(R.id.create_proximity_alert_stop_existing_alert_button);
    Button cancelButton = (Button) dialog.findViewById(R.id.create_proximity_alert_cancel_button);
    SeekBar seekbar = (SeekBar) dialog.findViewById(R.id.create_proximity_alert_seekBar);
    final EditText radiusEditText = (EditText) dialog.findViewById(R.id.create_proximity_alert_range_edit_text);
    final Switch formatSwitch = (Switch) dialog.findViewById(R.id.create_proximity_alert_format_switch);

    final double seekBarStepSize = (double) (getResources()
            .getInteger(R.integer.proximity_alert_maximum_warning_range_meters)
            - getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)) / 100;

    radiusEditText.setText(/*from w  w w  .jav a 2 s  . c  o  m*/
            String.valueOf(getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)));

    formatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setText(getString(R.string.range_format_nautical_miles));
            } else {
                buttonView.setText(getString(R.string.range_format_meters));
            }
        }
    });

    seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                String range = String.valueOf(
                        (int) (getResources().getInteger(R.integer.proximity_alert_minimum_warning_range_meters)
                                + (seekBarStepSize * progress)));
                radiusEditText.setText(range);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    setProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String toastText;

            if (proximityAlertWatcher == null) {
                toastText = getString(R.string.proximity_alert_set);
            } else {

                toastText = getString(R.string.proximity_alert_replace);
            }

            if (proximityAlertWatcher != null) {
                proximityAlertWatcher.cancel(true);
            }

            mGpsLocationTracker = new GpsLocationTracker(getActivity());
            double latitude, longitude;

            if (mGpsLocationTracker.canGetLocation()) {
                latitude = mGpsLocationTracker.getLatitude();
                cachedLat = latitude;
                longitude = mGpsLocationTracker.getLongitude();
                cachedLon = longitude;
            } else {
                mGpsLocationTracker.showSettingsAlert();
                return;
            }

            if (formatSwitch.isChecked()) {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString())
                        * getResources().getInteger(R.integer.meters_per_nautical_mile);
            } else {
                cachedDistance = Double.valueOf(radiusEditText.getText().toString());
            }

            dialog.dismiss();

            Response response;

            try {
                String apiName = "fishingfacility";
                String format = "OLEX";
                String filePath;
                String fileName = "collisionCheckToolsFile";

                response = barentswatchApi.getApi().geoDataDownload(apiName, format);

                if (response == null) {
                    Log.d(TAG, "RESPONSE == NULL");
                    throw new InternalError();
                }

                if (fiskInfoUtility.isExternalStorageWritable()) {
                    String directoryPath = Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
                    String directoryName = "FiskInfo";
                    filePath = directoryPath + "/" + directoryName + "/";
                    InputStream zippedInputStream = null;

                    try {
                        TypedInput responseInput = response.getBody();
                        zippedInputStream = responseInput.in();
                        zippedInputStream = new GZIPInputStream(zippedInputStream);

                        InputSource inputSource = new InputSource(zippedInputStream);
                        InputStream input = new BufferedInputStream(inputSource.getByteStream());
                        byte data[];
                        data = FiskInfoUtility.toByteArray(input);

                        InputStream inputStream = new ByteArrayInputStream(data);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        FiskInfoPolygon2D serializablePolygon2D = new FiskInfoPolygon2D();

                        String line;
                        boolean startSet = false;
                        String[] convertedLine;
                        List<Point> shape = new ArrayList<>();
                        while ((line = reader.readLine()) != null) {
                            Point currPoint = new Point();
                            if (line.length() == 0 || line.equals("")) {
                                continue;
                            }
                            if (Character.isLetter(line.charAt(0))) {
                                continue;
                            }

                            convertedLine = line.split("\\s+");

                            if (line.length() > 150) {
                                Log.d(TAG, "line " + line);
                            }

                            if (convertedLine[0].startsWith("3sl")) {
                                continue;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && startSet) {
                                if (shape.size() == 1) {
                                    // Point

                                    serializablePolygon2D.addPoint(shape.get(0));
                                    shape = new ArrayList<>();
                                } else if (shape.size() == 2) {

                                    // line
                                    serializablePolygon2D.addLine(new Line(shape.get(0), shape.get(1)));
                                    shape = new ArrayList<>();
                                } else {

                                    serializablePolygon2D.addPolygon(new Polygon(shape));
                                    shape = new ArrayList<>();
                                }
                                startSet = false;
                            }

                            if (convertedLine[3].equalsIgnoreCase("Garnstart") && !startSet) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                                startSet = true;
                            } else if (convertedLine[3].equalsIgnoreCase("Brunsirkel")) {
                                double lat = Double.parseDouble(convertedLine[0]) / 60;
                                double lon = Double.parseDouble(convertedLine[1]) / 60;
                                currPoint.setNewPointValues(lat, lon);
                                shape.add(currPoint);
                            }
                        }

                        reader.close();
                        new FiskInfoUtility().serializeFiskInfoPolygon2D(filePath + fileName + "." + format,
                                serializablePolygon2D);

                        tools = serializablePolygon2D;

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (ArrayIndexOutOfBoundsException e) {
                        Log.e(TAG, "Error when trying to serialize file.");
                        Toast error = Toast.makeText(getActivity(), "Ingen redskaper i omrdet du definerte",
                                Toast.LENGTH_LONG);
                        e.printStackTrace();
                        error.show();
                        return;
                    } finally {
                        try {
                            if (zippedInputStream != null) {
                                zippedInputStream.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    Toast.makeText(v.getContext(), R.string.download_failed, Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                    return;
                }

            } catch (Exception e) {
                Log.d(TAG, "Could not download tools file");
                Toast.makeText(getActivity(), R.string.download_failed, Toast.LENGTH_LONG).show();
            }

            runScheduledAlarm(getResources().getInteger(R.integer.zero),
                    getResources().getInteger(R.integer.proximity_alert_interval_time_seconds));

            Toast.makeText(getActivity(), toastText, Toast.LENGTH_LONG).show();
        }
    });

    if (proximityAlertWatcher != null) {
        TypedValue outValue = new TypedValue();
        stopCurrentProximityAlertWatcherButton.setVisibility(View.VISIBLE);

        getResources().getValue(R.dimen.proximity_alert_dialog_button_text_size_small, outValue, true);
        float textSize = outValue.getFloat();

        setProximityAlertWatcherButton.setTextSize(textSize);
        stopCurrentProximityAlertWatcherButton.setTextSize(textSize);
        cancelButton.setTextSize(textSize);

        stopCurrentProximityAlertWatcherButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                proximityAlertWatcher.cancel(true);
                proximityAlertWatcher = null;
                dialog.dismiss();
            }
        });
    }

    cancelButton.setOnClickListener(onClickListenerInterface.getDismissDialogListener(dialog));

    dialog.show();
}

From source file:it.cnr.icar.eric.server.profile.ws.wsdl.cataloger.WSDLCatalogerEngine.java

@SuppressWarnings("unused")
private Collection<File> addZipEntriesToMap(ExtrinsicObjectType zipEO, InputSource inputSource)
        throws IOException {
    //Unzip the file in tmp dir
    ArrayList<File> files = Utility.unZip(TMP_DIR, inputSource.getByteStream());
    Iterator<File> iter = files.iterator();
    while (iter.hasNext()) {
        File file = iter.next();/*w w w  . j ava  2 s. c  o  m*/
        String fileName = file.getName();
        String fileNameAbolute = file.getAbsolutePath();
        //String fileNameRelative = fileNameAbolute.substring(TMP_DIR.length()+1, fileNameAbolute.length());
        String fileNameRelative = fileNameAbolute.substring(TMP_DIR.length(), fileNameAbolute.length());
        idToFileMap.put(fileNameRelative, file);
    }
    return idToFileMap.values();
}

From source file:com.evolveum.midpoint.prism.schema.SchemaRegistry.java

@Override
public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId,
        String baseURI) {//from   ww w. java2 s  . com
    // Prefer built-in resolution over the pre-parsed one. This is less efficient, but if the order is swapped
    // the parsers complaints about re-definition of the elements
    //      InputSource inputSource = resolveResourceUsingBuiltinResolver(type,namespaceURI,publicId,systemId,baseURI);
    InputSource inputSource = resolveResourceFromRegisteredSchemas(type, namespaceURI, publicId, systemId,
            baseURI);
    if (inputSource == null) {
        inputSource = resolveResourceUsingBuiltinResolver(type, namespaceURI, publicId, systemId, baseURI);
        //         inputSource = resolveResourceFromRegisteredSchemas(type,namespaceURI,publicId,systemId,baseURI);
    }
    if (inputSource == null) {
        LOGGER.error(
                "Unable to resolve resource of type {}, namespaceURI: {}, publicID: {}, systemID: {}, baseURI: {}",
                new Object[] { type, namespaceURI, publicId, systemId, baseURI });
        return null;
    }
    LOGGER.trace("Resolved resource of type {}, namespaceURI: {}, publicID: {}, systemID: {}, baseURI: {} : {}",
            new Object[] { type, namespaceURI, publicId, systemId, baseURI, inputSource });
    return new Input(publicId, systemId, inputSource.getByteStream());
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLValidationService.java

public ServiceOutput invoke(ServerRequestContext context, ServiceInput input, ServiceType service,
        InvocationController invocationController, UserType user) throws RegistryException {

    ServerRequestContext outputContext = context;

    try {/*w w  w  . j a  v a  2s  .com*/
        //ExtrinsicObjectType eo = (ExtrinsicObjectType)input.getRegistryObject();
        //RepositoryItem repositoryItem = input.getRepositoryItem();
        //DataHandler dh = repositoryItem.getDataHandler();
        InputSource inputSource = null;

        //registryObject MUST be ExrinsicObject or ExternalLink of objectType WSDL
        ExtrinsicObjectType ebExtrinsicObjectType = null;
        ExternalLinkType ebExternalLinkType = null;
        RegistryObjectType ebRegistryObjectType = input.getRegistryObject();
        if (ebRegistryObjectType instanceof ExtrinsicObjectType) {
            ebExtrinsicObjectType = (ExtrinsicObjectType) ebRegistryObjectType;
            RepositoryItem repositoryItem = input.getRepositoryItem();
            if (repositoryItem == null) {
                // Section 8.10 of the [ebRS] spec specifies that the RI
                // is optional. Log message and return
                log.info(ServerResourceBundle.getInstance().getString("message.noRepositoryItemIncluded",
                        new String[] { ebRegistryObjectType.getId() }));
                ServiceOutput so = new ServiceOutput();
                so.setOutput(outputContext);
                return so;
            }
            inputSource = new InputSource(repositoryItem.getDataHandler().getInputStream());
        } else if (ebRegistryObjectType instanceof ExternalLinkType) {
            ebExternalLinkType = (ExternalLinkType) ebRegistryObjectType;
            String urlStr = ebExternalLinkType.getExternalURI();
            urlStr = Utility.absolutize(Utility.getFileOrURLName(urlStr));
            URL url = new URL(urlStr);
            InputStream is = url.openStream();
            inputSource = new InputSource(is);
        } else {
            throw new ValidationException("RegistryObject not ExtrinsicObject or ExternalLink");
        }

        StreamSource schematronInvControlFileSrc = rm.getAsStreamSource(invocationController.getEoId());
        //Commenting out caching until we figure out how to reinit the stream position at begining
        //Currently if we cache then subsequent uses result in error: "Could not compile stylesheet"
        // The schematron XSLT file is expected to be stable and change infrequently. So, cache it.
        //if (schematronXSLTFileSrc == null) {
        schematronXSLTFileSrc = new StreamSource(this.getClass().getClassLoader()
                .getResourceAsStream("it/cnr/icar/eric/server/cms/conf/skeleton1-5.xsl"));
        //}

        if (log.isDebugEnabled()) {
            dumpStream(schematronInvControlFileSrc);
            dumpStream(schematronXSLTFileSrc);
        }

        // Use the Schematron Invocation Control File and Schematron XSLT to
        // create the XSLT Invocation Control File
        File xsltInvocationControlFile = File.createTempFile("InvocationControlFile_WSDLValidation", ".xslt");
        xsltInvocationControlFile.deleteOnExit();
        StreamResult xsltInvocationControlFileSR = new StreamResult(xsltInvocationControlFile);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(schematronXSLTFileSrc);

        configureTransformer(transformer);

        // This call creates the XSLT Invocation Control File using
        // schematron invocation control file and schematron xslt files
        transformer.transform(schematronInvControlFileSrc, xsltInvocationControlFileSR);

        // Use generated XSLT Invocation Control File to validate the WSDL file(s)
        StreamSource xsltInvocationControlFileSrc = new StreamSource(xsltInvocationControlFile);
        transformer = tFactory.newTransformer(xsltInvocationControlFileSrc);

        configureTransformer(transformer);

        //Set respository item as parameter
        transformer.setParameter("repositoryItem", input.getRegistryObject().getId());

        if ((ebExtrinsicObjectType != null)
                && (ebExtrinsicObjectType.getMimeType().equalsIgnoreCase("application/zip"))) {
            ArrayList<File> files = Utility.unZip(TMP_DIR, inputSource.getByteStream());

            //Now iterate and create ExtrinsicObject - Repository Item pair for each unzipped file
            Iterator<File> iter = files.iterator();
            while (iter.hasNext()) {
                File file = iter.next();
                @SuppressWarnings("resource")
                BufferedReader br = new BufferedReader(new FileReader(file));
                StringBuffer sb = new StringBuffer();
                while (br.ready()) {
                    sb.append(br.readLine());
                }
                StringReader reader = new StringReader(sb.toString());
                StreamSource inputSrc = new StreamSource(reader);
                validateXMLFile(inputSrc, transformer);
            }
        } else {
            //Following will fail if there are unresolved imports in the WSDL
            StreamSource inputSrc = new StreamSource(inputSource.getByteStream());
            //dumpStream(inputSrc);
            //inputSrc = new StreamSource(inputSource.getByteStream());
            validateXMLFile(inputSrc, transformer);
        }
    } catch (ValidationException e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e);
        throw e;
    } catch (Exception e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e);
        throw new RegistryException(e);
    }

    ServiceOutput so = new ServiceOutput();
    so.setOutput(outputContext);

    if (outputContext != context) {
        outputContext.commit();
    }

    return so;
}

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 {/*from w w w.ja  va  2  s.c o  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("&", "&amp;");

                    // 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:org.apache.axis.SOAPPart.java

/**
 * Sets the content of the <CODE>SOAPEnvelope</CODE> object
 * with the data from the given <CODE>Source</CODE> object.
 * @param   source javax.xml.transform.Source</CODE> object with the data to
 *     be set//from  ww w  . j a va 2 s. co m
 * @throws  SOAPException if there is a problem in
 *     setting the source
 * @see #getContent() getContent()
 */
public void setContent(Source source) throws SOAPException {
    if (source == null)
        throw new SOAPException(Messages.getMessage("illegalArgumentException00"));

    // override the checks in HandlerChainImpl for JAXRPCHandler kludge
    MessageContext ctx = getMessage().getMessageContext();
    if (ctx != null) {
        ctx.setProperty(org.apache.axis.SOAPPart.ALLOW_FORM_OPTIMIZATION, Boolean.TRUE);
    }

    contentSource = source;
    InputSource in = org.apache.axis.utils.XMLUtils.sourceToInputSource(contentSource);
    InputStream is = in.getByteStream();
    if (is != null) {
        setCurrentMessage(is, FORM_INPUTSTREAM);
    } else {
        Reader r = in.getCharacterStream();
        if (r == null) {
            throw new SOAPException(Messages.getMessage("noCharacterOrByteStream"));
        }
        BufferedReader br = new BufferedReader(r);
        String line = null;
        StringBuffer sb = new StringBuffer();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new SOAPException(Messages.getMessage("couldNotReadFromCharStream"), e);
        }
        setCurrentMessage(sb.toString(), FORM_STRING);
    }
}

From source file:org.apache.axis.utils.XMLUtils.java

/**
 * Create a new document from the given URI, use the username and password
 * if the URI requires authentication.// w  w w. ja  v a  2s  . c  o  m
 * @param uri the resource to get
 * @param username basic auth username
 * @param password basic auth password
 * @throws ParserConfigurationException if construction problems occur
 * @throws SAXException if the document has xml sax problems
 * @throws IOException if i/o exceptions occur
 */
public static Document newDocument(String uri, String username, String password)
        throws ParserConfigurationException, SAXException, IOException {
    InputSource ins = XMLUtils.getInputSourceFromURI(uri, username, password);
    Document doc = XMLUtils.newDocument(ins);
    // Close the Stream
    if (ins.getByteStream() != null) {
        ins.getByteStream().close();
    } else if (ins.getCharacterStream() != null) {
        ins.getCharacterStream().close();
    }
    return doc;
}