Example usage for java.net URL getContent

List of usage examples for java.net URL getContent

Introduction

In this page you can find the example usage for java.net URL getContent.

Prototype

public final Object getContent() throws java.io.IOException 

Source Link

Document

Gets the contents of this URL.

Usage

From source file:org.motechproject.server.voxeo.IVRServiceImpl.java

@Override
public void initiateCall(CallRequest callRequest) {
    if (callRequest == null) {
        throw new IllegalArgumentException("CallRequest can not be null");
    }//from ww w .ja  v a 2s .  c o  m

    //Create a call record to track this call
    PhoneCall phoneCall = new PhoneCall(callRequest);
    phoneCall.setDirection(PhoneCall.Direction.OUTGOING);
    phoneCall.setDisposition(CallDetailRecord.Disposition.UNKNOWN);
    phoneCall.setStartDate(new Date());
    allPhoneCalls.add(phoneCall);

    String voxeoURL = "http://api.voxeo.net/SessionControl/CCXML10.start";
    String tokenId = "0cfbefecb166d741b9e54d043661a857d394f065d96c9d5416c2da4a0324a24e59b4a511a7450e15d50ecd59";
    String phonenum = "phonenum=" + callRequest.getPhone();
    String vxmlURL = "vxml=" + URLEncoder.encode(callRequest.getCallBackUrl());
    String externalId = "externalId=" + phoneCall.getId();

    if (0 != callRequest.getTimeOut()) {
        voxeoURL += "?tokenid=" + tokenId + "&" + phonenum + "&" + vxmlURL + "&" + externalId + "&timeout="
                + callRequest.getTimeOut() + "s" + "&cid=1234567890";
    } else {
        voxeoURL += "?tokenid=" + tokenId + "&" + phonenum + "&" + vxmlURL + "&" + externalId;
    }

    log.info("Initiating call to: " + callRequest.getPhone() + " VXML URL: " + callRequest.getCallBackUrl());
    log.info("Voxeo URL: " + voxeoURL);

    try {
        String line;
        String result = "";

        URL url = new URL(voxeoURL);

        BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) url.getContent()));
        while ((line = br.readLine()) != null)
            result += line;

        if (!"success".equals(result)) {
            log.error("Voxeo result: " + result);
            throw new CallInitiationException("Could not initiate call: non-success return from Voxeo");
        }
    } catch (MalformedURLException e) {
        log.error("MalformedURLException: ", e);
    } catch (Exception e) {
        log.error("Exception: ", e);
    }
}

From source file:org.apache.ofbiz.content.data.DataResourceWorker.java

public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale,
        Map<String, Object> templateContext, Delegator delegator, Appendable out, boolean cache)
        throws IOException, GeneralException {
    Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("context"));
    if (context == null) {
        context = new HashMap<String, Object>();
    }//from   w  w w.  j a v a  2  s  .  c  o  m
    String webSiteId = (String) templateContext.get("webSiteId");
    if (UtilValidate.isEmpty(webSiteId)) {
        if (context != null)
            webSiteId = (String) context.get("webSiteId");
    }

    String https = (String) templateContext.get("https");
    if (UtilValidate.isEmpty(https)) {
        if (context != null)
            https = (String) context.get("https");
    }

    String rootDir = (String) templateContext.get("rootDir");
    if (UtilValidate.isEmpty(rootDir)) {
        if (context != null)
            rootDir = (String) context.get("rootDir");
    }

    String dataResourceId = dataResource.getString("dataResourceId");
    String dataResourceTypeId = dataResource.getString("dataResourceTypeId");

    // default type
    if (UtilValidate.isEmpty(dataResourceTypeId)) {
        dataResourceTypeId = "SHORT_TEXT";
    }

    // text types
    if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) {
        String text = dataResource.getString("objectInfo");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
    } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
        GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText")
                .where("dataResourceId", dataResourceId).cache(cache).queryOne();
        if (electronicText != null) {
            String text = electronicText.getString("textData");
            writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
        }

        // object types
    } else if (dataResourceTypeId.endsWith("_OBJECT")) {
        String text = (String) dataResource.get("dataResourceId");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);

        // resource type
    } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
        String text = null;
        URL url = FlexibleLocation.resolveLocation(dataResource.getString("objectInfo"));

        if (url.getHost() != null) { // is absolute
            InputStream in = url.openStream();
            int c;
            StringWriter sw = new StringWriter();
            while ((c = in.read()) != -1) {
                sw.write(c);
            }
            sw.close();
            text = sw.toString();
        } else {
            String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
            String sep = "";
            if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
                sep = "/";
            }
            String fixedUrlStr = prefix + sep + url.toString();
            URL fixedUrl = new URL(fixedUrlStr);
            text = (String) fixedUrl.getContent();
        }
        out.append(text);

        // file types
    } else if (dataResourceTypeId.endsWith("_FILE_BIN")) {
        writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
    } else if (dataResourceTypeId.endsWith("_FILE")) {
        String dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
        String objectInfo = dataResource.getString("objectInfo");

        if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) {
            renderFile(dataResourceTypeId, objectInfo, rootDir, out);
        } else {
            writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
        }
    } else {
        throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId
                + "] is not supported in renderDataResourceAsText");
    }
}

From source file:org.ofbiz.content.data.DataResourceWorker.java

public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale,
        Map<String, Object> templateContext, Delegator delegator, Appendable out, boolean cache)
        throws IOException, GeneralException {
    Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("context"));
    if (context == null) {
        context = FastMap.newInstance();
    }//w w w  . j  a  v  a2  s  .  c o m
    String webSiteId = (String) templateContext.get("webSiteId");
    if (UtilValidate.isEmpty(webSiteId)) {
        if (context != null)
            webSiteId = (String) context.get("webSiteId");
    }

    String https = (String) templateContext.get("https");
    if (UtilValidate.isEmpty(https)) {
        if (context != null)
            https = (String) context.get("https");
    }

    String rootDir = (String) templateContext.get("rootDir");
    if (UtilValidate.isEmpty(rootDir)) {
        if (context != null)
            rootDir = (String) context.get("rootDir");
    }

    String dataResourceId = dataResource.getString("dataResourceId");
    String dataResourceTypeId = dataResource.getString("dataResourceTypeId");

    // default type
    if (UtilValidate.isEmpty(dataResourceTypeId)) {
        dataResourceTypeId = "SHORT_TEXT";
    }

    // text types
    if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) {
        String text = dataResource.getString("objectInfo");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
    } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
        GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText")
                .where("dataResourceId", dataResourceId).cache(cache).queryOne();
        if (electronicText != null) {
            String text = electronicText.getString("textData");
            writeText(dataResource, text, templateContext, mimeTypeId, locale, out);
        }

        // object types
    } else if (dataResourceTypeId.endsWith("_OBJECT")) {
        String text = (String) dataResource.get("dataResourceId");
        writeText(dataResource, text, templateContext, mimeTypeId, locale, out);

        // resource type
    } else if (dataResourceTypeId.equals("URL_RESOURCE")) {
        String text = null;
        URL url = FlexibleLocation.resolveLocation(dataResource.getString("objectInfo"));

        if (url.getHost() != null) { // is absolute
            InputStream in = url.openStream();
            int c;
            StringWriter sw = new StringWriter();
            while ((c = in.read()) != -1) {
                sw.write(c);
            }
            sw.close();
            text = sw.toString();
        } else {
            String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
            String sep = "";
            if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
                sep = "/";
            }
            String fixedUrlStr = prefix + sep + url.toString();
            URL fixedUrl = new URL(fixedUrlStr);
            text = (String) fixedUrl.getContent();
        }
        out.append(text);

        // file types
    } else if (dataResourceTypeId.endsWith("_FILE_BIN")) {
        writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
    } else if (dataResourceTypeId.endsWith("_FILE")) {
        String dataResourceMimeTypeId = dataResource.getString("mimeTypeId");
        String objectInfo = dataResource.getString("objectInfo");

        if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) {
            renderFile(dataResourceTypeId, objectInfo, rootDir, out);
        } else {
            writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out);
        }
    } else {
        throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId
                + "] is not supported in renderDataResourceAsText");
    }
}

From source file:service.GoEuroServiceImpl.java

@Override
public List<GoEuroModel> convertJsonDataToModel(String cityName) {
    String completeUrl = URL_SOURCE + cityName;
    List<GoEuroModel> goEuroModels = new LinkedList<>();
    try {/* w ww.ja v  a 2  s . co  m*/
        URL url = new URL(completeUrl);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setDoInput(true);
        if (url.getContent() != null) {
            InputStream is = url.openStream();
            String jsonData = getJsonData(new BufferedReader(new InputStreamReader(is)));
            JSONArray jsonArray = new JSONArray(jsonData);
            int jsonArrayLength = jsonArray.length();

            for (int i = 0; i < jsonArrayLength; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                GoEuroModel goEuroModel = new GoEuroModel();
                goEuroModel.set_id(Long.parseLong(jsonObject.get(ID).toString()));
                goEuroModel.setName(jsonObject.get(NAME).toString());
                goEuroModel.setType(jsonObject.get(TYPE).toString());
                goEuroModel.setLatitude(Double
                        .parseDouble(jsonObject.get(GEO_POSITION).toString().split(COMMA)[ZERO_INDEX_POSITION]
                                .split(COLON)[ONE_INDEX_POSITION]));
                goEuroModel.setLongitude(Double
                        .parseDouble(jsonObject.get(GEO_POSITION).toString().split(COMMA)[ONE_INDEX_POSITION]
                                .split(COLON)[ONE_INDEX_POSITION]
                                        .split(CLOSING_CURLY_BRACE)[ZERO_INDEX_POSITION]));
                goEuroModels.add(goEuroModel);
            }
        }
    } catch (MalformedURLException e) {
        throw new GoEuroException(e.getMessage());
    } catch (IOException | JSONException e) {
        throw new GoEuroException(e.getMessage());
    }
    return goEuroModels;
}

From source file:de.mirkosertic.desktopsearch.DesktopSearch.java

@Override
public void start(Stage aStage) throws Exception {

    // This is our base directory
    File theBaseDirectory = new File(SystemUtils.getUserHome(), "FreeSearchIndexDir");
    theBaseDirectory.mkdirs();/*from www  . j a va 2 s.  co  m*/

    configurationManager = new ConfigurationManager(theBaseDirectory);

    Notifier theNotifier = new Notifier();

    stage = aStage;

    // Create the known preview processors
    PreviewProcessor thePreviewProcessor = new PreviewProcessor();

    try {
        // Boot the search backend and set it up for listening to configuration changes
        backend = new Backend(theNotifier, configurationManager.getConfiguration(), thePreviewProcessor);
        configurationManager.addChangeListener(backend);

        // Boot embedded JSP container
        embeddedWebServer = new FrontendEmbeddedWebServer(aStage, backend, thePreviewProcessor,
                configurationManager);

        embeddedWebServer.start();
    } catch (BindException | LockReleaseFailedException | LockObtainFailedException e) {
        // In this case, there is already an instance of DesktopSearch running
        // Inform the instance to bring it to front end terminate the current process.
        URL theURL = new URL(FrontendEmbeddedWebServer.getBringToFrontUrl());
        // Retrieve the content, but it can be safely ignored
        // There must only be the get request
        Object theContent = theURL.getContent();

        // Terminate the JVM. The window of the running instance is visible now.
        System.exit(0);
    }

    aStage.setTitle("Free Desktop Search");
    aStage.setWidth(800);
    aStage.setHeight(600);
    aStage.initStyle(StageStyle.TRANSPARENT);

    FXMLLoader theLoader = new FXMLLoader(getClass().getResource("/scenes/mainscreen.fxml"));
    AnchorPane theMainScene = theLoader.load();

    final DesktopSearchController theController = theLoader.getController();
    theController.configure(this, backend, FrontendEmbeddedWebServer.getSearchUrl(), stage.getOwner());

    Undecorator theUndecorator = new Undecorator(stage, theMainScene);
    theUndecorator.getStylesheets().add("/skin/undecorator.css");

    Scene theScene = new Scene(theUndecorator);

    // Hacky, but works...
    theUndecorator.setStyle("-fx-background-color: rgba(0, 0, 0, 0);");

    theScene.setFill(Color.TRANSPARENT);
    aStage.setScene(theScene);

    aStage.getIcons().add(new Image(getClass().getResourceAsStream("/fds.png")));

    if (SystemTray.isSupported()) {
        Platform.setImplicitExit(false);
        SystemTray theTray = SystemTray.getSystemTray();

        // We need to reformat the icon according to the current tray icon dimensions
        // this depends on the underlying OS
        java.awt.Image theTrayIconImage = Toolkit.getDefaultToolkit()
                .getImage(getClass().getResource("/fds_small.png"));
        int trayIconWidth = new TrayIcon(theTrayIconImage).getSize().width;
        TrayIcon theTrayIcon = new TrayIcon(
                theTrayIconImage.getScaledInstance(trayIconWidth, -1, java.awt.Image.SCALE_SMOOTH),
                "Free Desktop Search");
        theTrayIcon.setImageAutoSize(true);
        theTrayIcon.setToolTip("FXDesktopSearch");
        theTrayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    Platform.runLater(() -> {
                        if (stage.isIconified()) {
                            stage.setIconified(false);
                        }
                        stage.show();
                        stage.toFront();
                    });
                }
            }
        });
        theTray.add(theTrayIcon);

        aStage.setOnCloseRequest(aEvent -> stage.hide());
    } else {

        aStage.setOnCloseRequest(aEvent -> shutdown());
    }

    aStage.setMaximized(true);
    aStage.show();
}

From source file:org.jboss.test.classloader.test.ScopingUnitTestCase.java

/** Test the ability to override the server classes with war local versions
 * of xml parser classes./*from  w w  w  .  j a v a 2  s  . co m*/
 * This test is invalid as of jdk1.4+ due to the bundling of the xerces
 * parser with the jdk
 */
public void badtestWarXmlOverrides() throws Exception {
    getLog().debug("+++ testWarOverrides");
    try {
        deploy("oldxerces.war");
        URL servletURL = new URL("http://" + getServerHost() + ":8080/oldxerces/");
        InputStream reply = (InputStream) servletURL.getContent();
        getLog().debug("Accessed http://" + getServerHost() + ":8080/oldxerces/");
        logReply(reply);
    } catch (Exception e) {
        getLog().info("Failed to access oldxerces.war", e);
        throw e;
    } finally {
        undeploy("oldxerces.war");
    }
}

From source file:org.jboss.test.classloader.test.ScopingUnitTestCase.java

/** Test the interaction through jndi of a service which binds a custom
 * object into jndi and a servlet which looks up the custom object when
 * the service and servlet have different class loader scopes that both
 * have the custom object. //from w  ww . j ava 2  s . co  m
 */
public void testSharedJNDI() throws Exception {
    getLog().debug("+++ testSharedJNDI");
    try {
        deploy("shared-jndi.sar");
        deploy("shared-jndi.war");
        URL servletURL = new URL("http://" + getServerHost() + ":8080/shared-jndi/LookupServlet");
        InputStream reply = (InputStream) servletURL.getContent();
        getLog().debug("Accessed: " + servletURL);
        logReply(reply);
    } catch (Exception e) {
        getLog().info("Failed to access LookupServlet", e);
        throw e;
    } finally {
        undeploy("shared-jndi.war");
        undeploy("shared-jndi.sar");
    }
}

From source file:com.facebook.samples.musicdashboard.MusicGalleryFragment.java

private Object fetch(String address) throws MalformedURLException, IOException {
    URL url = new URL(address);
    Object content = url.getContent();
    return content;
}

From source file:org.jboss.test.classloader.test.ScopingUnitTestCase.java

/** Test the ability to override the server classes with war local versions
 * of log4j classes/*from   w w  w.  ja  va  2 s  .co m*/
 */
public void testWarLog4jOverrides() throws Exception {
    getLog().debug("+++ testWarOverrides");
    try {
        deploy("log4j113.war");
        URL log4jServletURL = new URL("http://" + getServerHost() + ":8080/log4j113/Log4jServlet/");
        InputStream reply = (InputStream) log4jServletURL.getContent();
        getLog().debug("Accessed http://" + getServerHost() + ":8080/log4j113/Log4jServlet/");
        logReply(reply);

        URL encServletURL = new URL("http://" + getServerHost() + ":8080/log4j113/ENCServlet/");
        reply = (InputStream) encServletURL.getContent();
        getLog().debug("Accessed http://" + getServerHost() + ":8080/log4j113/ENCServlet/");
        logReply(reply);
    } catch (Exception e) {
        getLog().info("Failed to access Log4jServlet in log4j113.war", e);
        throw e;
    } finally {
        undeploy("log4j113.war");
    }
}

From source file:org.jboss.test.classloader.test.ScopingUnitTestCase.java

/** Test the ability to override the server classes with war local versions
 * of log4j classes when using commons-logging.
 *///from w w w.ja v a2  s.c  o m
public void testWarCommonsLoggingLog4jOverrides() throws Exception {
    getLog().debug("+++ testWarCommonsLoggingLog4jOverrides");
    try {
        deploy("common-logging.war");
        URL log4jServletURL = new URL("http://" + getServerHost() + ":8080/common-logging/Log4jServlet/");
        InputStream reply = (InputStream) log4jServletURL.getContent();
        getLog().debug("Accessed http://" + getServerHost() + ":8080/common-logging/Log4jServlet/");
        logReply(reply);
    } catch (Exception e) {
        getLog().info("Failed to access Log4jServlet in common-logging.war", e);
        throw e;
    } finally {
        undeploy("common-logging.war");
    }
}